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.d.ts b/addons/Dexie.Observable/dist/dexie-observable.d.ts new file mode 100644 index 000000000..73dafe6eb --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.d.ts @@ -0,0 +1,120 @@ +// Type definitions for dexie-observable v1.0.0-beta.8 +// Project: https://github.com/dfahlander/Dexie.js/tree/master/addons/Dexie.Observable +// Definitions by: David Fahlander + +import Dexie from 'dexie'; +import { IDatabaseChange } from '../api'; + +// +// Extend Dexie interface +// +declare module 'dexie' { + // Extend methods on db (db.sendMessage(), ...) + interface Dexie { + // Placeholder where to access the SyncNode class constructor. + // (makes it valid to do new db.observable.SyncNode()) + observable: { + SyncNode: Dexie.Observable.SyncNodeConstructor; + sendMessage( + type: string, // Don't use 'response' as it is used internally by the framework + message: any, // anything that can be saved by IndexedDB + destinationNode: number, + options: { + wantReply?: boolean; + } + ): Promise | void; // When wantReply is undefined or false return is void + + broadcastMessage( + type: string, + message: any, // anything that can be saved by IndexedDB + bIncludeSelf: boolean + ): void; + } + + readonly _localSyncNode: Dexie.Observable.SyncNode; + + _changes: Dexie.Table; + _syncNodes: Dexie.Table; + _intercomm: Dexie.Table; + } + + module Dexie { + // Extended events db.on('changes', subscriber), ... + interface DbEvents { + (eventName: 'changes', subscriber: (changes: IDatabaseChange[], partial: boolean)=>void): void; + (eventName: 'cleanup', subscriber: ()=>any): void; + (eventName: 'message', subscriber: (msg: Dexie.Observable.MessageEvent)=>any): void; + } + + // Extended IndexSpec with uuid boolean for primary key. + interface IndexSpec { + uuid: boolean; + } + + var Observable: { + (db: Dexie) : void; + + // + // + // + createUUID: () => string; + on: Observable.ObservableEventSet; + localStorageImpl: { + setItem(key: string, value: string): void, + getItem(key: string): string, + removeItem(key: string): void; + }; + _onStorage: (event: StorageEvent) => void; + } + + // + // Define Dexie.Observable + // + module Observable { + // + // Interfaces of Dexie.Observable + // + + interface SyncNodeConstructor { + new() : SyncNode; + } + + /** + * A SyncNode represents a local database instance that subscribes + * to changes made on the database. + * SyncNodes are stored in the _syncNodes table. + * + * Dexie.Syncable extends this interface and allows 'remote' nodes to be stored + * as well. + */ + interface SyncNode { + id?: number, + myRevision: number, + type: 'local' | '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. + isMaster: number // 1 if true. Not using Boolean because it's not possible to index Booleans. + } + + interface ObservableEventSet extends Dexie.DexieEventSet { + (eventName: 'latestRevisionIncremented', subscriber: (dbName: string, latestRevision: number) => void): void; + (eventName: 'suicideNurseCall', subscriber: (dbName: string, nodeID: number) => void): void; + (eventName: 'intercomm', subscriber: (dbName: string) => void): void; + (eventName: 'beforeunload', subscriber: () => void): void; + } + + // Object received by on('message') after sendMessage() or broadcastMessage() + interface MessageEvent { + id: number; + type: string; + message: any; + destinationNode: number; + wantReply?: boolean; + resolve(result: any): void; + reject(error: any): void; + } + } + } +} + +export default Dexie.Observable; diff --git a/addons/Dexie.Observable/dist/dexie-observable.es.js b/addons/Dexie.Observable/dist/dexie-observable.es.js new file mode 100644 index 000000000..2a9da7612 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js @@ -0,0 +1,990 @@ +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; + +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); + }; +} +function createUUID() { + // 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; +} + +function initOverrideCreateTransaction(db, wakeupObservers) { + return function overrideCreateTransaction(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; + }; + }; +} + +function initWakeupObservers(db, Observable, localStorage) { + return 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. + if (localStorage) + 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. + } + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function initCreatingHook(db, table) { + return function creatingHook(primKey, obj, trans) { + /// + var rv = undefined; + if (primKey === undefined && table.schema.primKey.uuid) { + primKey = rv = createUUID(); + if (table.schema.primKey.keyPath) { + Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey); + } + } + var change = { + source: trans.source || null, + table: table.name, + 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 () { + // 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; + }; +} + +function initUpdatingHook(db, tableName) { + return function updatingHook(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 wouldn't 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, + 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 () { + // 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); + }); + }; + } + }; +} + +function initDeletingHook(db, tableName) { + return function deletingHook(primKey, obj, trans) { + /// + var promise = db._changes.add({ + source: trans.source || null, + table: tableName, + key: primKey, + type: DELETE, + oldObj: obj + }).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }) + .catch(function (e) { + console.log(obj); + console.log(e.stack); + }); + 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); + }); + }; + }; +} + +function initCrudMonitor(db) { + // + // The Creating/Updating/Deleting hook will make sure any change is stored to the changes table + // + return function crudMonitor(table) { + /// + if (table.hook._observing) + return; + table.hook._observing = true; + var tableName = table.name; + table.hook('creating').subscribe(initCreatingHook(db, table)); + table.hook('updating').subscribe(initUpdatingHook(db, tableName)); + table.hook('deleting').subscribe(initDeletingHook(db, tableName)); + }; +} + +function initOnStorage(Observable) { + return 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 && 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); + } + } + } + }; +} + +function initOverrideOpen(db, SyncNode, crudMonitor) { + return function overrideOpen(origOpen) { + return function () { + // + // Make sure to subscribe to "creating", "updating" and "deleting" hooks for all observable tables that were created in the stores() method. + // + Object.keys(db._allTables).forEach(function (tableName) { + var table = db._allTables[tableName]; + if (table.schema.observable) { + crudMonitor(table); + } + if (table.name === "_syncNodes") { + table.mapToClass(SyncNode); + } + }); + return origOpen.apply(this, arguments); + }; + }; +} + +var Promise = Dexie.Promise; +function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) { + // + // Intercommunication between nodes + // + // Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable) + var requestsWaitingForReply = {}; + /** + * @param {string} type Type of message + * @param message Message to send + * @param {number} destinationNode ID of destination node + * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent. + */ + db.observable.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. + options = options || {}; + if (!mySyncNode.node) + return options.wantReply ? + Promise.reject(new Dexie.DatabaseClosedError()) : + Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either. + var msg = { message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type }; + Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ... + return Dexie.ignoreTransaction(function () { + var tables = ["_intercomm"]; + if (options.wantReply) + tables.push("_syncNodes"); // If caller wants a reply, include "_syncNodes" in transaction to check that there's a receiver there. Otherwise, new master will get it. + var promise = db.transaction('rw', tables, function () { + if (options.wantReply) { + // Check that there is a receiver there to take the request. + return db._syncNodes.where('id').equals(destinationNode).count(function (receiverAlive) { + if (receiverAlive) + return db._intercomm.add(msg); + else // If we couldn't find a node -> send to master + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + msg.destinationNode = masterNode.id; + return db._intercomm.add(msg); + }); + }); + } + else { + // If caller doesn't need a response, we don't have to make sure that it gets one. + return db._intercomm.add(msg); + } + }).then(function (messageId) { + var rv = null; + if (options.wantReply) { + rv = new Promise(function (resolve, reject) { + requestsWaitingForReply[messageId.toString()] = { resolve: resolve, reject: reject }; + }); + } + if (localStorage) { + localStorage.setItem("Dexie.Observable/intercomm/" + db.name, messageId.toString()); + } + Observable.on.intercomm.fire(db.name); + return rv; + }); + if (!options.wantReply) { + promise.catch(function () { + }); + return; + } + else { + // Forward rejection to caller if it waits for reply. + return promise; + } + }); + }; + // Send a message to all local _syncNodes + db.observable.broadcastMessage = function (type, message, bIncludeSelf) { + if (!mySyncNode.node) + return; + var mySyncNodeId = mySyncNode.node.id; + Dexie.ignoreTransaction(function () { + db._syncNodes.toArray(function (nodes) { + return Promise.all(nodes + .filter(function (node) { return node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId); }) + .map(function (node) { return db.observable.sendMessage(type, message, node.id); })); + }).catch(function () { + }); + }); + }; + function consumeIntercommMessages() { + // Check if we got messages: + if (!mySyncNode.node) + return Promise.reject(new Dexie.DatabaseClosedError()); + return Dexie.ignoreTransaction(function () { + return db.transaction('rw', '_intercomm', function () { + return db._intercomm.where({ destinationNode: mySyncNode.node.id }).toArray(function (messages) { + messages.forEach(function (msg) { return consumeMessage(msg); }); + return db._intercomm.where('id').anyOf(messages.map(function (msg) { return msg.id; })).delete(); + }); + }); + }); + } + function consumeMessage(msg) { + if (msg.type === 'response') { + // This is a response. Lookup pending request and fulfill its 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.observable.sendMessage('response', { result: result }, msg.sender, { requestId: msg.id }); + }; + msg.reject = function (error) { + db.observable.sendMessage('response', { error: error.toString() }, msg.sender, { isFailure: true, requestId: msg.id }); + }; + db.on.message.fire(msg); + } + } + // Listener for 'intercomm' events + // Gets fired when we get a 'storage' event from local storage or when sendMessage is called + // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event) + // sendMessage is used to communicate in the same tab and to trigger a storage event + function onIntercomm(dbname) { + // When storage event trigger us to check + if (dbname === db.name) { + consumeIntercommMessages().catch('DatabaseClosedError', function () { }); + } + } + return { + onIntercomm: onIntercomm, + consumeIntercommMessages: consumeIntercommMessages + }; +} + +function overrideParseStoresSpec(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; + } + }); + }; +} + +function deleteOldChanges(db) { + // This is a background job and should never be done within + // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that. + // We should not return the Promise but catch it ourselves instead. + // To prohibit starving the database we want to lock transactions as short as possible + // and since we're not in a hurry, we could do this job in chunks and reschedule a + // continuation every 500 ms. + var CHUNK_SIZE = 100; + Dexie.ignoreTransaction(function () { + return db._syncNodes.orderBy("myRevision").first(function (oldestNode) { + return db._changes + .where("rev").below(oldestNode.myRevision) + .limit(CHUNK_SIZE) + .primaryKeys(); + }).then(function (keysToDelete) { + if (keysToDelete.length === 0) + return; // Done. + return db._changes.bulkDelete(keysToDelete).then(function () { + // If not done garbage collecting, reschedule a continuation of it until done. + if (keysToDelete.length === CHUNK_SIZE) { + // Limit reached. Changes are there are more job to do. Schedule again: + setTimeout(function () { return db.isOpen() && deleteOldChanges(db); }, 500); + } + }); + }); + }).catch(function () { + // The operation is not crucial. A failure could almost only be due to that database has been closed. + // No need to log this. + }); +} + +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +var global = self; +/** class DatabaseChange + * + * Object contained by the _changes table. + */ +var DatabaseChange = Dexie.defineClass({ + rev: Number, + source: String, + table: String, + key: Object, + type: Number, + obj: Object, + mods: 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$1 = 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 = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event. + HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000; + var localStorage = Observable.localStorageImpl; + /** class SyncNode + * + * Object contained in the _syncNodes table. + */ + var SyncNode = Dexie.defineClass({ + //id: Number, + myRevision: Number, + type: String, + lastHeartBeat: Number, + deleteTimeStamp: Number, + url: String, + isMaster: Number, + // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == "remote"): + syncProtocol: String, + syncContext: null, + syncOptions: Object, + connected: false, + status: Number, + appliedRemoteRevision: null, + remoteBaseRevisions: [{ local: Number, remote: null }], + dbUploadState: { + tablesToUpload: [String], + currentTable: String, + currentKey: null, + localBaseRevision: Number + } + }); + db.observable = {}; + db.observable.SyncNode = SyncNode; + var wakeupObservers = initWakeupObservers(db, Observable, localStorage); + var overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers); + var crudMonitor = initCrudMonitor(db); + var overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor); + var mySyncNode = { node: null }; + var intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage); + var onIntercomm = intercomm.onIntercomm; + var consumeIntercommMessages = intercomm.consumeIntercommMessages; + // Allow other addons to access the local sync node. May be needed by Dexie.Syncable. + Object.defineProperty(db, "_localSyncNode", { + get: function () { return mySyncNode.node; } + }); + var pollHandle = null, heartbeatHandle = 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.node = new SyncNode({ + myRevision: 0, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null + }); + } + // + // Override parsing the stores to add "_changes" and "_syncNodes" tables. + // It also adds UUID support for the primary key and sets tables as observable tables. + // + db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec); + // changes event on db: + db.on.addEventType({ + changes: 'asap', + cleanup: [promisableChain, nop], + message: 'asap' + }); + // + // Override transaction creation to always include the "_changes" store when any observable store is involved. + // + db._createTransaction = override(db._createTransaction, overrideCreateTransaction); + // 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; + // + // Override open to setup hooks for db changes and map the _syncNodes table to class + // + db.open = override(db.open, overrideOpen); + 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.node && mySyncNode.node.id) { + Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id); + // Inform other windows as well: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now. + mySyncNode.node = null; + } + if (pollHandle) + clearTimeout(pollHandle); + pollHandle = null; + if (heartbeatHandle) + clearTimeout(heartbeatHandle); + heartbeatHandle = 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; + }); + }; + }); + // 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.node = 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 () { + return db._syncNodes + .where('isMaster').equals(1) + .first(function (currentMaster) { + if (!currentMaster) { + // There's no master. We must be the master + mySyncNode.node.isMaster = 1; + } + else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Master have been inactive for too long + // Take over mastership + mySyncNode.node.isMaster = 1; + currentMaster.isMaster = 0; + return db._syncNodes.put(currentMaster); + } + }).then(function () { + // Add our node to DB and start subscribing to events + return db._syncNodes.add(mySyncNode.node).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); + // Start heartbeat + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + }); + }); + }).then(function () { + 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 () { + // 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.node; // 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$1.reject(new Dexie.DatabaseClosedError()); + } + 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); + } + var ourNodeStillExists = false; + return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(function (syncNode) { + ourNodeStillExists = true; + syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!) + syncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision); + }).then(function () { return ourNodeStillExists; }); + }).then(function (ourNodeStillExists) { + if (!ourNodeStillExists) { + // 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; + } + /** + * The reason we need heartbeat in parallell with poll() is due to the risk of long-running + * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will + * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on + * during that changes are being applied and update our lastHeartBeat property while poll() is waiting. + * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this + * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction. + * + * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT + * (20 seconds), another node waking up after the sync would kill the master node and take over because + * it would believe it was dead. + */ + function heartbeat() { + heartbeatHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + db.transaction('rw!', db._syncNodes, function () { + db._syncNodes.where({ id: currentInstance }).first(function (ourSyncNode) { + if (!ourSyncNode) { + // We do not exist anymore. Call db.close() to teardown polls etc. + if (db.isOpen()) + db.close(); + return; + } + ourSyncNode.lastHeartBeat = Date.now(); + ourSyncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + return db._syncNodes.put(ourSyncNode); + }); + }).catch('DatabaseClosedError', function () { + // Ignore silently + }).finally(function () { + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + } + }); + } + function poll() { + pollHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + Dexie.vip(function () { + readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages) + .catch('DatabaseClosedError', function () { + // 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. + }) + .finally(function () { + // Poll again in given interval: + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + pollHandle = setTimeout(poll, LOCAL_POLL); + } + }); + }); + } + function cleanup() { + var ourSyncNode = mySyncNode.node; + if (!ourSyncNode) + return Promise$1.reject(new Dexie.DatabaseClosedError()); + 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).filter(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.) + if (localStorage) { + 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. + // Those that waits for reply should be redirected to us. + db._intercomm.where({ destinationNode: node.id }).modify(function (msg) { + if (msg.wantReply) + msg.destinationNode = ourSyncNode.id; + else + // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request. + delete this.value; + }); + } + 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() { + // Mark our own sync node for deletion. + if (!mySyncNode.node) + return; + browserIsShuttingDown = true; + mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // 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: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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); + }); + } + } +} +// +// 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 = createUUID; +Observable.deleteOldChanges = deleteOldChanges; +Observable._onStorage = initOnStorage(Observable); +Observable._onBeforeUnload = function () { + Observable.on.beforeunload.fire(); +}; +try { + Observable.localStorageImpl = global.localStorage; +} +catch (ex) { } +// +// 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); + +export default Observable; +//# sourceMappingURL=dexie-observable.es.js.map diff --git a/addons/Dexie.Observable/dist/dexie-observable.es.js.map b/addons/Dexie.Observable/dist/dexie-observable.es.js.map new file mode 100644 index 000000000..88eea1b3f --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-observable.es.js","sources":["../src/utils.js","../src/override-create-transaction.js","../src/wakeup-observers.js","../src/change_types.js","../src/hooks/creating.js","../src/hooks/updating.js","../src/hooks/deleting.js","../src/hooks/crud-monitor.js","../src/on-storage.js","../src/override-open.js","../src/intercomm.js","../src/override-parse-stores-spec.js","../src/delete-old-changes.js","../src/Dexie.Observable.js"],"sourcesContent":["export function nop() {}\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, args = arguments;\n return res.then(function() {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nexport function createUUID() {\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","export default function initOverrideCreateTransaction(db, wakeupObservers) {\n return function overrideCreateTransaction(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)\n 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(\n trans._lastWrittenRevision,\n 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","import Dexie from 'dexie';\n\nexport default function initWakeupObservers(db, Observable, localStorage) {\n return 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 if (localStorage) 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","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nimport {CREATE} from '../change_types';\nimport {createUUID} from '../utils';\n\nexport default function initCreatingHook(db, table) {\n return function creatingHook(primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = 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: table.name,\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)\n promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n\n this.onerror = function () {\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","import Dexie from 'dexie';\n\nimport {UPDATE} from '../change_types';\n\nexport default function initUpdatingHook(db, tableName) {\n return function updatingHook(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 wouldn't 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 () {\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","import {DELETE} from '../change_types';\n\nexport default function initDeletingHook(db, tableName) {\n return function deletingHook(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 .catch((e) => {\n console.log(obj)\n console.log(e.stack)\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","import initCreatingHook from './creating';\nimport initUpdatingHook from './updating';\nimport initDeletingHook from './deleting';\n\nexport default function initCrudMonitor(db) {\n//\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n//\n return function crudMonitor(table) {\n /// \n if (table.hook._observing) return;\n table.hook._observing = true;\n\n const tableName = table.name;\n table.hook('creating').subscribe(initCreatingHook(db, table));\n\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\n\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initOnStorage(Observable) {\n return 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 && event.key.indexOf(\"Dexie.Observable/\") === 0) { // 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}\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\n return function overrideOpen(origOpen) {\n return function () {\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 Object.keys(db._allTables).forEach(tableName => {\n let table = db._allTables[tableName];\n if (table.schema.observable) {\n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\") {\n table.mapToClass(SyncNode);\n }\n });\n return origOpen.apply(this, arguments);\n }\n };\n}\n","import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\n//\n// Intercommunication between nodes\n//\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\n\n var requestsWaitingForReply = {};\n\n /**\n * @param {string} type Type of message\n * @param message Message to send\n * @param {number} destinationNode ID of destination node\n * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n */\n db.observable.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 options = options || {};\n if (!mySyncNode.node)\n return options.wantReply ?\n Promise.reject(new Dexie.DatabaseClosedError()) :\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\n\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n return Dexie.ignoreTransaction(()=> {\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 receiver there. Otherwise, new master will get it.\n var promise = db.transaction('rw', tables, () => {\n if (options.wantReply) {\n // Check that there is a receiver there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\n if (receiverAlive)\n return db._intercomm.add(msg);\n else // If we couldn't find a node -> send to master\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return db._intercomm.add(msg)\n });\n });\n } else {\n // If caller doesn't need a response, we don't have to make sure that it gets one.\n return db._intercomm.add(msg);\n }\n }).then(messageId => {\n var rv = null;\n if (options.wantReply) {\n rv = new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\n });\n }\n if (localStorage) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n }\n Observable.on.intercomm.fire(db.name);\n return rv;\n });\n\n if (!options.wantReply) {\n promise.catch(()=> {\n });\n return;\n } else {\n // Forward rejection to caller if it waits for reply.\n return promise;\n }\n });\n };\n\n // Send a message to all local _syncNodes\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode.node) return;\n var mySyncNodeId = mySyncNode.node.id;\n Dexie.ignoreTransaction(()=> {\n db._syncNodes.toArray(nodes => {\n return Promise.all(nodes\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\n .map(node => db.observable.sendMessage(type, message, node.id)));\n }).catch(()=> {\n });\n });\n };\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\n\n return Dexie.ignoreTransaction(()=> {\n return db.transaction('rw', '_intercomm', function() {\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\n messages.forEach(msg => consumeMessage(msg));\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\n });\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill its 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.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\n };\n msg.reject = function (error) {\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\n };\n db.on.message.fire(msg);\n }\n }\n\n // Listener for 'intercomm' events\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\n // sendMessage is used to communicate in the same tab and to trigger a storage event\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\n }\n }\n\n return {\n onIntercomm,\n consumeIntercommMessages\n };\n}\n","export default function overrideParseStoresSpec(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","import Dexie from 'dexie';\n\nexport default function deleteOldChanges(db) {\n // This is a background job and should never be done within\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\n // We should not return the Promise but catch it ourselves instead.\n\n // To prohibit starving the database we want to lock transactions as short as possible\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\n // continuation every 500 ms.\n const CHUNK_SIZE = 100;\n\n Dexie.ignoreTransaction(()=>{\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\n return db._changes\n .where(\"rev\").below(oldestNode.myRevision)\n .limit(CHUNK_SIZE)\n .primaryKeys();\n }).then(keysToDelete => {\n if (keysToDelete.length === 0) return; // Done.\n return db._changes.bulkDelete(keysToDelete).then(()=> {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (keysToDelete.length === CHUNK_SIZE) {\n // Limit reached. Changes are there are more job to do. Schedule again:\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\n }\n });\n });\n }).catch(()=>{\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\n // No need to log this.\n });\n}\n","/* ========================================================================== \n * dexie-observable.js\n * ==========================================================================\n *\n * Dexie addon for observing database changes not just on local db instance\n * but also on other instances, tabs and windows.\n *\n * Comprises a base framework for dexie-syncable.js\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\nimport Dexie from 'dexie';\nimport { nop, promisableChain, createUUID } from './utils';\n\nimport initOverrideCreateTransaction from './override-create-transaction';\nimport initWakeupObservers from './wakeup-observers';\nimport initCrudMonitor from './hooks/crud-monitor';\nimport initOnStorage from './on-storage';\nimport initOverrideOpen from './override-open';\nimport initIntercomm from './intercomm';\n\nimport overrideParseStoresSpec from './override-parse-stores-spec';\n\nimport deleteOldChanges from './delete-old-changes';\n\nvar global = self;\n\n/** class DatabaseChange\n *\n * Object contained by the _changes table.\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, // 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, // 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 = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event.\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\n *\n * Object contained in the _syncNodes table.\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 db.observable = {};\n db.observable.SyncNode = SyncNode;\n\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\n const crudMonitor = initCrudMonitor(db);\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\n\n var mySyncNode = {node: null};\n\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\n const onIntercomm = intercomm.onIntercomm;\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\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() { return mySyncNode.node; }\n });\n\n var pollHandle = null,\n heartbeatHandle = 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.node = 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 // It also adds UUID support for the primary key and sets tables as observable tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\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 // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\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 //\n // Override open to setup hooks for db changes and map the _syncNodes table to class\n //\n db.open = override(db.open, overrideOpen);\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.node && mySyncNode.node.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\n // Inform other windows as well:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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 }\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode.node = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\n heartbeatHandle = 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 // 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 \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.node = 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', () => {\n return db._syncNodes\n .where('isMaster').equals(1)\n .first(currentMaster => {\n if (!currentMaster) {\n // There's no master. We must be the master\n mySyncNode.node.isMaster = 1;\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Master have been inactive for too long\n // Take over mastership\n mySyncNode.node.isMaster = 1;\n currentMaster.isMaster = 0;\n return db._syncNodes.put(currentMaster);\n }\n }).then(()=>{\n // Add our node to DB and start subscribing to events\n return db._syncNodes.add(mySyncNode.node).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 // Start heartbeat\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n });\n });\n }).then(function () {\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', ()=>{\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.node; // 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(new Dexie.DatabaseClosedError());\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 let ourNodeStillExists = false;\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\n ourNodeStillExists = true;\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\n }).then(()=>ourNodeStillExists);\n }).then(ourNodeStillExists =>{\n if (!ourNodeStillExists) {\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\n }).finally(function() {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n /**\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\n * \n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\n * it would believe it was dead.\n */\n function heartbeat() {\n heartbeatHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n db.transaction('rw!', db._syncNodes, ()=>{\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\n if (!ourSyncNode) {\n // We do not exist anymore. Call db.close() to teardown polls etc.\n if (db.isOpen()) db.close();\n return;\n }\n ourSyncNode.lastHeartBeat = Date.now();\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n return db._syncNodes.put(ourSyncNode);\n });\n }).catch('DatabaseClosedError', () => {\n // Ignore silently\n }).finally(() => {\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }\n });\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n 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.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\n .catch('DatabaseClosedError', ()=>{\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 .finally(function() {\n // Poll again in given interval:\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n \n function cleanup() {\n var ourSyncNode = mySyncNode.node;\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\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).filter(node => node.type === 'local').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 if (localStorage) {\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n }\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 // Those that waits for reply should be redirected to us.\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\n if (msg.wantReply)\n msg.destinationNode = ourSyncNode.id;\n else\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\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() {\n // Mark our own sync node for deletion.\n if (!mySyncNode.node) return;\n browserIsShuttingDown = true;\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // 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 if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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\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\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 = createUUID;\n\nObservable.deleteOldChanges = deleteOldChanges;\n\nObservable._onStorage = initOnStorage(Observable);\n\nObservable._onBeforeUnload = function() {\n Observable.on.beforeunload.fire();\n};\n\ntry {\n Observable.localStorageImpl = global.localStorage;\n} catch (ex){}\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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AAgB,GAAG,gBAAgB,CAAC;AAE/C,UAAU,CAAC,UAAU,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;AAElD,UAAU,CAAC,eAAe,GAAG;IACzB,UAAU,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC;CACrC,CAAC;AAEF,IAAI;IACA,UAAU,CAAC,gBAAgB,GAAG,MAAM,CAAC,YAAY,CAAC;CACrD;AAAC,OAAO,EAAE,EAAC,GAAE;;;;AAKd,IAAI,MAAM,CAAC,gBAAgB,EAAE;IACzB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAC1D,MAAM,CAAC,gBAAgB,CAAC,cAAc,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACvE;;AAED,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;AAC9B,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;;;;"} \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.js b/addons/Dexie.Observable/dist/dexie-observable.js new file mode 100644 index 000000000..98d37eaa0 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js @@ -0,0 +1,998 @@ +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.8, Fri Jul 31 2020 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +(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 = Dexie && Dexie.hasOwnProperty('default') ? Dexie['default'] : Dexie; + +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); + }; +} +function createUUID() { + // 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; +} + +function initOverrideCreateTransaction(db, wakeupObservers) { + return function overrideCreateTransaction(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; + }; + }; +} + +function initWakeupObservers(db, Observable, localStorage) { + return 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. + if (localStorage) + 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. + } + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function initCreatingHook(db, table) { + return function creatingHook(primKey, obj, trans) { + /// + var rv = undefined; + if (primKey === undefined && table.schema.primKey.uuid) { + primKey = rv = createUUID(); + if (table.schema.primKey.keyPath) { + Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey); + } + } + var change = { + source: trans.source || null, + table: table.name, + 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 () { + // 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; + }; +} + +function initUpdatingHook(db, tableName) { + return function updatingHook(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 wouldn't 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, + 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 () { + // 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); + }); + }; + } + }; +} + +function initDeletingHook(db, tableName) { + return function deletingHook(primKey, obj, trans) { + /// + var promise = db._changes.add({ + source: trans.source || null, + table: tableName, + key: primKey, + type: DELETE, + oldObj: obj + }).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }) + .catch(function (e) { + console.log(obj); + console.log(e.stack); + }); + 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); + }); + }; + }; +} + +function initCrudMonitor(db) { + // + // The Creating/Updating/Deleting hook will make sure any change is stored to the changes table + // + return function crudMonitor(table) { + /// + if (table.hook._observing) + return; + table.hook._observing = true; + var tableName = table.name; + table.hook('creating').subscribe(initCreatingHook(db, table)); + table.hook('updating').subscribe(initUpdatingHook(db, tableName)); + table.hook('deleting').subscribe(initDeletingHook(db, tableName)); + }; +} + +function initOnStorage(Observable) { + return 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 && 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); + } + } + } + }; +} + +function initOverrideOpen(db, SyncNode, crudMonitor) { + return function overrideOpen(origOpen) { + return function () { + // + // Make sure to subscribe to "creating", "updating" and "deleting" hooks for all observable tables that were created in the stores() method. + // + Object.keys(db._allTables).forEach(function (tableName) { + var table = db._allTables[tableName]; + if (table.schema.observable) { + crudMonitor(table); + } + if (table.name === "_syncNodes") { + table.mapToClass(SyncNode); + } + }); + return origOpen.apply(this, arguments); + }; + }; +} + +var Promise = Dexie.Promise; +function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) { + // + // Intercommunication between nodes + // + // Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable) + var requestsWaitingForReply = {}; + /** + * @param {string} type Type of message + * @param message Message to send + * @param {number} destinationNode ID of destination node + * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent. + */ + db.observable.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. + options = options || {}; + if (!mySyncNode.node) + return options.wantReply ? + Promise.reject(new Dexie.DatabaseClosedError()) : + Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either. + var msg = { message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type }; + Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ... + return Dexie.ignoreTransaction(function () { + var tables = ["_intercomm"]; + if (options.wantReply) + tables.push("_syncNodes"); // If caller wants a reply, include "_syncNodes" in transaction to check that there's a receiver there. Otherwise, new master will get it. + var promise = db.transaction('rw', tables, function () { + if (options.wantReply) { + // Check that there is a receiver there to take the request. + return db._syncNodes.where('id').equals(destinationNode).count(function (receiverAlive) { + if (receiverAlive) + return db._intercomm.add(msg); + else // If we couldn't find a node -> send to master + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + msg.destinationNode = masterNode.id; + return db._intercomm.add(msg); + }); + }); + } + else { + // If caller doesn't need a response, we don't have to make sure that it gets one. + return db._intercomm.add(msg); + } + }).then(function (messageId) { + var rv = null; + if (options.wantReply) { + rv = new Promise(function (resolve, reject) { + requestsWaitingForReply[messageId.toString()] = { resolve: resolve, reject: reject }; + }); + } + if (localStorage) { + localStorage.setItem("Dexie.Observable/intercomm/" + db.name, messageId.toString()); + } + Observable.on.intercomm.fire(db.name); + return rv; + }); + if (!options.wantReply) { + promise.catch(function () { + }); + return; + } + else { + // Forward rejection to caller if it waits for reply. + return promise; + } + }); + }; + // Send a message to all local _syncNodes + db.observable.broadcastMessage = function (type, message, bIncludeSelf) { + if (!mySyncNode.node) + return; + var mySyncNodeId = mySyncNode.node.id; + Dexie.ignoreTransaction(function () { + db._syncNodes.toArray(function (nodes) { + return Promise.all(nodes + .filter(function (node) { return node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId); }) + .map(function (node) { return db.observable.sendMessage(type, message, node.id); })); + }).catch(function () { + }); + }); + }; + function consumeIntercommMessages() { + // Check if we got messages: + if (!mySyncNode.node) + return Promise.reject(new Dexie.DatabaseClosedError()); + return Dexie.ignoreTransaction(function () { + return db.transaction('rw', '_intercomm', function () { + return db._intercomm.where({ destinationNode: mySyncNode.node.id }).toArray(function (messages) { + messages.forEach(function (msg) { return consumeMessage(msg); }); + return db._intercomm.where('id').anyOf(messages.map(function (msg) { return msg.id; })).delete(); + }); + }); + }); + } + function consumeMessage(msg) { + if (msg.type === 'response') { + // This is a response. Lookup pending request and fulfill its 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.observable.sendMessage('response', { result: result }, msg.sender, { requestId: msg.id }); + }; + msg.reject = function (error) { + db.observable.sendMessage('response', { error: error.toString() }, msg.sender, { isFailure: true, requestId: msg.id }); + }; + db.on.message.fire(msg); + } + } + // Listener for 'intercomm' events + // Gets fired when we get a 'storage' event from local storage or when sendMessage is called + // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event) + // sendMessage is used to communicate in the same tab and to trigger a storage event + function onIntercomm(dbname) { + // When storage event trigger us to check + if (dbname === db.name) { + consumeIntercommMessages().catch('DatabaseClosedError', function () { }); + } + } + return { + onIntercomm: onIntercomm, + consumeIntercommMessages: consumeIntercommMessages + }; +} + +function overrideParseStoresSpec(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; + } + }); + }; +} + +function deleteOldChanges(db) { + // This is a background job and should never be done within + // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that. + // We should not return the Promise but catch it ourselves instead. + // To prohibit starving the database we want to lock transactions as short as possible + // and since we're not in a hurry, we could do this job in chunks and reschedule a + // continuation every 500 ms. + var CHUNK_SIZE = 100; + Dexie.ignoreTransaction(function () { + return db._syncNodes.orderBy("myRevision").first(function (oldestNode) { + return db._changes + .where("rev").below(oldestNode.myRevision) + .limit(CHUNK_SIZE) + .primaryKeys(); + }).then(function (keysToDelete) { + if (keysToDelete.length === 0) + return; // Done. + return db._changes.bulkDelete(keysToDelete).then(function () { + // If not done garbage collecting, reschedule a continuation of it until done. + if (keysToDelete.length === CHUNK_SIZE) { + // Limit reached. Changes are there are more job to do. Schedule again: + setTimeout(function () { return db.isOpen() && deleteOldChanges(db); }, 500); + } + }); + }); + }).catch(function () { + // The operation is not crucial. A failure could almost only be due to that database has been closed. + // No need to log this. + }); +} + +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.8, Fri Jul 31 2020 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +var global = self; +/** class DatabaseChange + * + * Object contained by the _changes table. + */ +var DatabaseChange = Dexie.defineClass({ + rev: Number, + source: String, + table: String, + key: Object, + type: Number, + obj: Object, + mods: 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$1 = 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 = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event. + HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000; + var localStorage = Observable.localStorageImpl; + /** class SyncNode + * + * Object contained in the _syncNodes table. + */ + var SyncNode = Dexie.defineClass({ + //id: Number, + myRevision: Number, + type: String, + lastHeartBeat: Number, + deleteTimeStamp: Number, + url: String, + isMaster: Number, + // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == "remote"): + syncProtocol: String, + syncContext: null, + syncOptions: Object, + connected: false, + status: Number, + appliedRemoteRevision: null, + remoteBaseRevisions: [{ local: Number, remote: null }], + dbUploadState: { + tablesToUpload: [String], + currentTable: String, + currentKey: null, + localBaseRevision: Number + } + }); + db.observable = {}; + db.observable.SyncNode = SyncNode; + var wakeupObservers = initWakeupObservers(db, Observable, localStorage); + var overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers); + var crudMonitor = initCrudMonitor(db); + var overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor); + var mySyncNode = { node: null }; + var intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage); + var onIntercomm = intercomm.onIntercomm; + var consumeIntercommMessages = intercomm.consumeIntercommMessages; + // Allow other addons to access the local sync node. May be needed by Dexie.Syncable. + Object.defineProperty(db, "_localSyncNode", { + get: function () { return mySyncNode.node; } + }); + var pollHandle = null, heartbeatHandle = 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.node = new SyncNode({ + myRevision: 0, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null + }); + } + // + // Override parsing the stores to add "_changes" and "_syncNodes" tables. + // It also adds UUID support for the primary key and sets tables as observable tables. + // + db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec); + // changes event on db: + db.on.addEventType({ + changes: 'asap', + cleanup: [promisableChain, nop], + message: 'asap' + }); + // + // Override transaction creation to always include the "_changes" store when any observable store is involved. + // + db._createTransaction = override(db._createTransaction, overrideCreateTransaction); + // 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; + // + // Override open to setup hooks for db changes and map the _syncNodes table to class + // + db.open = override(db.open, overrideOpen); + 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.node && mySyncNode.node.id) { + Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id); + // Inform other windows as well: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now. + mySyncNode.node = null; + } + if (pollHandle) + clearTimeout(pollHandle); + pollHandle = null; + if (heartbeatHandle) + clearTimeout(heartbeatHandle); + heartbeatHandle = 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; + }); + }; + }); + // 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.node = 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 () { + return db._syncNodes + .where('isMaster').equals(1) + .first(function (currentMaster) { + if (!currentMaster) { + // There's no master. We must be the master + mySyncNode.node.isMaster = 1; + } + else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Master have been inactive for too long + // Take over mastership + mySyncNode.node.isMaster = 1; + currentMaster.isMaster = 0; + return db._syncNodes.put(currentMaster); + } + }).then(function () { + // Add our node to DB and start subscribing to events + return db._syncNodes.add(mySyncNode.node).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); + // Start heartbeat + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + }); + }); + }).then(function () { + 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 () { + // 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.node; // 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$1.reject(new Dexie.DatabaseClosedError()); + } + 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); + } + var ourNodeStillExists = false; + return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(function (syncNode) { + ourNodeStillExists = true; + syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!) + syncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision); + }).then(function () { return ourNodeStillExists; }); + }).then(function (ourNodeStillExists) { + if (!ourNodeStillExists) { + // 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; + } + /** + * The reason we need heartbeat in parallell with poll() is due to the risk of long-running + * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will + * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on + * during that changes are being applied and update our lastHeartBeat property while poll() is waiting. + * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this + * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction. + * + * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT + * (20 seconds), another node waking up after the sync would kill the master node and take over because + * it would believe it was dead. + */ + function heartbeat() { + heartbeatHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + db.transaction('rw!', db._syncNodes, function () { + db._syncNodes.where({ id: currentInstance }).first(function (ourSyncNode) { + if (!ourSyncNode) { + // We do not exist anymore. Call db.close() to teardown polls etc. + if (db.isOpen()) + db.close(); + return; + } + ourSyncNode.lastHeartBeat = Date.now(); + ourSyncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + return db._syncNodes.put(ourSyncNode); + }); + }).catch('DatabaseClosedError', function () { + // Ignore silently + }).finally(function () { + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + } + }); + } + function poll() { + pollHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + Dexie.vip(function () { + readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages) + .catch('DatabaseClosedError', function () { + // 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. + }) + .finally(function () { + // Poll again in given interval: + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + pollHandle = setTimeout(poll, LOCAL_POLL); + } + }); + }); + } + function cleanup() { + var ourSyncNode = mySyncNode.node; + if (!ourSyncNode) + return Promise$1.reject(new Dexie.DatabaseClosedError()); + 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).filter(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.) + if (localStorage) { + 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. + // Those that waits for reply should be redirected to us. + db._intercomm.where({ destinationNode: node.id }).modify(function (msg) { + if (msg.wantReply) + msg.destinationNode = ourSyncNode.id; + else + // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request. + delete this.value; + }); + } + 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() { + // Mark our own sync node for deletion. + if (!mySyncNode.node) + return; + browserIsShuttingDown = true; + mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // 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: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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); + }); + } + } +} +// +// 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 = createUUID; +Observable.deleteOldChanges = deleteOldChanges; +Observable._onStorage = initOnStorage(Observable); +Observable._onBeforeUnload = function () { + Observable.on.beforeunload.fire(); +}; +try { + Observable.localStorageImpl = global.localStorage; +} +catch (ex) { } +// +// 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..33d00f032 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-observable.js","sources":["../src/utils.js","../src/override-create-transaction.js","../src/wakeup-observers.js","../src/change_types.js","../src/hooks/creating.js","../src/hooks/updating.js","../src/hooks/deleting.js","../src/hooks/crud-monitor.js","../src/on-storage.js","../src/override-open.js","../src/intercomm.js","../src/override-parse-stores-spec.js","../src/delete-old-changes.js","../src/Dexie.Observable.js"],"sourcesContent":["export function nop() {}\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, args = arguments;\n return res.then(function() {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nexport function createUUID() {\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","export default function initOverrideCreateTransaction(db, wakeupObservers) {\n return function overrideCreateTransaction(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)\n 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(\n trans._lastWrittenRevision,\n 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","import Dexie from 'dexie';\n\nexport default function initWakeupObservers(db, Observable, localStorage) {\n return 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 if (localStorage) 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","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nimport {CREATE} from '../change_types';\nimport {createUUID} from '../utils';\n\nexport default function initCreatingHook(db, table) {\n return function creatingHook(primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = 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: table.name,\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)\n promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n\n this.onerror = function () {\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","import Dexie from 'dexie';\n\nimport {UPDATE} from '../change_types';\n\nexport default function initUpdatingHook(db, tableName) {\n return function updatingHook(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 wouldn't 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 () {\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","import {DELETE} from '../change_types';\n\nexport default function initDeletingHook(db, tableName) {\n return function deletingHook(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 .catch((e) => {\n console.log(obj)\n console.log(e.stack)\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","import initCreatingHook from './creating';\nimport initUpdatingHook from './updating';\nimport initDeletingHook from './deleting';\n\nexport default function initCrudMonitor(db) {\n//\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n//\n return function crudMonitor(table) {\n /// \n if (table.hook._observing) return;\n table.hook._observing = true;\n\n const tableName = table.name;\n table.hook('creating').subscribe(initCreatingHook(db, table));\n\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\n\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initOnStorage(Observable) {\n return 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 && event.key.indexOf(\"Dexie.Observable/\") === 0) { // 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}\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\n return function overrideOpen(origOpen) {\n return function () {\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 Object.keys(db._allTables).forEach(tableName => {\n let table = db._allTables[tableName];\n if (table.schema.observable) {\n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\") {\n table.mapToClass(SyncNode);\n }\n });\n return origOpen.apply(this, arguments);\n }\n };\n}\n","import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\n//\n// Intercommunication between nodes\n//\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\n\n var requestsWaitingForReply = {};\n\n /**\n * @param {string} type Type of message\n * @param message Message to send\n * @param {number} destinationNode ID of destination node\n * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n */\n db.observable.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 options = options || {};\n if (!mySyncNode.node)\n return options.wantReply ?\n Promise.reject(new Dexie.DatabaseClosedError()) :\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\n\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n return Dexie.ignoreTransaction(()=> {\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 receiver there. Otherwise, new master will get it.\n var promise = db.transaction('rw', tables, () => {\n if (options.wantReply) {\n // Check that there is a receiver there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\n if (receiverAlive)\n return db._intercomm.add(msg);\n else // If we couldn't find a node -> send to master\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return db._intercomm.add(msg)\n });\n });\n } else {\n // If caller doesn't need a response, we don't have to make sure that it gets one.\n return db._intercomm.add(msg);\n }\n }).then(messageId => {\n var rv = null;\n if (options.wantReply) {\n rv = new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\n });\n }\n if (localStorage) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n }\n Observable.on.intercomm.fire(db.name);\n return rv;\n });\n\n if (!options.wantReply) {\n promise.catch(()=> {\n });\n return;\n } else {\n // Forward rejection to caller if it waits for reply.\n return promise;\n }\n });\n };\n\n // Send a message to all local _syncNodes\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode.node) return;\n var mySyncNodeId = mySyncNode.node.id;\n Dexie.ignoreTransaction(()=> {\n db._syncNodes.toArray(nodes => {\n return Promise.all(nodes\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\n .map(node => db.observable.sendMessage(type, message, node.id)));\n }).catch(()=> {\n });\n });\n };\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\n\n return Dexie.ignoreTransaction(()=> {\n return db.transaction('rw', '_intercomm', function() {\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\n messages.forEach(msg => consumeMessage(msg));\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\n });\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill its 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.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\n };\n msg.reject = function (error) {\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\n };\n db.on.message.fire(msg);\n }\n }\n\n // Listener for 'intercomm' events\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\n // sendMessage is used to communicate in the same tab and to trigger a storage event\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\n }\n }\n\n return {\n onIntercomm,\n consumeIntercommMessages\n };\n}\n","export default function overrideParseStoresSpec(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","import Dexie from 'dexie';\n\nexport default function deleteOldChanges(db) {\n // This is a background job and should never be done within\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\n // We should not return the Promise but catch it ourselves instead.\n\n // To prohibit starving the database we want to lock transactions as short as possible\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\n // continuation every 500 ms.\n const CHUNK_SIZE = 100;\n\n Dexie.ignoreTransaction(()=>{\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\n return db._changes\n .where(\"rev\").below(oldestNode.myRevision)\n .limit(CHUNK_SIZE)\n .primaryKeys();\n }).then(keysToDelete => {\n if (keysToDelete.length === 0) return; // Done.\n return db._changes.bulkDelete(keysToDelete).then(()=> {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (keysToDelete.length === CHUNK_SIZE) {\n // Limit reached. Changes are there are more job to do. Schedule again:\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\n }\n });\n });\n }).catch(()=>{\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\n // No need to log this.\n });\n}\n","/* ========================================================================== \n * dexie-observable.js\n * ==========================================================================\n *\n * Dexie addon for observing database changes not just on local db instance\n * but also on other instances, tabs and windows.\n *\n * Comprises a base framework for dexie-syncable.js\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\nimport Dexie from 'dexie';\nimport { nop, promisableChain, createUUID } from './utils';\n\nimport initOverrideCreateTransaction from './override-create-transaction';\nimport initWakeupObservers from './wakeup-observers';\nimport initCrudMonitor from './hooks/crud-monitor';\nimport initOnStorage from './on-storage';\nimport initOverrideOpen from './override-open';\nimport initIntercomm from './intercomm';\n\nimport overrideParseStoresSpec from './override-parse-stores-spec';\n\nimport deleteOldChanges from './delete-old-changes';\n\nvar global = self;\n\n/** class DatabaseChange\n *\n * Object contained by the _changes table.\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, // 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, // 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 = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event.\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\n *\n * Object contained in the _syncNodes table.\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 db.observable = {};\n db.observable.SyncNode = SyncNode;\n\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\n const crudMonitor = initCrudMonitor(db);\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\n\n var mySyncNode = {node: null};\n\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\n const onIntercomm = intercomm.onIntercomm;\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\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() { return mySyncNode.node; }\n });\n\n var pollHandle = null,\n heartbeatHandle = 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.node = 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 // It also adds UUID support for the primary key and sets tables as observable tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\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 // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\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 //\n // Override open to setup hooks for db changes and map the _syncNodes table to class\n //\n db.open = override(db.open, overrideOpen);\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.node && mySyncNode.node.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\n // Inform other windows as well:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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 }\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode.node = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\n heartbeatHandle = 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 // 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 \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.node = 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', () => {\n return db._syncNodes\n .where('isMaster').equals(1)\n .first(currentMaster => {\n if (!currentMaster) {\n // There's no master. We must be the master\n mySyncNode.node.isMaster = 1;\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Master have been inactive for too long\n // Take over mastership\n mySyncNode.node.isMaster = 1;\n currentMaster.isMaster = 0;\n return db._syncNodes.put(currentMaster);\n }\n }).then(()=>{\n // Add our node to DB and start subscribing to events\n return db._syncNodes.add(mySyncNode.node).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 // Start heartbeat\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n });\n });\n }).then(function () {\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', ()=>{\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.node; // 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(new Dexie.DatabaseClosedError());\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 let ourNodeStillExists = false;\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\n ourNodeStillExists = true;\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\n }).then(()=>ourNodeStillExists);\n }).then(ourNodeStillExists =>{\n if (!ourNodeStillExists) {\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\n }).finally(function() {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n /**\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\n * \n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\n * it would believe it was dead.\n */\n function heartbeat() {\n heartbeatHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n db.transaction('rw!', db._syncNodes, ()=>{\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\n if (!ourSyncNode) {\n // We do not exist anymore. Call db.close() to teardown polls etc.\n if (db.isOpen()) db.close();\n return;\n }\n ourSyncNode.lastHeartBeat = Date.now();\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n return db._syncNodes.put(ourSyncNode);\n });\n }).catch('DatabaseClosedError', () => {\n // Ignore silently\n }).finally(() => {\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }\n });\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n 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.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\n .catch('DatabaseClosedError', ()=>{\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 .finally(function() {\n // Poll again in given interval:\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n \n function cleanup() {\n var ourSyncNode = mySyncNode.node;\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\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).filter(node => node.type === 'local').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 if (localStorage) {\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n }\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 // Those that waits for reply should be redirected to us.\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\n if (msg.wantReply)\n msg.destinationNode = ourSyncNode.id;\n else\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\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() {\n // Mark our own sync node for deletion.\n if (!mySyncNode.node) return;\n browserIsShuttingDown = true;\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // 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 if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.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\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\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 = createUUID;\n\nObservable.deleteOldChanges = deleteOldChanges;\n\nObservable._onStorage = initOnStorage(Observable);\n\nObservable._onBeforeUnload = function() {\n Observable.on.beforeunload.fire();\n};\n\ntry {\n Observable.localStorageImpl = global.localStorage;\n} catch (ex){}\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);\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAAwB;AAExB,yBAAgC,EAAE,EAAE,EAAE;IACpC,IAAI,EAAE,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IAC1B,OAAO;QACL,IAAI,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACpC,IAAI,GAAG,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,EAAE;YACzC,IAAI,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;YAClC,OAAO,GAAG,CAAC,IAAI,CAAC;gBACd,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;aAC7B,CAAC,CAAC;SACJ;QACD,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;KAClC,CAAC;CACH;AAED;;IAEE,IAAI,CAAC,GAAG,IAA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dexie.Observable/dist/dexie-observable.min.js b/addons/Dexie.Observable/dist/dexie-observable.min.js new file mode 100644 index 000000000..bc1dc0879 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js @@ -0,0 +1 @@ +(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(O){"use strict";function S(){}function T(o,i){return o===S?i:function(){var e=o.apply(this,arguments);if(e&&"function"==typeof e.then){var n=this,t=arguments;return e.then(function(){return i.apply(n,t)})}return i.apply(this,arguments)}}function c(){var t=Date.now();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var n=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"===e?n:7&n|8).toString(16)})}O=O&&O.hasOwnProperty("default")?O.default:O;var u=1,v=2,a=3;function D(t){return function(e){if(!e.hook._observing){e.hook._observing=!0;var n=e.name;e.hook("creating").subscribe(function(a,s){return function(n,e,t){var o=void 0;void 0===n&&s.schema.primKey.uuid&&(n=o=c(),s.schema.primKey.keyPath&&O.setByKeyPath(e,s.schema.primKey.keyPath,n));var i={source:t.source||null,table:s.name,key:void 0===n?null:n,type:u,obj:e},r=a._changes.add(i).then(function(e){return t._lastWrittenRevision=Math.max(t._lastWrittenRevision,e),e});return this.onsuccess=function(e){n!=e&&r._then(function(){i.key=e,a._changes.put(i)})},this.onerror=function(){r._then(function(e){a._changes.delete(e)})},o}}(t,e)),e.hook("updating").subscribe(function(f,m){return function(e,n,t,o){var i={},r=!1,a=O.deepClone(t);for(var s in e){var c=e[s];if(void 0===c)O.delByKeyPath(a,s),r=!(i[s]=null);else{var u=O.getByKeyPath(t,s);c!==u&&JSON.stringify(c)!==JSON.stringify(u)&&(O.setByKeyPath(a,s,c),i[s]=c,r=!0)}}if(r){var l={source:o.source||null,table:m,key:n,type:v,mods:i,oldObj:t,obj:a},d=f._changes.add(l);this.onsuccess=function(){d._then(function(e){o._lastWrittenRevision=Math.max(o._lastWrittenRevision,e)})},this.onerror=function(){d._then(function(e){f._changes.delete(e)})}}}}(t,n)),e.hook("deleting").subscribe(function(i,r){return function(e,n,t){var o=i._changes.add({source:t.source||null,table:r,key:e,type:a,oldObj:n}).then(function(e){return t._lastWrittenRevision=Math.max(t._lastWrittenRevision,e),e}).catch(function(e){console.log(n),console.log(e.stack)});this.onerror=function(){o._then(function(e){i._changes.delete(e)})}}}(t,n))}}}var l=O.Promise;function C(r,a,e,s,c){var u={};function n(){return s.node?O.ignoreTransaction(function(){return r.transaction("rw","_intercomm",function(){return r._intercomm.where({destinationNode:s.node.id}).toArray(function(e){return e.forEach(function(e){return function(n){if("response"===n.type){var e=u[n.requestId.toString()];e&&(n.isFailure?e.reject(n.message.error):e.resolve(n.message.result),delete u[n.requestId.toString()])}else n.resolve=function(e){r.observable.sendMessage("response",{result:e},n.sender,{requestId:n.id})},n.reject=function(e){r.observable.sendMessage("response",{error:e.toString()},n.sender,{isFailure:!0,requestId:n.id})},r.on.message.fire(n)}(e)}),r._intercomm.where("id").anyOf(e.map(function(e){return e.id})).delete()})})}):l.reject(new O.DatabaseClosedError)}return r.observable.sendMessage=function(e,n,t,o){if(o=o||{},!s.node)return o.wantReply?l.reject(new O.DatabaseClosedError):l.resolve();var i={message:n,destinationNode:t,sender:s.node.id,type:e};return O.extend(i,o),O.ignoreTransaction(function(){var e=["_intercomm"];o.wantReply&&e.push("_syncNodes");var n=r.transaction("rw",e,function(){return o.wantReply?r._syncNodes.where("id").equals(t).count(function(e){return e?r._intercomm.add(i):r._syncNodes.where("isMaster").above(0).first(function(e){return i.destinationNode=e.id,r._intercomm.add(i)})}):r._intercomm.add(i)}).then(function(t){var e=null;return o.wantReply&&(e=new l(function(e,n){u[t.toString()]={resolve:e,reject:n}})),c&&c.setItem("Dexie.Observable/intercomm/"+r.name,t.toString()),a.on.intercomm.fire(r.name),e});return o.wantReply?n:void n.catch(function(){})})},r.observable.broadcastMessage=function(n,t,o){if(s.node){var i=s.node.id;O.ignoreTransaction(function(){r._syncNodes.toArray(function(e){return l.all(e.filter(function(e){return"local"===e.type&&(o||e.id!==i)}).map(function(e){return r.observable.sendMessage(n,t,e.id)}))}).catch(function(){})})}},{onIntercomm:function(e){e===r.name&&n().catch("DatabaseClosedError",function(){})},consumeIntercommMessages:n}}function I(n){return function(e,t){e._changes="++rev",e._syncNodes="++id,myRevision,lastHeartBeat,&url,isMaster,type,status",e._intercomm="++id,destinationNode",e._uncommittedChanges="++id,node",n.call(this,e,t),Object.keys(t).forEach(function(e){var n=t[e];0===n.primKey.name.indexOf("$$")&&(n.primKey.uuid=!0,n.primKey.name=n.primKey.name.substr(2),n.primKey.keyPath=n.primKey.keyPath.substr(2))}),Object.keys(t).forEach(function(e){0!==e.indexOf("_")&&0!==e.indexOf("$")&&(t[e].observable=!0)})}}var s,M=self,j=O.defineClass({rev:Number,source:String,table:String,key:Object,type:Number,obj:Object,mods:Object,oldObj:Object}),k=O.override,B=O.Promise,E=!1;function H(a){var o=2e4,i=2e4,t=500,r=o-5e3,s=H.localStorageImpl,c=O.defineClass({myRevision:Number,type:String,lastHeartBeat:Number,deleteTimeStamp:Number,url:String,isMaster:Number,syncProtocol:String,syncContext:null,syncOptions:Object,connected:!1,status:Number,appliedRemoteRevision:null,remoteBaseRevisions:[{local:Number,remote:null}],dbUploadState:{tablesToUpload:[String],currentTable:String,currentKey:null,localBaseRevision:Number}});a.observable={},a.observable.SyncNode=c;var n=function(n,t,o){return function(e){t.latestRevision[n.name]r.myRevision)return g(H.latestRevision[a.name],(n||0)+1,i)}).finally(function(){delete g.ongoingOperation});return n||(g.ongoingOperation=t),t}function _(){p=null;var e=d.node&&d.node.id;e&&a.transaction("rw!",a._syncNodes,function(){a._syncNodes.where({id:e}).first(function(e){if(e)return e.lastHeartBeat=Date.now(),e.deleteTimeStamp=null,a._syncNodes.put(e);a.isOpen()&&a.close()})}).catch("DatabaseClosedError",function(){}).finally(function(){d.node&&d.node.id===e&&a.isOpen()&&(p=setTimeout(_,r))})}function x(){y=null;var e=d.node&&d.node.id;e&&O.vip(function(){g(H.latestRevision[a.name]).then(R).then(v).catch("DatabaseClosedError",function(){}).finally(function(){d.node&&d.node.id===e&&a.isOpen()&&(y=setTimeout(x,t))})})}function R(){var t=d.node;return t?a.transaction("rw","_syncNodes","_changes","_intercomm",function(){var n=!1;a._syncNodes.where("lastHeartBeat").below(Date.now()-o).filter(function(e){return"local"===e.type}).modify(function(e){e.deleteTimeStamp&&e.deleteTimeStamps.latestRevision[o]&&(s.latestRevision[o]=i,O.ignoreTransaction(function(){s.on("latestRevisionIncremented").fire(o,i)}))}else if(0===t.indexOf("deadnode:")){var r=parseInt(t.split(":")[1],10);e.newValue&&s.on.suicideNurseCall.fire(o,r)}else"intercomm"===t&&e.newValue&&s.on.intercomm.fire(o)}}),H._onBeforeUnload=function(){H.on.beforeunload.fire()};try{H.localStorageImpl=M.localStorage}catch(e){}return M.addEventListener&&(M.addEventListener("storage",H._onStorage),M.addEventListener("beforeunload",H._onBeforeUnload)),O.Observable=H,O.addons.push(H),H}); \ 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..f5a779f5d --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["dexie-observable.js"],"names":["global","factory","exports","module","require","define","amd","Dexie","Observable","this","nop","promisableChain","f1","f2","res","apply","arguments","then","thiz","args","createUUID","d","Date","now","replace","c","r","Math","random","floor","toString","hasOwnProperty","CREATE","UPDATE","DELETE","initCrudMonitor","db","table","hook","_observing","tableName","name","subscribe","primKey","obj","trans","rv","undefined","schema","uuid","keyPath","setByKeyPath","change","source","key","type","promise","_changes","add","rev","_lastWrittenRevision","max","onsuccess","resultKey","_then","put","onerror","delete","initCreatingHook","mods","oldObj","modsWithoutUndefined","anythingChanged","newObj","deepClone","propPath","mod","delByKeyPath","currentValue","getByKeyPath","JSON","stringify","initUpdatingHook","catch","e","console","log","stack","initDeletingHook","Promise","initIntercomm","SyncNode","mySyncNode","localStorage","requestsWaitingForReply","consumeIntercommMessages","node","ignoreTransaction","transaction","_intercomm","where","destinationNode","id","toArray","messages","forEach","msg","request","requestId","isFailure","reject","message","error","resolve","result","observable","sendMessage","sender","on","fire","consumeMessage","anyOf","map","DatabaseClosedError","options","wantReply","extend","tables","push","_syncNodes","equals","count","receiverAlive","above","first","masterNode","messageId","setItem","intercomm","broadcastMessage","bIncludeSelf","mySyncNodeId","nodes","all","filter","onIntercomm","dbname","overrideParseStoresSpec","origFunc","stores","dbSchema","call","Object","keys","indexOf","substr","self","DatabaseChange","defineClass","Number","String","override","Promise$1","browserIsShuttingDown","NODE_TIMEOUT","HIBERNATE_GRACE_PERIOD","LOCAL_POLL","HEARTBEAT_INTERVAL","localStorageImpl","myRevision","lastHeartBeat","deleteTimeStamp","url","isMaster","syncProtocol","syncContext","syncOptions","connected","status","appliedRemoteRevision","remoteBaseRevisions","local","remote","dbUploadState","tablesToUpload","currentTable","currentKey","localBaseRevision","wakeupObservers","lastWrittenRevision","latestRevision","initWakeupObservers","overrideCreateTransaction","mode","storenames","dbschema","parent","dynamicallyOpened","addChanges","some","storeName","slice","rootTransaction","findRootTransaction","timeoutHandle","clearTimeout","setTimeout","initOverrideCreateTransaction","crudMonitor","overrideOpen","origOpen","_allTables","mapToClass","initOverrideOpen","defineProperty","get","pollHandle","heartbeatHandle","fake","version","_uncommittedChanges","Version","prototype","_parseStoresSpec","addEventType","changes","cleanup","_createTransaction","open","close","origClose","unsubscribe","onLatestRevisionIncremented","onSuicide","onBeforeUnload","suicideNurseCall","origDelete","orderBy","last","lastChange","latestRevisionIncremented","currentMaster","poll","heartbeat","handledRevision","vip","readChanges","recursion","wasPartial","ongoingOperation","partial","ourSyncNode","limit","length","ourNodeStillExists","modify","syncNode","Error","location","reload","finally","currentInstance","isOpen","weBecameMaster","below","value","removeItem","update","deleteOldChanges","wereTheOneDying","nodeID","Events","oldestNode","primaryKeys","keysToDelete","bulkDelete","_onStorage","event","parts","split","prop","parseInt","newValue","isNaN","_onBeforeUnload","beforeunload","ex","addEventListener","addons"],"mappings":"CAsBC,SAAUA,EAAQC,GACC,iBAAZC,SAA0C,oBAAXC,OAAyBA,OAAOD,QAAUD,EAAQG,QAAQ,UAC9E,mBAAXC,QAAyBA,OAAOC,IAAMD,OAAO,CAAC,SAAUJ,IAC9DD,EAAOO,MAAQP,EAAOO,OAAS,GAAIP,EAAOO,MAAMC,WAAaP,EAAQD,EAAOO,SAH9E,CAIEE,KAAM,SAAWF,GAAS,aAI5B,SAASG,KACT,SAASC,EAAgBC,EAAIC,GACzB,OAAID,IAAOF,EACAG,EACJ,WACH,IAAIC,EAAMF,EAAGG,MAAMN,KAAMO,WACzB,GAAIF,GAA2B,mBAAbA,EAAIG,KAAqB,CACvC,IAAIC,EAAOT,KAAMU,EAAOH,UACxB,OAAOF,EAAIG,KAAK,WACZ,OAAOJ,EAAGE,MAAMG,EAAMC,KAG9B,OAAON,EAAGE,MAAMN,KAAMO,YAG9B,SAASI,IAEL,IAAIC,EAAIC,KAAKC,MAMb,MALW,uCAAuCC,QAAQ,QAAS,SAAUC,GACzE,IAAIC,GAAKL,EAAoB,GAAhBM,KAAKC,UAAiB,GAAK,EAExC,OADAP,EAAIM,KAAKE,MAAMR,EAAI,KACL,MAANI,EAAYC,EAAS,EAAJA,EAAU,GAAMI,SAAS,MAvB1DvB,EAAQA,GAASA,EAAMwB,eAAe,WAAaxB,EAAe,QAAIA,EAsGtE,IAAIyB,EAAS,EACTC,EAAS,EACTC,EAAS,EA8Hb,SAASC,EAAgBC,GAIrB,OAAO,SAAqBC,GAExB,IAAIA,EAAMC,KAAKC,WAAf,CAEAF,EAAMC,KAAKC,YAAa,EACxB,IAAIC,EAAYH,EAAMI,KACtBJ,EAAMC,KAAK,YA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2cb3E,EAAW4Q,YA7rBY5Q,EA6rBeA,EA5rB3B,SAAmB6Q,GAEtB,GAAIA,EAAM/N,KAAkD,IAA3C+N,EAAM/N,IAAIoG,QAAQ,qBAA4B,CAC3D,IAAI4H,EAAQD,EAAM/N,IAAIiO,MAAM,KACxBC,EAAOF,EAAM,GACbpI,EAASoI,EAAM,GACnB,GAAa,mBAATE,EAA2B,CAC3B,IAAI7N,EAAM8N,SAASJ,EAAMK,SAAU,KAC9BC,MAAMhO,IAAQA,EAAMnD,EAAWsL,eAAe5C,KAC/C1I,EAAWsL,eAAe5C,GAAUvF,EACpCpD,EAAM0F,kBAAkB,WACpBzF,EAAW8G,GAAG,6BAA6BC,KAAK2B,EAAQvF,WAI/D,GAAkC,IAA9B6N,EAAK9H,QAAQ,aAAoB,CACtC,IAAIoH,EAASW,SAASD,EAAKD,MAAM,KAAK,GAAI,IACtCF,EAAMK,UACNlR,EAAW8G,GAAGqH,iBAAiBpH,KAAK2B,EAAQ4H,OAGlC,cAATU,GACDH,EAAMK,UACNlR,EAAW8G,GAAGoB,UAAUnB,KAAK2B,MAsqBjD1I,EAAWoR,gBAAkB,WACzBpR,EAAW8G,GAAGuK,aAAatK,QAE/B,IACI/G,EAAWgK,iBAAmBxK,EAAO6F,aAEzC,MAAOiM,IAYP,OARI9R,EAAO+R,mBACP/R,EAAO+R,iBAAiB,UAAWvR,EAAW4Q,YAC9CpR,EAAO+R,iBAAiB,eAAgBvR,EAAWoR,kBAGvDrR,EAAMC,WAAaA,EACnBD,EAAMyR,OAAOhK,KAAKxH,GAEXA"} \ 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.d.ts b/addons/Dexie.Syncable/dist/dexie-syncable.d.ts new file mode 100644 index 000000000..376fd1070 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.d.ts @@ -0,0 +1,106 @@ +// Type definitions for dexie-syncable v1.0.0-beta.8 +// Project: https://github.com/dfahlander/Dexie.js/tree/master/addons/Dexie.Syncable +// Definitions by: David Fahlander + +import Dexie from 'dexie'; +import 'dexie-observable'; +import { ISyncProtocol, SyncStatus } from '../api'; +import {IDatabaseChange} from 'dexie-observable/api'; + +// +// Extend Dexie interface +// +declare module 'dexie' { + interface Dexie { + syncable: { + /** + * Connect to given URL using given protocol and options. See documentation at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.connect() + */ + connect(protocol: string, url: string, options?: any): Dexie.Promise; + + /** + * Stop syncing with given url.. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.disconnect() + */ + disconnect(url: string): Dexie.Promise; + + /** + * Stop syncing and delete all sync state for given URL. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.delete() + */ + delete(url: string): Dexie.Promise; + + /** + * List remote URLs. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.list() + */ + list (): Dexie.Promise; + + /** + * Get sync status for given URL. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.getStatus() + */ + getStatus(url: string): Dexie.Promise; + + /** + * Syncable events. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.on('statusChanged') + */ + on: Dexie.Syncable.SyncableEventSet; + } + + /** + * Table used for storing uncommitted changes when downloading partial change sets from + * a sync server. + * + * Each change is bound to a node id (represents the remote server that the change was + * downloaded from) + */ + _uncommittedChanges: Dexie.Table; + } + + module Dexie { + + // Extend SyncNode interface from Dexie.Observable to + // allow storing remote nodes in table _syncNodes. + module Observable { + interface SyncNode { + url: string, // Only applicable for "remote" nodes. Only used in Dexie.Syncable. + syncProtocol: string, // Tells which implementation of ISyncProtocol to use for remote syncing. + syncContext: any, + syncOptions: any, + status: number, + appliedRemoteRevision: any, + remoteBaseRevisions: { local: number, remote: any }[], + dbUploadState: { + tablesToUpload: string[], + currentTable: string, + currentKey: any, + localBaseRevision: number + } + } + } + + var Syncable : { + (db: Dexie) : void; + /** + * See documentation at: + * https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.registerSyncProtocol() + */ + registerSyncProtocol: (name: string, prototocolInstance: ISyncProtocol) => void; + + /** Translates a sync status number into a string "ERROR_WILL_RETRY", "ERROR", etc */ + StatusTexts: {[syncStatus:number]: string}; + } + + module Syncable { + interface SyncableEventSet extends DexieEventSet { + (eventName: 'statusChanged', subscriber: (status: number, url: string) => void): void; + } + } + } +} + +export default Dexie.Syncable; + diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.es.js b/addons/Dexie.Syncable/dist/dexie-syncable.es.js new file mode 100644 index 000000000..c3e0bf304 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.es.js @@ -0,0 +1,1198 @@ +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; +import 'dexie-observable'; + +var Promise$1 = Dexie.Promise; +function initSyncableConnect(db, connect) { + return function syncableConnect(protocolInstance, protocolName, url, options) { + if (db.isOpen()) { + // Database is open + if (!db._localSyncNode) + throw new Error("Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!"); + 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: + return 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.observable.sendMessage('connect', { + protocolName: protocolName, + url: url, + options: options + }, masterNode.id, { wantReply: true }); + }); + } + } + else if (db.hasBeenClosed()) { + // Database has been closed. + return Promise$1.reject(new Dexie.DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$1.reject(new Dexie.InvalidStateError("Dexie.Syncable: Cannot connect. Database has failed to open")); + } + else { + // Database not yet open. It may be on its way to open, or open() hasn't yet been called. + // Wait for it to open, then connect. + var promise = new Promise$1(function (resolve, reject) { + db.on("ready", function () { + // First, check if this is the very first time we connect to given URL. + // Need to know, because if it is, we should stall the promise returned to + // db.on('ready') to not be fulfilled until the initial sync has succeeded. + return db._syncNodes.get({ url: url }, function (node) { + // Ok, now we know whether we should await the connect promise or not. + // No matter, we should now connect (will maybe create the SyncNode instance + // representing the given URL) + var connectPromise = db.syncable.connect(protocolName, url, options); + connectPromise.then(resolve, reject); // Resolve the returned promise when connected. + // Ok, so let's see if we should suspend DB queries until connected or not: + if (node && node.appliedRemoteRevision) { + // The very first initial sync has been done so we need not wait + // for the connect promise to complete. It can continue in background. + // Returning here will resume db.on('ready') and resume all queries that + // the application has put to the database. + return; + } + // This was the very first time we connect to the remote server, + // we must make sure that the initial sync request succeeeds before resuming + // database queries that the application code puts onto the database. + // If OFFLINE or other error, don't allow the application to proceed. + // We are assuming that an initial sync is essential for the application to + // function correctly. + return connectPromise; + }); + }); + // Force open() to happen. Otherwise connect() may stall forever. + db.open().catch(function (ex) { + // If open fails, db.on('ready') may not have been called and we must + // reject promise with InvalidStateError + reject(new Dexie.InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open", ex)); + }); + }); + return promise; + } + }; +} + +function initPersistedContext(node) { + // + // PersistedContext : IPersistedContext + // + return /** @class */ (function () { + 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(); + }); + }; + return PersistedContext; + }()); +} + +function initGetOrCreateSyncNode(db, protocolName, url) { + return function getOrCreateSyncNode(options) { + return db.transaction('rw', db._syncNodes, db._changes, 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) { + // If we found a node it will be instanceof SyncNode as Dexie.Observable + // maps to class + if (node) { + var PersistedContext = initPersistedContext(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... + node.syncOptions = options; // Options could have been changed + 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; + var PersistedContext_1 = initPersistedContext(node); + Dexie.Promise.resolve(function () { + // If options.initialUpload is explicitely false, set myRevision to currentRevision. + if (options.initialUpload === false) + return db._changes.toCollection().lastKey(function (currentRevision) { + node.myRevision = currentRevision; + }); + }()).then(function () { + db._syncNodes.add(node).then(function (nodeID) { + node.syncContext = new PersistedContext_1(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 initEnqueue(db) { + return function enqueue(context, fn, instanceID) { + function _enqueue() { + if (!context.ongoingOperation) { + context.ongoingOperation = Dexie.ignoreTransaction(function () { + return Dexie.vip(function () { + return fn(); + }); + }).finally(function () { + delete context.ongoingOperation; + }); + } + else { + context.ongoingOperation = context.ongoingOperation.then(function () { + return enqueue(context, fn, instanceID); + }); + } + return context.ongoingOperation; + } + if (!instanceID) { + // Caller wants to enqueue it until database becomes open. + if (db.isOpen()) { + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + } + else if (db._localSyncNode && instanceID === db._localSyncNode.id) { + // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB) + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + }; +} + +function initSaveToUncommittedChanges(db, node) { + return function saveToUncommittedChanges(changes, remoteRevision) { + return db.transaction('rw!', db._uncommittedChanges, function () { + return db._uncommittedChanges.bulkAdd(changes.map(function (change) { + var changeWithNodeId = { + node: node.id, + type: change.type, + table: change.table, + key: change.key + }; + if (change.obj) + changeWithNodeId.obj = change.obj; + if (change.mods) + changeWithNodeId.mods = change.mods; + return changeWithNodeId; + })); + }).then(function () { + node.appliedRemoteRevision = remoteRevision; + return node.save(); + }); + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function bulkUpdate(table, changes) { + var keys = changes.map(function (c) { return c.key; }); + var map = {}; + // Retrieve current object of each change to update and map each + // found object's primary key to the existing object: + return table.where(':id').anyOf(keys).raw().each(function (obj, cursor) { + map[cursor.primaryKey + ''] = obj; + }).then(function () { + // Filter away changes whose key wasn't found in the local database + // (we can't update them if we do not know the existing values) + var updatesThatApply = changes.filter(function (c) { return map.hasOwnProperty(c.key + ''); }); + // Apply modifications onto each existing object (in memory) + // and generate array of resulting objects to put using bulkPut(): + var objsToPut = updatesThatApply.map(function (c) { + var curr = map[c.key + '']; + Object.keys(c.mods).forEach(function (keyPath) { + Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]); + }); + return curr; + }); + return table.bulkPut(objsToPut); + }); +} + +function initApplyChanges(db) { + return function applyChanges(changes) { + var collectedChanges = {}; + changes.forEach(function (change) { + var _a; + if (!collectedChanges.hasOwnProperty(change.table)) { + collectedChanges[change.table] = (_a = {}, _a[CREATE] = [], _a[DELETE] = [], _a[UPDATE] = [], _a); + } + collectedChanges[change.table][change.type].push(change); + }); + var table_names = Object.keys(collectedChanges); + var tables = table_names.map(function (table) { return db.table(table); }); + return db.transaction("rw", tables, function () { + table_names.forEach(function (table_name) { + var table = db.table(table_name); + var specifyKeys = !table.schema.primKey.keyPath; + var createChangesToApply = collectedChanges[table_name][CREATE]; + var deleteChangesToApply = collectedChanges[table_name][DELETE]; + var updateChangesToApply = collectedChanges[table_name][UPDATE]; + if (createChangesToApply.length > 0) + table.bulkPut(createChangesToApply.map(function (c) { return c.obj; }), specifyKeys ? + createChangesToApply.map(function (c) { return c.key; }) : undefined); + if (updateChangesToApply.length > 0) + bulkUpdate(table, updateChangesToApply); + if (deleteChangesToApply.length > 0) + table.bulkDelete(deleteChangesToApply.map(function (c) { return c.key; })); + }); + }); + }; +} + +function initFinallyCommitAllChanges(db, node) { + var applyChanges = initApplyChanges(db); + return function finallyCommitAllChanges(changes, remoteRevision) { + // 1. Open a write transaction on all tables in DB + var tablesToIncludeInTrans = db.tables.filter(function (table) { return table.name === '_changes' || + table.name === '_uncommittedChanges' || + table.schema.observable; }); + return db.transaction('rw!', tablesToIncludeInTrans, function () { + var trans = Dexie.currentTransaction; + var localRevisionBeforeChanges = 0; + return 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); + }).then(function () { + return db._uncommittedChanges.where('node').equals(node.id).delete(); + }).then(function () { + // 3. Apply last chunk of changes + return applyChanges(changes); + }).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; + } + } + } + // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction. + node.save().catch(function (err) { + console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: " + (err.stack || err)); + }); + }); + }); + }; +} + +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 hasn't yet become up-to-date with the 0 revision from client. + return { + maxClientRevision: node.remoteBaseRevisions[0].local, + remoteBaseRevision: null + }; +} + +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) { + Dexie.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) { + Dexie.setByKeyPath(clonedChange.mods[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.mods[subPath]; + }); + }); + return clonedChange; +} + +function mergeChange(prevChange, nextChange) { + 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; + } +} + +function initGetChangesSinceRevision(db, node, hasMoreToGive) { + return 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 = db._changes.where('rev').between(revision, maxRevision, false, true); + return query.until(function () { + if (numChanges === maxChanges) { + partial = true; + return true; + } + }).each(function (change) { + // Note the revision in nextRevision: + nextRevision = change.rev; + // change.source is set based on currentTransaction.source + if (change.source === ignoreSource) + return; + // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary 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 = mergeChange(prevChange, nextChange); + changeSet[id] = mergedChange; + } + }); + }).then(function () { + var changes = Object.keys(changeSet).map(function (key) { + return changeSet[key]; + }); + hasMoreToGive.hasMoreToGive = partial; + return cb(changes, partial, { myRevision: nextRevision }); + }); + }; +} + +function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) { + return 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.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 initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) { + var MAX_CHANGES_PER_CHUNK = partialsThreshold; + return 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. + var getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive); + var getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb); + // Only a "remote" SyncNode created by Dexie.Syncable + // could not pass this test (remote nodes have myRevision: -1 on instantiation) + if (node.myRevision >= 0) { + // Node is based on a revision in our local database and will just need to get the changes that have 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 the 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) { + // Initialize dbUploadState + var tablesToUpload = db.tables.filter(function (table) { + return table.schema.observable; + }).map(function (table) { + return table.name; + }); + if (tablesToUpload.length === 0) + return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced 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); + } + } + }; +} + +var Statuses = { + ERROR: -1, + OFFLINE: 0, + CONNECTING: 1, + ONLINE: 2, + SYNCING: 3, + ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect. +}; +var StatusTexts = { + "-1": "ERROR", + "0": "OFFLINE", + "1": "CONNECTING", + "2": "ONLINE", + "3": "SYNCING", + "4": "ERROR_WILL_RETRY" +}; + +var Promise$2 = Dexie.Promise; +function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) { + var enqueue = initEnqueue(db); + var hasMoreToGive = { hasMoreToGive: true }; + 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; + } + return function connectProtocol(node, activePeer) { + /// + var getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold); + var url = activePeer.url; + function changeStatusTo(newStatus) { + if (node.status !== newStatus) { + node.status = newStatus; + node.save().then(function () { + db.syncable.on.statusChanged.fire(newStatus, url); + // Also broadcast message to other nodes about the status + db.observable.broadcastMessage("syncStatusChanged", { newStatus: newStatus, url: url }, false); + }).catch('DatabaseClosedError', function () { + }); + } + } + activePeer.on('disconnect', function (newStatus) { + if (!isNaN(newStatus)) + changeStatusTo(newStatus); + }); + var connectedContinuation; + changeStatusTo(Statuses.CONNECTING); + return doSync(); + function doSync() { + // Use enqueue() to ensure only a single promise execution at a time. + return enqueue(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, sendChangesToProvider); + }, dbAliveID); + } + 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$2(function (resolve, reject) { + rejectConnectPromise.p = 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().catch('DatabaseClosedError', abortTheProvider); + } + }, 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! + return undefined; + }).finally(function () { + // In case error happens after connect, don't try reject the connect promise anymore. + // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon + // is active and this happens. It would fire unhandledrejection but that we do not want. + rejectConnectPromise.p = null; + }); + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + // 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); + return node.save(); + } + } + function abortTheProvider(error) { + activePeer.disconnect(Statuses.ERROR, error); + } + 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().catch('DatabaseClosedError', function () { + }); + return getLocalChangesForNode(node, autoAck); + } + else { + return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck); + } + }); + } + function applyRemoteChanges(remoteChanges, remoteRevision, partial /*, clear*/) { + var saveToUncommittedChanges = initSaveToUncommittedChanges(db, node); + var finallyCommitAllChanges = initFinallyCommitAllChanges(db, node); + return enqueue(applyRemoteChanges, function () { + if (!stillAlive()) + return Promise$2.reject(new Dexie.DatabaseClosedError()); + // FIXTHIS: Check what to do if clear() is true! + return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision)) + .catch(function (error) { + abortTheProvider(error); + return Promise$2.reject(error); + }); + }, dbAliveID); + } + // + // + // 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); + 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().catch('DatabaseClosedError', function () { + }); + // 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(function (ex) { + console.error("Got " + ex.message + " caught by reactToChanges"); + abortTheProvider(ex); + }); + } + 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().catch('DatabaseClosedError', function () { + }); + } + 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.hasMoreToGive) { + syncAgain(); + } + else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) { + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, connectedContinuation.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 initConnectFn(db, activePeers) { + return function connect(protocolInstance, protocolName, url, options, dbAliveID) { + /// + var existingPeer = activePeers.filter(function (peer) { + return peer.url === url; + }); + if (existingPeer.length > 0) { + var activePeer = existingPeer[0]; + var diffObject = {}; + Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject); + // Options have been changed + // We need to disconnect and reconnect + if (Object.keys(diffObject).length !== 0) { + return db.syncable.disconnect(url) + .then(function () { + return execConnect(); + }); + } + else { + // 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; + } + } + function execConnect() { + // Use an object otherwise we wouldn't be able to get the reject promise from + // connectProtocol + var rejectConnectPromise = { p: null }; + var connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise); + var getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url); + var connectPromise = getOrCreateSyncNode(options).then(function (node) { + return connectProtocol(node, activePeer); + }); + var disconnected = false; + var activePeer = { + url: url, + status: Statuses.OFFLINE, + connectPromise: connectPromise, + syncOptions: options, + on: Dexie.Events(null, "disconnect"), + disconnect: function (newStatus, error) { + var pos = activePeers.indexOf(activePeer); + if (pos >= 0) + activePeers.splice(pos, 1); + if (error && rejectConnectPromise.p) + rejectConnectPromise.p(error); + if (!disconnected) { + activePeer.on.disconnect.fire(newStatus, error); + } + disconnected = true; + } + }; + activePeers.push(activePeer); + return connectPromise; + } + return execConnect(); + }; +} + +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +// 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 Observable = Dexie.Observable; +function Syncable(db) { + /// + var activePeers = []; + var connectFn = initConnectFn(db, activePeers); + var syncableConnect = initSyncableConnect(db, connectFn); + 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.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject); + } + else if (msg.type === 'disconnect') { + db.syncable.disconnect(msg.message.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.message.newStatus, msg.message.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. + // We should connect to remote servers now. + // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR. + // Reason to reconnect to those with plain "ERROR" is that the ERROR state may occur when a database + // connection has been closed. The new master would then be expected to reconnect. + // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from + // an old closed one. + Dexie.ignoreTransaction(function () { return Dexie.vip(function () { + return db._syncNodes.where({ type: 'remote' }) + .filter(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { return Promise.all(connectedRemoteNodes.map(function (node) { + return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(function (e) { + console.warn("Dexie.Syncable: Could not connect to " + node.url + ". " + (e.stack || e)); + }); + })); }); + }); }).catch('DatabaseClosedError', function () { }); + } + }); + // "ready" subscriber for the master node that makes sure it will always connect to sync server + // when the database opens. It will not wait for the connection to complete, just initiate the + // connection so that it will continue syncing as long as the database is open. + // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure + // that db._localSyncNode exists and persisted before this subscriber kicks in. + 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!) + // This "ready" subscriber will never be the one performing the initial sync request, because + // even after calling db.syncable.connect(), there won't exist any "remote" sync node yet. + // Instead, db.syncable.connect() will subscribe to "ready" also, and that subscriber will be + // called after this one. There, in that subscriber, the initial sync request will take place + // and the "remote" node will be created so that this "ready" subscriber can auto-connect the + // next time this database is opened. + // CONCLUSION: We can always assume that the local DB has been in sync with the server at least + // once in the past for each "connectedRemoteNode" we find in query below. + // Don't halt db.ready while connecting (i.e. we do not return a promise here!) + db._syncNodes + .where('type').equals('remote') + .and(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { + // There are connected remote nodes that we must manage (or take over to manage) + connectedRemoteNodes.forEach(function (node) { return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions) + .catch(function () { }); } // A failure will be triggered in on('statusChanged'). We can ignore. + ); + }).catch('DatabaseClosedError', function () { }); + } + }, 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.getOptions = function (url, cb) { + return db.transaction('r?', db._syncNodes, function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node.syncOptions; + }).then(cb); + }); + }; + db.syncable.list = function () { + return db.transaction('r?', db._syncNodes, 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) { + return Dexie.ignoreTransaction(function () { + return Promise.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise.all(activePeers.filter(function (peer) { return peer.url === url; }).map(function (peer) { + return peer.disconnect(Statuses.OFFLINE); + })); + } + else { + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, { wantReply: true }); + }); + } + }).then(function () { + 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) { + return syncableConnect(protocolInstance, protocolName, url, options); + } + else { + return Promise.reject(new Error("ISyncProtocol '" + protocolName + "' is not registered in Dexie.Syncable.registerSyncProtocol()")); + } + }; + db.syncable.delete = function (url) { + return db.syncable.disconnect(url).then(function () { + return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, function () { + // Find the node(s) + // Several can be found, as detected by @martindiphoorn, + // let's delete them and cleanup _uncommittedChanges and _changes + // accordingly. + var nodeIDsToDelete; + return db._syncNodes + .where("url").equals(url) + .toArray(function (nodes) { return nodes.map(function (node) { return node.id; }); }) + .then(function (nodeIDs) { + nodeIDsToDelete = nodeIDs; + // Delete the syncNode that represents the remote endpoint. + return db._syncNodes.where('id').anyOf(nodeIDs).delete(); + }) + .then(function () { + // In case there were uncommittedChanges belonging to this, delete them as well + return db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete(); + }); + }).then(function () { + // Spawn background job to delete old changes, now that a node has been deleted, + // there might be changes in _changes table that is not needed to keep anymore. + // This is done in its own transaction, or possible several transaction to prohibit + // starvation + Observable.deleteOldChanges(db); + }); + }); + }; + db.syncable.unsyncedChanges = function (url) { + return db._syncNodes.where("url").equals(url).first(function (node) { + return db._changes.where('rev').above(node.myRevision).toArray(); + }); + }; + db.close = override(db.close, function (origClose) { + return function () { + activePeers.forEach(function (peer) { + peer.disconnect(); + }); + return origClose.apply(this, arguments); + }; + }); + Object.defineProperty(db.observable.SyncNode.prototype, 'save', { + enumerable: false, + configurable: true, + writable: true, + value: function () { + var _this = this; + return db.transaction('rw?', db._syncNodes, function () { + return db._syncNodes.put(_this); + }); + } + }); +} +Syncable.Statuses = Statuses; +Syncable.StatusTexts = StatusTexts; +Syncable.registeredProtocols = {}; // Map when key is the provider name. +Syncable.registerSyncProtocol = function (name, protocolInstance) { + /// + /// Register a synchronization protocol that can synchronize databases with remote servers. + /// + /// Provider name + /// Implementation of ISyncProtocol + var partialsThreshold = protocolInstance.partialsThreshold; + if (typeof partialsThreshold === 'number') { + // Don't allow NaN or negative threshold + if (isNaN(partialsThreshold) || partialsThreshold < 0) { + throw new Error('The given number for the threshold is not supported'); + } + // If the threshold is 0 we will not send any client changes but will get server changes + } + else { + // Use Infinity as the default so simple protocols don't have to care about partial synchronization + protocolInstance.partialsThreshold = Infinity; + } + Syncable.registeredProtocols[name] = protocolInstance; +}; +// Register addon in Dexie: +Dexie.Syncable = Syncable; +Dexie.addons.push(Syncable); + +export default Syncable; +//# sourceMappingURL=dexie-syncable.es.js.map diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.es.js.map b/addons/Dexie.Syncable/dist/dexie-syncable.es.js.map new file mode 100644 index 000000000..edc396fc9 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-syncable.es.js","sources":["../src/syncable-connect.js","../src/PersistedContext.js","../src/get-or-create-sync-node.js","../src/enqueue.js","../src/save-to-uncommitted-changes.js","../src/change_types.js","../src/bulk-update.js","../src/apply-changes.js","../src/finally-commit-all-changes.js","../src/get-local-changes-for-node/get-base-revision-and-max-client-revision.js","../src/combine-create-and-update.js","../src/combine-update-and-update.js","../src/merge-change.js","../src/get-local-changes-for-node/get-changes-since-revision.js","../src/get-local-changes-for-node/get-table-objects-as-changes.js","../src/get-local-changes-for-node/get-local-changes-for-node.js","../src/statuses.js","../src/connect-protocol.js","../src/connect-fn.js","../src/Dexie.Syncable.js"],"sourcesContent":["import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initSyncableConnect(db, connect) {\n return function syncableConnect(protocolInstance, protocolName, url, options) {\n if (db.isOpen()) {\n // Database is open\n if (!db._localSyncNode)\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\n\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 return 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.observable.sendMessage('connect', {\n protocolName: protocolName,\n url: url,\n options: options\n }, masterNode.id, {wantReply: true});\n });\n }\n } else if (db.hasBeenClosed()) {\n // Database has been closed.\n return Promise.reject(new Dexie.DatabaseClosedError());\n } else if (db.hasFailed()) {\n // Database has failed to open\n return Promise.reject(new Dexie.InvalidStateError(\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\n } else {\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\n // Wait for it to open, then connect.\n var promise = new Promise(function (resolve, reject) {\n db.on(\"ready\", () => {\n // First, check if this is the very first time we connect to given URL.\n // Need to know, because if it is, we should stall the promise returned to\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\n return db._syncNodes.get({url}, node => {\n // Ok, now we know whether we should await the connect promise or not.\n // No matter, we should now connect (will maybe create the SyncNode instance\n // representing the given URL)\n let connectPromise = db.syncable.connect(protocolName, url, options);\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\n // Ok, so let's see if we should suspend DB queries until connected or not:\n if (node && node.appliedRemoteRevision) {\n // The very first initial sync has been done so we need not wait\n // for the connect promise to complete. It can continue in background.\n // Returning here will resume db.on('ready') and resume all queries that\n // the application has put to the database.\n return;\n }\n // This was the very first time we connect to the remote server,\n // we must make sure that the initial sync request succeeeds before resuming\n // database queries that the application code puts onto the database.\n // If OFFLINE or other error, don't allow the application to proceed.\n // We are assuming that an initial sync is essential for the application to\n // function correctly.\n return connectPromise;\n });\n });\n // Force open() to happen. Otherwise connect() may stall forever.\n db.open().catch(ex => {\n // If open fails, db.on('ready') may not have been called and we must\n // reject promise with InvalidStateError\n reject(new Dexie.InvalidStateError(\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\n ex\n ));\n });\n });\n return promise;\n }\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initPersistedContext(node) {\n //\n // PersistedContext : IPersistedContext\n //\n return class PersistedContext {\n constructor(nodeID, otherProps) {\n this.nodeID = nodeID;\n if (otherProps) Dexie.extend(this, otherProps);\n }\n\n save() {\n // Store this instance in the syncContext property of the node it belongs to.\n return Dexie.vip(() => {\n return node.save();\n });\n }\n }\n}\n","import Dexie from 'dexie';\n\nimport initPersistedContext from './PersistedContext';\n\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\n return function getOrCreateSyncNode(options) {\n return db.transaction('rw', db._syncNodes, db._changes, function () {\n if (!url) throw new Error(\"Url cannot be empty\");\n\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\n // maps to class\n if (node) {\n const PersistedContext = initPersistedContext(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 node.syncOptions = options; // Options could have been changed\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 const PersistedContext = initPersistedContext(node);\n Dexie.Promise.resolve(function () {\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\n if (options.initialUpload === false)\n return db._changes.toCollection().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","import Dexie from 'dexie';\n\nexport default function initEnqueue(db) {\n return function enqueue(context, fn, instanceID) {\n function _enqueue() {\n if (!context.ongoingOperation) {\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\n return Dexie.vip(function () {\n return fn();\n });\n }).finally(()=> {\n delete context.ongoingOperation;\n });\n } else {\n context.ongoingOperation = context.ongoingOperation.then(function () {\n return enqueue(context, fn, instanceID);\n });\n }\n return context.ongoingOperation;\n }\n\n if (!instanceID) {\n // Caller wants to enqueue it until database becomes open.\n if (db.isOpen()) {\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\n // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB)\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n };\n}\n","export default function initSaveToUncommittedChanges(db, node) {\n return function saveToUncommittedChanges(changes, remoteRevision) {\n return db.transaction('rw!', db._uncommittedChanges, () => {\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\n let changeWithNodeId = {\n node: node.id,\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.obj) changeWithNodeId.obj = change.obj;\n if (change.mods) changeWithNodeId.mods = change.mods;\n return changeWithNodeId;\n }));\n }).then(() => {\n node.appliedRemoteRevision = remoteRevision;\n return node.save();\n });\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nexport default function bulkUpdate(table, changes) {\n let keys = changes.map(c => c.key);\n let map = {};\n // Retrieve current object of each change to update and map each\n // found object's primary key to the existing object:\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\n map[cursor.primaryKey+''] = obj;\n }).then(()=>{\n // Filter away changes whose key wasn't found in the local database\n // (we can't update them if we do not know the existing values)\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\n // Apply modifications onto each existing object (in memory)\n // and generate array of resulting objects to put using bulkPut():\n let objsToPut = updatesThatApply.map (c => {\n let curr = map[c.key+''];\n Object.keys(c.mods).forEach(keyPath => {\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\n });\n return curr;\n });\n return table.bulkPut(objsToPut);\n });\n}\n","import { CREATE, DELETE, UPDATE } from './change_types';\nimport bulkUpdate from './bulk-update';\n\nexport default function initApplyChanges(db) {\n return function applyChanges(changes) {\n let collectedChanges = {};\n changes.forEach((change) => {\n if (!collectedChanges.hasOwnProperty(change.table)) {\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\n }\n collectedChanges[change.table][change.type].push(change);\n });\n let table_names = Object.keys(collectedChanges);\n let tables = table_names.map((table) => db.table(table));\n\n return db.transaction(\"rw\", tables, () => {\n table_names.forEach((table_name) => {\n const table = db.table(table_name);\n const specifyKeys = !table.schema.primKey.keyPath;\n const createChangesToApply = collectedChanges[table_name][CREATE];\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\n if (createChangesToApply.length > 0)\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\n createChangesToApply.map(c => c.key) : undefined);\n if (updateChangesToApply.length > 0)\n bulkUpdate(table, updateChangesToApply);\n if (deleteChangesToApply.length > 0)\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\n });\n });\n };\n}\n","import Dexie from 'dexie';\nimport initApplyChanges from './apply-changes';\n\nexport default function initFinallyCommitAllChanges(db, node) {\n const applyChanges = initApplyChanges(db);\n\n return function finallyCommitAllChanges(changes, remoteRevision) {\n // 1. Open a write transaction on all tables in DB\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\n table.name === '_uncommittedChanges' ||\n table.schema.observable);\n\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\n var trans = Dexie.currentTransaction;\n var localRevisionBeforeChanges = 0;\n return 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(() => {\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);\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);\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 // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\n node.save().catch(err=> {\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\n });\n });\n });\n };\n}\n","export default function getBaseRevisionAndMaxClientRevision(node) {\n /// \n if (node.remoteBaseRevisions.length === 0)\n 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 hasn't 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","import Dexie from 'dexie';\n\nexport default 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 Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\n });\n return clonedChange;\n}\n","import Dexie from 'dexie';\n\nexport default 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) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\n Dexie.setByKeyPath(clonedChange.mods[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) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\n delete clonedChange.mods[subPath];\n });\n });\n return clonedChange;\n}\n","import { CREATE, UPDATE, DELETE } from './change_types';\nimport combineCreateAndUpdate from './combine-create-and-update.js';\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\n\nexport default function mergeChange(prevChange, nextChange) {\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","import {CREATE, UPDATE} from '../change_types';\nimport mergeChange from '../merge-change';\n\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\n return 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 = db._changes.where('rev').between(revision, maxRevision, false, true);\n return query.until(() => {\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 // change.source is set based on currentTransaction.source\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 necessary info:\n var changeToSend = {\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.type === CREATE)\n changeToSend.obj = change.obj;\n else if (change.type === UPDATE)\n 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 = mergeChange(prevChange, nextChange);\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.hasMoreToGive = partial;\n return cb(changes, partial, {myRevision: nextRevision});\n });\n };\n}\n","import {CREATE} from '../change_types';\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\n\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\n return 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.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","import Dexie from 'dexie';\n\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\nimport initGetChangesSinceRevision from './get-changes-since-revision';\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\n\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\n\n return 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 const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\n\n // Only a \"remote\" SyncNode created by Dexie.Syncable\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\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 have 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 the 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 // Initialize 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 Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced 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 const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n } else {\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n }\n }\n };\n}\n","export const Statuses = {\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\n OFFLINE: 0, // The sync provider hasn't 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 occurred such as net down but the sync provider will retry to connect.\n};\n\nexport const StatusTexts = {\n \"-1\": \"ERROR\",\n \"0\": \"OFFLINE\",\n \"1\": \"CONNECTING\",\n \"2\": \"ONLINE\",\n \"3\": \"SYNCING\",\n \"4\": \"ERROR_WILL_RETRY\"\n};\n","import Dexie from 'dexie';\n\nimport initEnqueue from './enqueue';\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\nimport {Statuses} from './statuses';\n\nconst Promise = Dexie.Promise;\n\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\n const enqueue = initEnqueue(db);\n var hasMoreToGive = {hasMoreToGive: true};\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 return function connectProtocol(node, activePeer) {\n /// \n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\n\n const url = activePeer.url;\n\n function changeStatusTo(newStatus) {\n if (node.status !== newStatus) {\n node.status = newStatus;\n node.save().then(()=> {\n db.syncable.on.statusChanged.fire(newStatus, url);\n // Also broadcast message to other nodes about the status\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\n }).catch('DatabaseClosedError', ()=> {\n });\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 enqueue() to ensure only a single promise execution at a time.\n return enqueue(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, sendChangesToProvider);\n }, dbAliveID);\n }\n\n 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.p = function (err) {\n reject(err);\n };\n Dexie.asap(function () {\n try {\n protocolInstance.sync(\n node.syncContext,\n url,\n options,\n remoteBaseRevision,\n node.appliedRemoteRevision,\n changes,\n partial,\n applyRemoteChanges,\n onChangesAccepted,\n function (continuation) {\n resolve(continuation);\n },\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().catch('DatabaseClosedError', abortTheProvider);\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 return undefined;\n }).finally(()=> {\n // In case error happens after connect, don't try reject the connect promise anymore.\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\n // is active and this happens. It would fire unhandledrejection but that we do not want.\n rejectConnectPromise.p = null;\n });\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\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 return node.save();\n }\n }\n\n function abortTheProvider(error) {\n activePeer.disconnect(Statuses.ERROR, error);\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().catch('DatabaseClosedError', ()=> {\n });\n return getLocalChangesForNode(node, autoAck);\n } else {\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\n }\n });\n }\n\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\n\n return enqueue(applyRemoteChanges, function () {\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\n // FIXTHIS: Check what to do if clear() is true!\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\n .catch(function (error) {\n abortTheProvider(error);\n return Promise.reject(error);\n });\n }, dbAliveID);\n }\n\n //\n //\n // Continuation Patterns Follows\n //\n //\n\n function continueSendingChanges(continuation) {\n if (!stillAlive()) { // Database was closed.\n if (continuation.disconnect)\n 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 }\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)\n changesWaiting = true;\n else {\n reactToChanges();\n }\n }\n }\n\n db.on('changes', onChanges);\n\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().catch('DatabaseClosedError', ()=> {\n });\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(ex => {\n console.error(`Got ${ex.message} caught by reactToChanges`);\n abortTheProvider(ex);\n });\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().catch('DatabaseClosedError', ()=> {\n });\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.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 } 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","import Dexie from 'dexie';\n\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\nimport initConnectProtocol from './connect-protocol';\nimport {Statuses} from './statuses';\n\nexport default function initConnectFn(db, activePeers) {\n return 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 const activePeer = existingPeer[0];\n const diffObject = {};\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\n // Options have been changed\n // We need to disconnect and reconnect\n if (Object.keys(diffObject).length !== 0) {\n return db.syncable.disconnect(url)\n .then(() => {\n return execConnect();\n })\n } else {\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\n function execConnect() {\n // Use an object otherwise we wouldn't be able to get the reject promise from\n // connectProtocol\n var rejectConnectPromise = {p: null};\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\n return connectProtocol(node, activePeer);\n });\n\n var disconnected = false;\n var activePeer = {\n url: url,\n status: Statuses.OFFLINE,\n connectPromise: connectPromise,\n syncOptions: options,\n on: Dexie.Events(null, \"disconnect\"),\n disconnect: function (newStatus, error) {\n var pos = activePeers.indexOf(activePeer);\n if (pos >= 0) activePeers.splice(pos, 1);\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\n if (!disconnected) {\n activePeer.on.disconnect.fire(newStatus, error);\n }\n disconnected = true;\n }\n };\n activePeers.push(activePeer);\n\n return connectPromise;\n }\n\n return execConnect();\n };\n}\n","/* ========================================================================== \n * dexie-syncable.js\n * ==========================================================================\n *\n * Dexie addon for syncing indexedDB with remote endpoints.\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \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\nimport initSyncableConnect from './syncable-connect';\nimport initConnectFn from './connect-fn';\nimport {Statuses, StatusTexts} from './statuses';\n\nvar override = Dexie.override,\n Promise = Dexie.Promise,\n Observable = Dexie.Observable;\n\nexport default function Syncable (db) {\n /// \n\n var activePeers = [];\n\n const connectFn = initConnectFn(db, activePeers);\n const syncableConnect = initSyncableConnect(db, connectFn);\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.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\n } else if (msg.type === 'disconnect') {\n db.syncable.disconnect(msg.message.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.message.newStatus, msg.message.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 // We should connect to remote servers now.\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\n // connection has been closed. The new master would then be expected to reconnect.\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\n // an old closed one. \n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\n return db._syncNodes.where({type: 'remote'})\n .filter(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\n })\n )));\n })).catch('DatabaseClosedError', ()=>{});\n }\n });\n\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\n // when the database opens. It will not wait for the connection to complete, just initiate the\n // connection so that it will continue syncing as long as the database is open.\n\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\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 // This \"ready\" subscriber will never be the one performing the initial sync request, because\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\n // called after this one. There, in that subscriber, the initial sync request will take place\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\n // next time this database is opened.\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\n // once in the past for each \"connectedRemoteNode\" we find in query below.\n\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\n db._syncNodes\n .where('type').equals('remote')\n .and(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => {\n // There are connected remote nodes that we must manage (or take over to manage)\n connectedRemoteNodes.forEach(\n node => db.syncable.connect(\n node.syncProtocol,\n node.url,\n node.syncOptions) \n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\n );\n }).catch('DatabaseClosedError', ()=>{});\n }\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\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.getOptions = function(url, cb) {\n return db.transaction('r?', db._syncNodes, () => {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node.syncOptions;\n }).then(cb);\n });\n };\n\n db.syncable.list = function() {\n return db.transaction('r?', db._syncNodes, ()=>{\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\n return a.map(function(node) { return node.url; });\n });\n });\n };\n\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\n\n db.syncable.disconnect = function(url) {\n return Dexie.ignoreTransaction(()=>{\n return Promise.resolve().then(()=>{\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\n return peer.disconnect(Statuses.OFFLINE);\n }));\n } else {\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\n });\n }\n }).then(()=>{\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\n node.status = Statuses.OFFLINE;\n });\n });\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 if (protocolInstance) {\n return syncableConnect(protocolInstance, protocolName, url, options);\n } else {\n return Promise.reject(\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\n );\n }\n };\n\n db.syncable.delete = function(url) {\n return db.syncable.disconnect(url).then(()=>{\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\n // Find the node(s)\n // Several can be found, as detected by @martindiphoorn,\n // let's delete them and cleanup _uncommittedChanges and _changes \n // accordingly.\n let nodeIDsToDelete;\n return db._syncNodes\n .where(\"url\").equals(url)\n .toArray(nodes => nodes.map(node => node.id))\n .then(nodeIDs => {\n nodeIDsToDelete = nodeIDs;\n // Delete the syncNode that represents the remote endpoint.\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\n })\n .then (() =>\n // In case there were uncommittedChanges belonging to this, delete them as well\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\n }).then(()=> {\n // Spawn background job to delete old changes, now that a node has been deleted,\n // there might be changes in _changes table that is not needed to keep anymore.\n // This is done in its own transaction, or possible several transaction to prohibit\n // starvation\n Observable.deleteOldChanges(db);\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 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 Object.defineProperty(\n db.observable.SyncNode.prototype,\n 'save', {\n enumerable: false,\n configurable: true,\n writable: true,\n value() {\n return db.transaction('rw?', db._syncNodes, () => {\n return db._syncNodes.put(this);\n });\n }\n });\n}\n\nSyncable.Statuses = Statuses;\n\nSyncable.StatusTexts = StatusTexts;\n\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\n\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\n /// \n /// Register a synchronization protocol that can synchronize databases with remote servers.\n /// \n /// Provider name\n /// Implementation of ISyncProtocol\n const partialsThreshold = protocolInstance.partialsThreshold;\n if (typeof partialsThreshold === 'number') {\n // Don't allow NaN or negative threshold\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\n throw new Error('The given number for the threshold is not supported');\n }\n // If the threshold is 0 we will not send any client changes but will get server changes\n } else {\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\n protocolInstance.partialsThreshold = Infinity;\n }\n Syncable.registeredProtocols[name] = protocolInstance;\n};\n\n// Register addon in Dexie:\nDexie.Syncable = Syncable;\nDexie.addons.push(Syncable);\n"],"names":["Promise"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AE,IAAI;QAClB,QAAQ,EAAE,IAAI;QACd,KAAK;YAAL,iBAIH;YAHO,OAAO,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,EAAE;gBACxC,OAAO,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,KAAI,CAAC,CAAC;aACtC,CAAC,CAAC;SACN;KACH,CAAC,CAAC;CACP;AAED,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAE7B,QAAQ,CAAC,WAAW,GAAG,WAAW,CAAC;AAEnC,QAAQ,CAAC,mBAAmB,GAAG,EAAE,CAAC;AAElC,QAAQ,CAAC,oBAAoB,GAAG,UAAS,IAAI,EAAE,gBAAgB;;;;;;IAM3D,IAAM,iBAAiB,GAAG,gBAAgB,CAAC,iBAAiB,CAAC;IAC7D,IAAI,OAAO,iBAAiB,KAAK,QAAQ,EAAE;;QAEvC,IAAI,KAAK,CAAC,iBAAiB,CAAC,IAAI,iBAAiB,GAAG,CAAC,EAAE;YACnD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;SAC1E;;KAEJ;SAAM;;QAEH,gBAAgB,CAAC,iBAAiB,GAAG,QAAQ,CAAC;KACjD;IACD,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,CAAC;;"} \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.js b/addons/Dexie.Syncable/dist/dexie-syncable.js new file mode 100644 index 000000000..11ddcf3e1 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js @@ -0,0 +1,1205 @@ +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.8, Fri Jul 31 2020 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +(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)); +}(this, (function (Dexie) { 'use strict'; + +Dexie = 'default' in Dexie ? Dexie['default'] : Dexie; + +var Promise$1 = Dexie.Promise; +function initSyncableConnect(db, connect) { + return function syncableConnect(protocolInstance, protocolName, url, options) { + if (db.isOpen()) { + // Database is open + if (!db._localSyncNode) + throw new Error("Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!"); + 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: + return 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.observable.sendMessage('connect', { + protocolName: protocolName, + url: url, + options: options + }, masterNode.id, { wantReply: true }); + }); + } + } + else if (db.hasBeenClosed()) { + // Database has been closed. + return Promise$1.reject(new Dexie.DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$1.reject(new Dexie.InvalidStateError("Dexie.Syncable: Cannot connect. Database has failed to open")); + } + else { + // Database not yet open. It may be on its way to open, or open() hasn't yet been called. + // Wait for it to open, then connect. + var promise = new Promise$1(function (resolve, reject) { + db.on("ready", function () { + // First, check if this is the very first time we connect to given URL. + // Need to know, because if it is, we should stall the promise returned to + // db.on('ready') to not be fulfilled until the initial sync has succeeded. + return db._syncNodes.get({ url: url }, function (node) { + // Ok, now we know whether we should await the connect promise or not. + // No matter, we should now connect (will maybe create the SyncNode instance + // representing the given URL) + var connectPromise = db.syncable.connect(protocolName, url, options); + connectPromise.then(resolve, reject); // Resolve the returned promise when connected. + // Ok, so let's see if we should suspend DB queries until connected or not: + if (node && node.appliedRemoteRevision) { + // The very first initial sync has been done so we need not wait + // for the connect promise to complete. It can continue in background. + // Returning here will resume db.on('ready') and resume all queries that + // the application has put to the database. + return; + } + // This was the very first time we connect to the remote server, + // we must make sure that the initial sync request succeeeds before resuming + // database queries that the application code puts onto the database. + // If OFFLINE or other error, don't allow the application to proceed. + // We are assuming that an initial sync is essential for the application to + // function correctly. + return connectPromise; + }); + }); + // Force open() to happen. Otherwise connect() may stall forever. + db.open().catch(function (ex) { + // If open fails, db.on('ready') may not have been called and we must + // reject promise with InvalidStateError + reject(new Dexie.InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open", ex)); + }); + }); + return promise; + } + }; +} + +function initPersistedContext(node) { + // + // PersistedContext : IPersistedContext + // + return /** @class */ (function () { + 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(); + }); + }; + return PersistedContext; + }()); +} + +function initGetOrCreateSyncNode(db, protocolName, url) { + return function getOrCreateSyncNode(options) { + return db.transaction('rw', db._syncNodes, db._changes, 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) { + // If we found a node it will be instanceof SyncNode as Dexie.Observable + // maps to class + if (node) { + var PersistedContext = initPersistedContext(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... + node.syncOptions = options; // Options could have been changed + 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; + var PersistedContext_1 = initPersistedContext(node); + Dexie.Promise.resolve(function () { + // If options.initialUpload is explicitely false, set myRevision to currentRevision. + if (options.initialUpload === false) + return db._changes.toCollection().lastKey(function (currentRevision) { + node.myRevision = currentRevision; + }); + }()).then(function () { + db._syncNodes.add(node).then(function (nodeID) { + node.syncContext = new PersistedContext_1(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 initEnqueue(db) { + return function enqueue(context, fn, instanceID) { + function _enqueue() { + if (!context.ongoingOperation) { + context.ongoingOperation = Dexie.ignoreTransaction(function () { + return Dexie.vip(function () { + return fn(); + }); + }).finally(function () { + delete context.ongoingOperation; + }); + } + else { + context.ongoingOperation = context.ongoingOperation.then(function () { + return enqueue(context, fn, instanceID); + }); + } + return context.ongoingOperation; + } + if (!instanceID) { + // Caller wants to enqueue it until database becomes open. + if (db.isOpen()) { + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + } + else if (db._localSyncNode && instanceID === db._localSyncNode.id) { + // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB) + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + }; +} + +function initSaveToUncommittedChanges(db, node) { + return function saveToUncommittedChanges(changes, remoteRevision) { + return db.transaction('rw!', db._uncommittedChanges, function () { + return db._uncommittedChanges.bulkAdd(changes.map(function (change) { + var changeWithNodeId = { + node: node.id, + type: change.type, + table: change.table, + key: change.key + }; + if (change.obj) + changeWithNodeId.obj = change.obj; + if (change.mods) + changeWithNodeId.mods = change.mods; + return changeWithNodeId; + })); + }).then(function () { + node.appliedRemoteRevision = remoteRevision; + return node.save(); + }); + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function bulkUpdate(table, changes) { + var keys = changes.map(function (c) { return c.key; }); + var map = {}; + // Retrieve current object of each change to update and map each + // found object's primary key to the existing object: + return table.where(':id').anyOf(keys).raw().each(function (obj, cursor) { + map[cursor.primaryKey + ''] = obj; + }).then(function () { + // Filter away changes whose key wasn't found in the local database + // (we can't update them if we do not know the existing values) + var updatesThatApply = changes.filter(function (c) { return map.hasOwnProperty(c.key + ''); }); + // Apply modifications onto each existing object (in memory) + // and generate array of resulting objects to put using bulkPut(): + var objsToPut = updatesThatApply.map(function (c) { + var curr = map[c.key + '']; + Object.keys(c.mods).forEach(function (keyPath) { + Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]); + }); + return curr; + }); + return table.bulkPut(objsToPut); + }); +} + +function initApplyChanges(db) { + return function applyChanges(changes) { + var collectedChanges = {}; + changes.forEach(function (change) { + var _a; + if (!collectedChanges.hasOwnProperty(change.table)) { + collectedChanges[change.table] = (_a = {}, _a[CREATE] = [], _a[DELETE] = [], _a[UPDATE] = [], _a); + } + collectedChanges[change.table][change.type].push(change); + }); + var table_names = Object.keys(collectedChanges); + var tables = table_names.map(function (table) { return db.table(table); }); + return db.transaction("rw", tables, function () { + table_names.forEach(function (table_name) { + var table = db.table(table_name); + var specifyKeys = !table.schema.primKey.keyPath; + var createChangesToApply = collectedChanges[table_name][CREATE]; + var deleteChangesToApply = collectedChanges[table_name][DELETE]; + var updateChangesToApply = collectedChanges[table_name][UPDATE]; + if (createChangesToApply.length > 0) + table.bulkPut(createChangesToApply.map(function (c) { return c.obj; }), specifyKeys ? + createChangesToApply.map(function (c) { return c.key; }) : undefined); + if (updateChangesToApply.length > 0) + bulkUpdate(table, updateChangesToApply); + if (deleteChangesToApply.length > 0) + table.bulkDelete(deleteChangesToApply.map(function (c) { return c.key; })); + }); + }); + }; +} + +function initFinallyCommitAllChanges(db, node) { + var applyChanges = initApplyChanges(db); + return function finallyCommitAllChanges(changes, remoteRevision) { + // 1. Open a write transaction on all tables in DB + var tablesToIncludeInTrans = db.tables.filter(function (table) { return table.name === '_changes' || + table.name === '_uncommittedChanges' || + table.schema.observable; }); + return db.transaction('rw!', tablesToIncludeInTrans, function () { + var trans = Dexie.currentTransaction; + var localRevisionBeforeChanges = 0; + return 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); + }).then(function () { + return db._uncommittedChanges.where('node').equals(node.id).delete(); + }).then(function () { + // 3. Apply last chunk of changes + return applyChanges(changes); + }).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; + } + } + } + // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction. + node.save().catch(function (err) { + console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: " + (err.stack || err)); + }); + }); + }); + }; +} + +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 hasn't yet become up-to-date with the 0 revision from client. + return { + maxClientRevision: node.remoteBaseRevisions[0].local, + remoteBaseRevision: null + }; +} + +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) { + Dexie.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) { + Dexie.setByKeyPath(clonedChange.mods[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.mods[subPath]; + }); + }); + return clonedChange; +} + +function mergeChange(prevChange, nextChange) { + 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; + } +} + +function initGetChangesSinceRevision(db, node, hasMoreToGive) { + return 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 = db._changes.where('rev').between(revision, maxRevision, false, true); + return query.until(function () { + if (numChanges === maxChanges) { + partial = true; + return true; + } + }).each(function (change) { + // Note the revision in nextRevision: + nextRevision = change.rev; + // change.source is set based on currentTransaction.source + if (change.source === ignoreSource) + return; + // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary 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 = mergeChange(prevChange, nextChange); + changeSet[id] = mergedChange; + } + }); + }).then(function () { + var changes = Object.keys(changeSet).map(function (key) { + return changeSet[key]; + }); + hasMoreToGive.hasMoreToGive = partial; + return cb(changes, partial, { myRevision: nextRevision }); + }); + }; +} + +function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) { + return 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.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 initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) { + var MAX_CHANGES_PER_CHUNK = partialsThreshold; + return 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. + var getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive); + var getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb); + // Only a "remote" SyncNode created by Dexie.Syncable + // could not pass this test (remote nodes have myRevision: -1 on instantiation) + if (node.myRevision >= 0) { + // Node is based on a revision in our local database and will just need to get the changes that have 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 the 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) { + // Initialize dbUploadState + var tablesToUpload = db.tables.filter(function (table) { + return table.schema.observable; + }).map(function (table) { + return table.name; + }); + if (tablesToUpload.length === 0) + return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced 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); + } + } + }; +} + +var Statuses = { + ERROR: -1, + OFFLINE: 0, + CONNECTING: 1, + ONLINE: 2, + SYNCING: 3, + ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect. +}; +var StatusTexts = { + "-1": "ERROR", + "0": "OFFLINE", + "1": "CONNECTING", + "2": "ONLINE", + "3": "SYNCING", + "4": "ERROR_WILL_RETRY" +}; + +var Promise$2 = Dexie.Promise; +function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) { + var enqueue = initEnqueue(db); + var hasMoreToGive = { hasMoreToGive: true }; + 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; + } + return function connectProtocol(node, activePeer) { + /// + var getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold); + var url = activePeer.url; + function changeStatusTo(newStatus) { + if (node.status !== newStatus) { + node.status = newStatus; + node.save().then(function () { + db.syncable.on.statusChanged.fire(newStatus, url); + // Also broadcast message to other nodes about the status + db.observable.broadcastMessage("syncStatusChanged", { newStatus: newStatus, url: url }, false); + }).catch('DatabaseClosedError', function () { + }); + } + } + activePeer.on('disconnect', function (newStatus) { + if (!isNaN(newStatus)) + changeStatusTo(newStatus); + }); + var connectedContinuation; + changeStatusTo(Statuses.CONNECTING); + return doSync(); + function doSync() { + // Use enqueue() to ensure only a single promise execution at a time. + return enqueue(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, sendChangesToProvider); + }, dbAliveID); + } + 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$2(function (resolve, reject) { + rejectConnectPromise.p = 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().catch('DatabaseClosedError', abortTheProvider); + } + }, 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! + return undefined; + }).finally(function () { + // In case error happens after connect, don't try reject the connect promise anymore. + // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon + // is active and this happens. It would fire unhandledrejection but that we do not want. + rejectConnectPromise.p = null; + }); + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + // 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); + return node.save(); + } + } + function abortTheProvider(error) { + activePeer.disconnect(Statuses.ERROR, error); + } + 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().catch('DatabaseClosedError', function () { + }); + return getLocalChangesForNode(node, autoAck); + } + else { + return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck); + } + }); + } + function applyRemoteChanges(remoteChanges, remoteRevision, partial /*, clear*/) { + var saveToUncommittedChanges = initSaveToUncommittedChanges(db, node); + var finallyCommitAllChanges = initFinallyCommitAllChanges(db, node); + return enqueue(applyRemoteChanges, function () { + if (!stillAlive()) + return Promise$2.reject(new Dexie.DatabaseClosedError()); + // FIXTHIS: Check what to do if clear() is true! + return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision)) + .catch(function (error) { + abortTheProvider(error); + return Promise$2.reject(error); + }); + }, dbAliveID); + } + // + // + // 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); + 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().catch('DatabaseClosedError', function () { + }); + // 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(function (ex) { + console.error("Got " + ex.message + " caught by reactToChanges"); + abortTheProvider(ex); + }); + } + 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().catch('DatabaseClosedError', function () { + }); + } + 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.hasMoreToGive) { + syncAgain(); + } + else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) { + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, connectedContinuation.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 initConnectFn(db, activePeers) { + return function connect(protocolInstance, protocolName, url, options, dbAliveID) { + /// + var existingPeer = activePeers.filter(function (peer) { + return peer.url === url; + }); + if (existingPeer.length > 0) { + var activePeer = existingPeer[0]; + var diffObject = {}; + Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject); + // Options have been changed + // We need to disconnect and reconnect + if (Object.keys(diffObject).length !== 0) { + return db.syncable.disconnect(url) + .then(function () { + return execConnect(); + }); + } + else { + // 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; + } + } + function execConnect() { + // Use an object otherwise we wouldn't be able to get the reject promise from + // connectProtocol + var rejectConnectPromise = { p: null }; + var connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise); + var getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url); + var connectPromise = getOrCreateSyncNode(options).then(function (node) { + return connectProtocol(node, activePeer); + }); + var disconnected = false; + var activePeer = { + url: url, + status: Statuses.OFFLINE, + connectPromise: connectPromise, + syncOptions: options, + on: Dexie.Events(null, "disconnect"), + disconnect: function (newStatus, error) { + var pos = activePeers.indexOf(activePeer); + if (pos >= 0) + activePeers.splice(pos, 1); + if (error && rejectConnectPromise.p) + rejectConnectPromise.p(error); + if (!disconnected) { + activePeer.on.disconnect.fire(newStatus, error); + } + disconnected = true; + } + }; + activePeers.push(activePeer); + return connectPromise; + } + return execConnect(); + }; +} + +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.8, Fri Jul 31 2020 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +// 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 Observable = Dexie.Observable; +function Syncable(db) { + /// + var activePeers = []; + var connectFn = initConnectFn(db, activePeers); + var syncableConnect = initSyncableConnect(db, connectFn); + 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.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject); + } + else if (msg.type === 'disconnect') { + db.syncable.disconnect(msg.message.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.message.newStatus, msg.message.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. + // We should connect to remote servers now. + // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR. + // Reason to reconnect to those with plain "ERROR" is that the ERROR state may occur when a database + // connection has been closed. The new master would then be expected to reconnect. + // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from + // an old closed one. + Dexie.ignoreTransaction(function () { return Dexie.vip(function () { + return db._syncNodes.where({ type: 'remote' }) + .filter(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { return Promise.all(connectedRemoteNodes.map(function (node) { + return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(function (e) { + console.warn("Dexie.Syncable: Could not connect to " + node.url + ". " + (e.stack || e)); + }); + })); }); + }); }).catch('DatabaseClosedError', function () { }); + } + }); + // "ready" subscriber for the master node that makes sure it will always connect to sync server + // when the database opens. It will not wait for the connection to complete, just initiate the + // connection so that it will continue syncing as long as the database is open. + // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure + // that db._localSyncNode exists and persisted before this subscriber kicks in. + 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!) + // This "ready" subscriber will never be the one performing the initial sync request, because + // even after calling db.syncable.connect(), there won't exist any "remote" sync node yet. + // Instead, db.syncable.connect() will subscribe to "ready" also, and that subscriber will be + // called after this one. There, in that subscriber, the initial sync request will take place + // and the "remote" node will be created so that this "ready" subscriber can auto-connect the + // next time this database is opened. + // CONCLUSION: We can always assume that the local DB has been in sync with the server at least + // once in the past for each "connectedRemoteNode" we find in query below. + // Don't halt db.ready while connecting (i.e. we do not return a promise here!) + db._syncNodes + .where('type').equals('remote') + .and(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { + // There are connected remote nodes that we must manage (or take over to manage) + connectedRemoteNodes.forEach(function (node) { return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions) + .catch(function () { }); } // A failure will be triggered in on('statusChanged'). We can ignore. + ); + }).catch('DatabaseClosedError', function () { }); + } + }, 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.getOptions = function (url, cb) { + return db.transaction('r?', db._syncNodes, function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node.syncOptions; + }).then(cb); + }); + }; + db.syncable.list = function () { + return db.transaction('r?', db._syncNodes, 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) { + return Dexie.ignoreTransaction(function () { + return Promise.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise.all(activePeers.filter(function (peer) { return peer.url === url; }).map(function (peer) { + return peer.disconnect(Statuses.OFFLINE); + })); + } + else { + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, { wantReply: true }); + }); + } + }).then(function () { + 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) { + return syncableConnect(protocolInstance, protocolName, url, options); + } + else { + return Promise.reject(new Error("ISyncProtocol '" + protocolName + "' is not registered in Dexie.Syncable.registerSyncProtocol()")); + } + }; + db.syncable.delete = function (url) { + return db.syncable.disconnect(url).then(function () { + return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, function () { + // Find the node(s) + // Several can be found, as detected by @martindiphoorn, + // let's delete them and cleanup _uncommittedChanges and _changes + // accordingly. + var nodeIDsToDelete; + return db._syncNodes + .where("url").equals(url) + .toArray(function (nodes) { return nodes.map(function (node) { return node.id; }); }) + .then(function (nodeIDs) { + nodeIDsToDelete = nodeIDs; + // Delete the syncNode that represents the remote endpoint. + return db._syncNodes.where('id').anyOf(nodeIDs).delete(); + }) + .then(function () { + // In case there were uncommittedChanges belonging to this, delete them as well + return db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete(); + }); + }).then(function () { + // Spawn background job to delete old changes, now that a node has been deleted, + // there might be changes in _changes table that is not needed to keep anymore. + // This is done in its own transaction, or possible several transaction to prohibit + // starvation + Observable.deleteOldChanges(db); + }); + }); + }; + db.syncable.unsyncedChanges = function (url) { + return db._syncNodes.where("url").equals(url).first(function (node) { + return db._changes.where('rev').above(node.myRevision).toArray(); + }); + }; + db.close = override(db.close, function (origClose) { + return function () { + activePeers.forEach(function (peer) { + peer.disconnect(); + }); + return origClose.apply(this, arguments); + }; + }); + Object.defineProperty(db.observable.SyncNode.prototype, 'save', { + enumerable: false, + configurable: true, + writable: true, + value: function () { + var _this = this; + return db.transaction('rw?', db._syncNodes, function () { + return db._syncNodes.put(_this); + }); + } + }); +} +Syncable.Statuses = Statuses; +Syncable.StatusTexts = StatusTexts; +Syncable.registeredProtocols = {}; // Map when key is the provider name. +Syncable.registerSyncProtocol = function (name, protocolInstance) { + /// + /// Register a synchronization protocol that can synchronize databases with remote servers. + /// + /// Provider name + /// Implementation of ISyncProtocol + var partialsThreshold = protocolInstance.partialsThreshold; + if (typeof partialsThreshold === 'number') { + // Don't allow NaN or negative threshold + if (isNaN(partialsThreshold) || partialsThreshold < 0) { + throw new Error('The given number for the threshold is not supported'); + } + // If the threshold is 0 we will not send any client changes but will get server changes + } + else { + // Use Infinity as the default so simple protocols don't have to care about partial synchronization + protocolInstance.partialsThreshold = Infinity; + } + 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..5c9f29645 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-syncable.js","sources":["../src/syncable-connect.js","../src/PersistedContext.js","../src/get-or-create-sync-node.js","../src/enqueue.js","../src/save-to-uncommitted-changes.js","../src/change_types.js","../src/bulk-update.js","../src/apply-changes.js","../src/finally-commit-all-changes.js","../src/get-local-changes-for-node/get-base-revision-and-max-client-revision.js","../src/combine-create-and-update.js","../src/combine-update-and-update.js","../src/merge-change.js","../src/get-local-changes-for-node/get-changes-since-revision.js","../src/get-local-changes-for-node/get-table-objects-as-changes.js","../src/get-local-changes-for-node/get-local-changes-for-node.js","../src/statuses.js","../src/connect-protocol.js","../src/connect-fn.js","../src/Dexie.Syncable.js"],"sourcesContent":["import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initSyncableConnect(db, connect) {\n return function syncableConnect(protocolInstance, protocolName, url, options) {\n if (db.isOpen()) {\n // Database is open\n if (!db._localSyncNode)\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\n\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 return 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.observable.sendMessage('connect', {\n protocolName: protocolName,\n url: url,\n options: options\n }, masterNode.id, {wantReply: true});\n });\n }\n } else if (db.hasBeenClosed()) {\n // Database has been closed.\n return Promise.reject(new Dexie.DatabaseClosedError());\n } else if (db.hasFailed()) {\n // Database has failed to open\n return Promise.reject(new Dexie.InvalidStateError(\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\n } else {\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\n // Wait for it to open, then connect.\n var promise = new Promise(function (resolve, reject) {\n db.on(\"ready\", () => {\n // First, check if this is the very first time we connect to given URL.\n // Need to know, because if it is, we should stall the promise returned to\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\n return db._syncNodes.get({url}, node => {\n // Ok, now we know whether we should await the connect promise or not.\n // No matter, we should now connect (will maybe create the SyncNode instance\n // representing the given URL)\n let connectPromise = db.syncable.connect(protocolName, url, options);\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\n // Ok, so let's see if we should suspend DB queries until connected or not:\n if (node && node.appliedRemoteRevision) {\n // The very first initial sync has been done so we need not wait\n // for the connect promise to complete. It can continue in background.\n // Returning here will resume db.on('ready') and resume all queries that\n // the application has put to the database.\n return;\n }\n // This was the very first time we connect to the remote server,\n // we must make sure that the initial sync request succeeeds before resuming\n // database queries that the application code puts onto the database.\n // If OFFLINE or other error, don't allow the application to proceed.\n // We are assuming that an initial sync is essential for the application to\n // function correctly.\n return connectPromise;\n });\n });\n // Force open() to happen. Otherwise connect() may stall forever.\n db.open().catch(ex => {\n // If open fails, db.on('ready') may not have been called and we must\n // reject promise with InvalidStateError\n reject(new Dexie.InvalidStateError(\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\n ex\n ));\n });\n });\n return promise;\n }\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initPersistedContext(node) {\n //\n // PersistedContext : IPersistedContext\n //\n return class PersistedContext {\n constructor(nodeID, otherProps) {\n this.nodeID = nodeID;\n if (otherProps) Dexie.extend(this, otherProps);\n }\n\n save() {\n // Store this instance in the syncContext property of the node it belongs to.\n return Dexie.vip(() => {\n return node.save();\n });\n }\n }\n}\n","import Dexie from 'dexie';\n\nimport initPersistedContext from './PersistedContext';\n\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\n return function getOrCreateSyncNode(options) {\n return db.transaction('rw', db._syncNodes, db._changes, function () {\n if (!url) throw new Error(\"Url cannot be empty\");\n\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\n // maps to class\n if (node) {\n const PersistedContext = initPersistedContext(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 node.syncOptions = options; // Options could have been changed\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 const PersistedContext = initPersistedContext(node);\n Dexie.Promise.resolve(function () {\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\n if (options.initialUpload === false)\n return db._changes.toCollection().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","import Dexie from 'dexie';\n\nexport default function initEnqueue(db) {\n return function enqueue(context, fn, instanceID) {\n function _enqueue() {\n if (!context.ongoingOperation) {\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\n return Dexie.vip(function () {\n return fn();\n });\n }).finally(()=> {\n delete context.ongoingOperation;\n });\n } else {\n context.ongoingOperation = context.ongoingOperation.then(function () {\n return enqueue(context, fn, instanceID);\n });\n }\n return context.ongoingOperation;\n }\n\n if (!instanceID) {\n // Caller wants to enqueue it until database becomes open.\n if (db.isOpen()) {\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\n // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB)\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n };\n}\n","export default function initSaveToUncommittedChanges(db, node) {\n return function saveToUncommittedChanges(changes, remoteRevision) {\n return db.transaction('rw!', db._uncommittedChanges, () => {\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\n let changeWithNodeId = {\n node: node.id,\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.obj) changeWithNodeId.obj = change.obj;\n if (change.mods) changeWithNodeId.mods = change.mods;\n return changeWithNodeId;\n }));\n }).then(() => {\n node.appliedRemoteRevision = remoteRevision;\n return node.save();\n });\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nexport default function bulkUpdate(table, changes) {\n let keys = changes.map(c => c.key);\n let map = {};\n // Retrieve current object of each change to update and map each\n // found object's primary key to the existing object:\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\n map[cursor.primaryKey+''] = obj;\n }).then(()=>{\n // Filter away changes whose key wasn't found in the local database\n // (we can't update them if we do not know the existing values)\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\n // Apply modifications onto each existing object (in memory)\n // and generate array of resulting objects to put using bulkPut():\n let objsToPut = updatesThatApply.map (c => {\n let curr = map[c.key+''];\n Object.keys(c.mods).forEach(keyPath => {\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\n });\n return curr;\n });\n return table.bulkPut(objsToPut);\n });\n}\n","import { CREATE, DELETE, UPDATE } from './change_types';\nimport bulkUpdate from './bulk-update';\n\nexport default function initApplyChanges(db) {\n return function applyChanges(changes) {\n let collectedChanges = {};\n changes.forEach((change) => {\n if (!collectedChanges.hasOwnProperty(change.table)) {\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\n }\n collectedChanges[change.table][change.type].push(change);\n });\n let table_names = Object.keys(collectedChanges);\n let tables = table_names.map((table) => db.table(table));\n\n return db.transaction(\"rw\", tables, () => {\n table_names.forEach((table_name) => {\n const table = db.table(table_name);\n const specifyKeys = !table.schema.primKey.keyPath;\n const createChangesToApply = collectedChanges[table_name][CREATE];\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\n if (createChangesToApply.length > 0)\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\n createChangesToApply.map(c => c.key) : undefined);\n if (updateChangesToApply.length > 0)\n bulkUpdate(table, updateChangesToApply);\n if (deleteChangesToApply.length > 0)\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\n });\n });\n };\n}\n","import Dexie from 'dexie';\nimport initApplyChanges from './apply-changes';\n\nexport default function initFinallyCommitAllChanges(db, node) {\n const applyChanges = initApplyChanges(db);\n\n return function finallyCommitAllChanges(changes, remoteRevision) {\n // 1. Open a write transaction on all tables in DB\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\n table.name === '_uncommittedChanges' ||\n table.schema.observable);\n\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\n var trans = Dexie.currentTransaction;\n var localRevisionBeforeChanges = 0;\n return 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(() => {\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);\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);\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 // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\n node.save().catch(err=> {\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\n });\n });\n });\n };\n}\n","export default function getBaseRevisionAndMaxClientRevision(node) {\n /// \n if (node.remoteBaseRevisions.length === 0)\n 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 hasn't 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","import Dexie from 'dexie';\n\nexport default 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 Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\n });\n return clonedChange;\n}\n","import Dexie from 'dexie';\n\nexport default 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) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\n Dexie.setByKeyPath(clonedChange.mods[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) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\n delete clonedChange.mods[subPath];\n });\n });\n return clonedChange;\n}\n","import { CREATE, UPDATE, DELETE } from './change_types';\nimport combineCreateAndUpdate from './combine-create-and-update.js';\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\n\nexport default function mergeChange(prevChange, nextChange) {\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","import {CREATE, UPDATE} from '../change_types';\nimport mergeChange from '../merge-change';\n\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\n return 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 = db._changes.where('rev').between(revision, maxRevision, false, true);\n return query.until(() => {\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 // change.source is set based on currentTransaction.source\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 necessary info:\n var changeToSend = {\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.type === CREATE)\n changeToSend.obj = change.obj;\n else if (change.type === UPDATE)\n 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 = mergeChange(prevChange, nextChange);\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.hasMoreToGive = partial;\n return cb(changes, partial, {myRevision: nextRevision});\n });\n };\n}\n","import {CREATE} from '../change_types';\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\n\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\n return 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.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","import Dexie from 'dexie';\n\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\nimport initGetChangesSinceRevision from './get-changes-since-revision';\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\n\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\n\n return 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 const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\n\n // Only a \"remote\" SyncNode created by Dexie.Syncable\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\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 have 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 the 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 // Initialize 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 Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced 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 const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n } else {\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n }\n }\n };\n}\n","export const Statuses = {\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\n OFFLINE: 0, // The sync provider hasn't 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 occurred such as net down but the sync provider will retry to connect.\n};\n\nexport const StatusTexts = {\n \"-1\": \"ERROR\",\n \"0\": \"OFFLINE\",\n \"1\": \"CONNECTING\",\n \"2\": \"ONLINE\",\n \"3\": \"SYNCING\",\n \"4\": \"ERROR_WILL_RETRY\"\n};\n","import Dexie from 'dexie';\n\nimport initEnqueue from './enqueue';\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\nimport {Statuses} from './statuses';\n\nconst Promise = Dexie.Promise;\n\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\n const enqueue = initEnqueue(db);\n var hasMoreToGive = {hasMoreToGive: true};\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 return function connectProtocol(node, activePeer) {\n /// \n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\n\n const url = activePeer.url;\n\n function changeStatusTo(newStatus) {\n if (node.status !== newStatus) {\n node.status = newStatus;\n node.save().then(()=> {\n db.syncable.on.statusChanged.fire(newStatus, url);\n // Also broadcast message to other nodes about the status\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\n }).catch('DatabaseClosedError', ()=> {\n });\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 enqueue() to ensure only a single promise execution at a time.\n return enqueue(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, sendChangesToProvider);\n }, dbAliveID);\n }\n\n 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.p = function (err) {\n reject(err);\n };\n Dexie.asap(function () {\n try {\n protocolInstance.sync(\n node.syncContext,\n url,\n options,\n remoteBaseRevision,\n node.appliedRemoteRevision,\n changes,\n partial,\n applyRemoteChanges,\n onChangesAccepted,\n function (continuation) {\n resolve(continuation);\n },\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().catch('DatabaseClosedError', abortTheProvider);\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 return undefined;\n }).finally(()=> {\n // In case error happens after connect, don't try reject the connect promise anymore.\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\n // is active and this happens. It would fire unhandledrejection but that we do not want.\n rejectConnectPromise.p = null;\n });\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\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 return node.save();\n }\n }\n\n function abortTheProvider(error) {\n activePeer.disconnect(Statuses.ERROR, error);\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().catch('DatabaseClosedError', ()=> {\n });\n return getLocalChangesForNode(node, autoAck);\n } else {\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\n }\n });\n }\n\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\n\n return enqueue(applyRemoteChanges, function () {\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\n // FIXTHIS: Check what to do if clear() is true!\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\n .catch(function (error) {\n abortTheProvider(error);\n return Promise.reject(error);\n });\n }, dbAliveID);\n }\n\n //\n //\n // Continuation Patterns Follows\n //\n //\n\n function continueSendingChanges(continuation) {\n if (!stillAlive()) { // Database was closed.\n if (continuation.disconnect)\n 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 }\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)\n changesWaiting = true;\n else {\n reactToChanges();\n }\n }\n }\n\n db.on('changes', onChanges);\n\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().catch('DatabaseClosedError', ()=> {\n });\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(ex => {\n console.error(`Got ${ex.message} caught by reactToChanges`);\n abortTheProvider(ex);\n });\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().catch('DatabaseClosedError', ()=> {\n });\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.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 } 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","import Dexie from 'dexie';\n\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\nimport initConnectProtocol from './connect-protocol';\nimport {Statuses} from './statuses';\n\nexport default function initConnectFn(db, activePeers) {\n return 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 const activePeer = existingPeer[0];\n const diffObject = {};\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\n // Options have been changed\n // We need to disconnect and reconnect\n if (Object.keys(diffObject).length !== 0) {\n return db.syncable.disconnect(url)\n .then(() => {\n return execConnect();\n })\n } else {\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\n function execConnect() {\n // Use an object otherwise we wouldn't be able to get the reject promise from\n // connectProtocol\n var rejectConnectPromise = {p: null};\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\n return connectProtocol(node, activePeer);\n });\n\n var disconnected = false;\n var activePeer = {\n url: url,\n status: Statuses.OFFLINE,\n connectPromise: connectPromise,\n syncOptions: options,\n on: Dexie.Events(null, \"disconnect\"),\n disconnect: function (newStatus, error) {\n var pos = activePeers.indexOf(activePeer);\n if (pos >= 0) activePeers.splice(pos, 1);\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\n if (!disconnected) {\n activePeer.on.disconnect.fire(newStatus, error);\n }\n disconnected = true;\n }\n };\n activePeers.push(activePeer);\n\n return connectPromise;\n }\n\n return execConnect();\n };\n}\n","/* ========================================================================== \n * dexie-syncable.js\n * ==========================================================================\n *\n * Dexie addon for syncing indexedDB with remote endpoints.\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \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\nimport initSyncableConnect from './syncable-connect';\nimport initConnectFn from './connect-fn';\nimport {Statuses, StatusTexts} from './statuses';\n\nvar override = Dexie.override,\n Promise = Dexie.Promise,\n Observable = Dexie.Observable;\n\nexport default function Syncable (db) {\n /// \n\n var activePeers = [];\n\n const connectFn = initConnectFn(db, activePeers);\n const syncableConnect = initSyncableConnect(db, connectFn);\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.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\n } else if (msg.type === 'disconnect') {\n db.syncable.disconnect(msg.message.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.message.newStatus, msg.message.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 // We should connect to remote servers now.\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\n // connection has been closed. The new master would then be expected to reconnect.\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\n // an old closed one. \n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\n return db._syncNodes.where({type: 'remote'})\n .filter(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\n })\n )));\n })).catch('DatabaseClosedError', ()=>{});\n }\n });\n\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\n // when the database opens. It will not wait for the connection to complete, just initiate the\n // connection so that it will continue syncing as long as the database is open.\n\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\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 // This \"ready\" subscriber will never be the one performing the initial sync request, because\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\n // called after this one. There, in that subscriber, the initial sync request will take place\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\n // next time this database is opened.\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\n // once in the past for each \"connectedRemoteNode\" we find in query below.\n\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\n db._syncNodes\n .where('type').equals('remote')\n .and(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => {\n // There are connected remote nodes that we must manage (or take over to manage)\n connectedRemoteNodes.forEach(\n node => db.syncable.connect(\n node.syncProtocol,\n node.url,\n node.syncOptions) \n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\n );\n }).catch('DatabaseClosedError', ()=>{});\n }\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\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.getOptions = function(url, cb) {\n return db.transaction('r?', db._syncNodes, () => {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node.syncOptions;\n }).then(cb);\n });\n };\n\n db.syncable.list = function() {\n return db.transaction('r?', db._syncNodes, ()=>{\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\n return a.map(function(node) { return node.url; });\n });\n });\n };\n\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\n\n db.syncable.disconnect = function(url) {\n return Dexie.ignoreTransaction(()=>{\n return Promise.resolve().then(()=>{\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\n return peer.disconnect(Statuses.OFFLINE);\n }));\n } else {\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\n });\n }\n }).then(()=>{\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\n node.status = Statuses.OFFLINE;\n });\n });\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 if (protocolInstance) {\n return syncableConnect(protocolInstance, protocolName, url, options);\n } else {\n return Promise.reject(\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\n );\n }\n };\n\n db.syncable.delete = function(url) {\n return db.syncable.disconnect(url).then(()=>{\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\n // Find the node(s)\n // Several can be found, as detected by @martindiphoorn,\n // let's delete them and cleanup _uncommittedChanges and _changes \n // accordingly.\n let nodeIDsToDelete;\n return db._syncNodes\n .where(\"url\").equals(url)\n .toArray(nodes => nodes.map(node => node.id))\n .then(nodeIDs => {\n nodeIDsToDelete = nodeIDs;\n // Delete the syncNode that represents the remote endpoint.\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\n })\n .then (() =>\n // In case there were uncommittedChanges belonging to this, delete them as well\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\n }).then(()=> {\n // Spawn background job to delete old changes, now that a node has been deleted,\n // there might be changes in _changes table that is not needed to keep anymore.\n // This is done in its own transaction, or possible several transaction to prohibit\n // starvation\n Observable.deleteOldChanges(db);\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 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 Object.defineProperty(\n db.observable.SyncNode.prototype,\n 'save', {\n enumerable: false,\n configurable: true,\n writable: true,\n value() {\n return db.transaction('rw?', db._syncNodes, () => {\n return db._syncNodes.put(this);\n });\n }\n });\n}\n\nSyncable.Statuses = Statuses;\n\nSyncable.StatusTexts = StatusTexts;\n\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\n\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\n /// \n /// Register a synchronization protocol that can synchronize databases with remote servers.\n /// \n /// Provider name\n /// Implementation of ISyncProtocol\n const partialsThreshold = protocolInstance.partialsThreshold;\n if (typeof partialsThreshold === 'number') {\n // Don't allow NaN or negative threshold\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\n throw new Error('The given number for the threshold is not supported');\n }\n // If the threshold is 0 we will not send any client changes but will get server changes\n } else {\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\n protocolInstance.partialsThreshold = Infinity;\n }\n Syncable.registeredProtocols[name] = protocolInstance;\n};\n\n// Register addon in Dexie:\nDexie.Syncable = Sy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AAE;QACJ,UAAU,EAAE,KAAK;QACjB,YAAY,EAAE,IAAI;QAClB,QAAQ,EAAE,IAAI;QACd,KAAK;YAAL,iBAIH;YAHO,OAAO,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,EAAE;gBACxC,OAAO,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,KAAI,CAAC,CAAC;aACtC,CAAC,CAAC;SACN;KACH,CAAC,CAAC;CACP;AAED,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAE7B,QAAQ,CAAC,WAAW,GAAG,WAAW,CAAC;AAEnC,QAAQ,CAAC,mBAAmB,GAAG,EAAE,CAAC;AAElC,QAAQ,CAAC,oBAAoB,GAAG,UAAS,IAAI,EAAE,gBAAgB;;;;;;IAM3D,IAAM,iBAAiB,GAAG,gBAAgB,CAAC,iBAAiB,CAAC;IAC7D,IAAI,OAAO,iBAAiB,KAAK,QAAQ,EAAE;;QAEvC,IAAI,KAAK,CAAC,iBAAiB,CAAC,IAAI,iBAAiB,GAAG,CAAC,EAAE;YACnD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;SAC1E;;KAEJ;SAAM;;QAEH,gBAAgB,CAAC,iBAAiB,GAAG,QAAQ,CAAC;KACjD;IACD,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,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..47b2e25a3 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.min.js @@ -0,0 +1 @@ +(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))})(this,function(R){"use strict";var s=(R="default"in R?R.default:R).Promise;function d(e){return n.prototype.save=function(){return R.vip(function(){return e.save()})},n;function n(e,n){this.nodeID=e,n&&R.extend(this,n)}}var y=1,h=2,u=3;function O(a){return function(e){var c={};e.forEach(function(e){var n;c.hasOwnProperty(e.table)||(c[e.table]=((n={})[y]=[],n[u]=[],n[h]=[],n)),c[e.table][e.type].push(e)});var n=Object.keys(c),t=n.map(function(e){return a.table(e)});return a.transaction("rw",t,function(){n.forEach(function(e){var n=a.table(e),t=!n.schema.primKey.keyPath,r=c[e][y],o=c[e][u],i=c[e][h];0=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 b(e,n){switch(e.type){case y:switch(n.type){case y:return n;case h:return function(e,n){var t=R.deepClone(e);return Object.keys(n.mods).forEach(function(e){R.setByKeyPath(t.obj,e,n.mods[e])}),t}(e,n);case u:return n}break;case h:switch(n.type){case y:return n;case h:return function(e,r){var o=R.deepClone(e);return Object.keys(r.mods).forEach(function(n){var t=!1;Object.keys(e.mods).filter(function(e){return 0===n.indexOf(e+".")}).forEach(function(e){R.setByKeyPath(o.mods[e],n.substr(e.length+1),r.mods[n]),t=!0}),t||(o.mods[n]=r.mods[n]),Object.keys(e.mods).filter(function(e){return 0===e.indexOf(n+".")}).forEach(function(e){delete o.mods[e]})}),o}(e,n);case u:return n}break;case u:switch(n.type){case y:return n;case h:case u:return e}}}function o(s,u,e){var l=e;return function(e,r){var n=function(u,l,f){return function(e,n,t,r){var i={},c=0,o=!1,a=l.id,s=e;return u.transaction("r",u._changes,function(){return u._changes.where("rev").between(e,t,!1,!0).until(function(){if(c===n)return o=!0}).each(function(e){if(s=e.rev,e.source!==a){var n={type:e.type,table:e.table,key:e.key};e.type===y?n.obj=e.obj:e.type===h&&(n.mods=e.mods);var t=e.table+":"+e.key,r=i[t];if(r){var o=b(r,n);i[t]=o}else i[t]=n,++c}})}).then(function(){var e=Object.keys(i).map(function(e){return i[e]});return f.hasMoreToGive=o,r(e,o,{myRevision:s})})}}(s,e,u),t=function(c,a,s,u,l,f){return function e(t,o,n){var i=!1;return n.until(function(){if(o.length===s)return i=!0}).each(function(e,n){o.push({type:y,table:t.currentTable,key:n.key,obj:n.value}),t.currentKey=n.key}).then(function(){if(i)return l.hasMoreToGive=!0,f(o,null,!0,{dbUploadState:t});if(0!==t.tablesToUpload.length)return t.currentTable=t.tablesToUpload.shift(),e(t,o,c.table(t.currentTable).orderBy(":id"));var r=v(a);return u(t.localBaseRevision,s-o.length,r.maxClientRevision,function(e,n,t){return o=o.concat(e),t.dbUploadState=null,f(o,r.remoteBaseRevision,n,t)})})}}(s,e,l,n,u,r);if(0<=e.myRevision){var o=v(e);return n(e.myRevision,l,o.maxClientRevision,function(e,n,t){return r(e,o.remoteBaseRevision,n,t)})}if(null===e.dbUploadState){var i=s.tables.filter(function(e){return e.schema.observable}).map(function(e){return e.name});if(0===i.length)return R.Promise.resolve(r([],null,!1,{}));var c={tablesToUpload:i,currentTable:i.shift(),currentKey:null};return s._changes.orderBy("rev").last(function(e){c.localBaseRevision=e&&e.rev||0;var n=s.table(c.currentTable).orderBy(":id");return t(c,[],n)})}if(e.dbUploadState.currentKey){var a=s.table(e.dbUploadState.currentTable).where(":id").above(e.dbUploadState.currentKey);return t(R.deepClone(e.dbUploadState),[],a)}a=s.table(c.currentTable).orderBy(":id");return t(R.deepClone(e.dbUploadState),[],a)}}var E={ERROR:-1,OFFLINE:0,CONNECTING:1,ONLINE:2,SYNCING:3,ERROR_WILL_RETRY:4},w=R.Promise;function p(b,p,i,m,N){var c=function(i){return function e(n,t,r){function o(){return n.ongoingOperation?n.ongoingOperation=n.ongoingOperation.then(function(){return e(n,t,r)}):n.ongoingOperation=R.ignoreTransaction(function(){return R.vip(function(){return t()})}).finally(function(){delete n.ongoingOperation}),n.ongoingOperation}return r?i._localSyncNode&&r===i._localSyncNode.id?o():R.Promise.reject(new R.DatabaseClosedError):i.isOpen()?o():R.Promise.reject(new R.DatabaseClosedError)}}(b),t={hasMoreToGive:!0};function g(){return b._localSyncNode&&b._localSyncNode.id===i}return function(s,u){var l,a=o(b,t,p.partialsThreshold),f=u.url;function d(e){s.status!==e&&(s.status=e,s.save().then(function(){b.syncable.on.statusChanged.fire(e,f),b.observable.broadcastMessage("syncStatusChanged",{newStatus:e,url:f},!1)}).catch("DatabaseClosedError",function(){}))}return u.on("disconnect",function(e){isNaN(e)||d(e)}),d(E.CONNECTING),y();function y(){return c(y,function(){return n(s,e)},i)}function e(e,o,i,n){var t=new w(function(t,r){N.p=function(e){r(e)},R.asap(function(){try{p.sync(s.syncContext,f,m,o,s.appliedRemoteRevision,e,i,v,c,function(e){t(e)},n)}catch(e){n(e,1/0)}function n(e,n){r(e),g()&&(!isNaN(n)&&n<1/0?(setTimeout(function(){g()&&(d(E.SYNCING),y().catch("DatabaseClosedError",h))},n),d(E.ERROR_WILL_RETRY),l&&l.disconnect&&l.disconnect(),l=null):h(e))}})});return t.then(function(){}).finally(function(){N.p=null});function c(){return Object.keys(n).forEach(function(e){R.setByKeyPath(s,e,n[e])}),t.then(r),s.save()}}function h(e){u.disconnect(E.ERROR,e)}function n(i,c){return a(i,function e(n,t,r,o){return 0===n.length&&"myRevision"in o&&o.myRevision!==i.myRevision?(Object.keys(o).forEach(function(e){R.setByKeyPath(i,e,o[e])}),i.save().catch("DatabaseClosedError",function(){}),a(i,e)):c(n,t,r,o)})}function v(e,n,t){var r=function(t,r){return function(e,n){return t.transaction("rw!",t._uncommittedChanges,function(){return t._uncommittedChanges.bulkAdd(e.map(function(e){var n={node:r.id,type:e.type,table:e.table,key:e.key};return e.obj&&(n.obj=e.obj),e.mods&&(n.mods=e.mods),n}))}).then(function(){return r.appliedRemoteRevision=n,r.save()})}}(b,s),o=function(t,i){var c=O(t);return function(n,o){var e=t.tables.filter(function(e){return"_changes"===e.name||"_uncommittedChanges"===e.name||e.schema.observable});return t.transaction("rw!",e,function(){var e=R.currentTransaction,r=0;return t._changes.orderBy("rev").last(function(e){r=e&&e.rev||0}).then(function(){return e.source=i.id,t._uncommittedChanges.where("node").equals(i.id).toArray()}).then(function(e){return c(e)}).then(function(){return t._uncommittedChanges.where("node").equals(i.id).delete()}).then(function(){return c(n)}).then(function(){return t._changes.orderBy("rev").last()}).then(function(e){var n=e&&e.rev||0;if(i.appliedRemoteRevision=o,i.remoteBaseRevisions.push({remote:o,local:n}),i.myRevision===r&&(i.myRevision=n),1=i.remoteBaseRevisions[t].local){i.remoteBaseRevisions.splice(0,t);break}i.save().catch(function(e){console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: "+(e.stack||e))})})})}}(b,s);return c(v,function(){return g()?(t?r(e,n):o(e,n)).catch(function(e){return h(e),w.reject(e)}):w.reject(new R.DatabaseClosedError)},i)}function r(e){g()?(l=e,u.on("disconnect",function(){if(l){if(l.react)try{l.disconnect()}catch(e){}l=null}}),e.react?function(o){var i,c;function e(){l&&(d(E.SYNCING),c?i=!0:a())}function a(){l&&(c=!(i=!1),n(s,function(e,n,t,r){l&&(0 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + function getSchemaString(table) { + var primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes); + return primKeyAndIndexes.map(function (index) { return index.src; }).join(','); + } + function extractDbSchema(exportedDb) { + var schema = {}; + for (var _i = 0, _a = exportedDb.tables; _i < _a.length; _i++) { + var table = _a[_i]; + schema[table.name] = table.schema; + } + return schema; + } + function readBlobAsync(blob, type) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onabort = function (ev) { return reject(new Error("file read aborted")); }; + reader.onerror = function (ev) { return reject(ev.target.error); }; + reader.onload = function (ev) { return resolve(ev.target.result); }; + if (type === 'binary') + reader.readAsArrayBuffer(blob); + else + reader.readAsText(blob); + }); + } + function readBlobSync(blob, type) { + if (typeof FileReaderSync === 'undefined') { + throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.'); + } + var reader = new FileReaderSync(); // Requires worker environment + var data = type === 'binary' ? + reader.readAsArrayBuffer(blob) : + reader.readAsText(blob); + return data; + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var typeson = createCommonjsModule(function (module, exports) { + !function(e,n){module.exports=n();}(commonjsGlobal,function(){var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=function(){return function(e,n){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function sliceIterator(e,n){var t=[],r=!0,i=!1,o=void 0;try{for(var s,c=e[Symbol.iterator]();!(r=(s=c.next()).done)&&(t.push(s.value),!n||t.length!==n);r=!0);}catch(e){i=!0,o=e;}finally{try{!r&&c.return&&c.return();}finally{if(i)throw o}}return t}(e,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),t=function(e){if(Array.isArray(e)){for(var n=0,t=Array(e.length);n2&&void 0!==arguments[2]?arguments[2]:{};return t.returnTypeNames=!0,this.encapsulate(e,n,t)},this.rootTypeName=function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.iterateNone=!0,this.encapsulate(e,n,t)};var l=this.encapsulate=function(y,p,f){var l=(f=Object.assign({sync:!0},o,f)).sync,h={},v=[],d=[],b=[],O=!(f&&"cyclic"in f)||f.cyclic,m=f.encapsulateObserver,T=_encapsulate("",y,O,p||{},b);function finish(e){var n=Object.values(h);if(f.iterateNone)return n.length?n[0]:Typeson.getJSONType(e);if(n.length){if(f.returnTypeNames)return [].concat(t(new Set(n)));e&&isPlainObject(e)&&!e.hasOwnProperty("$types")?e.$types=h:e={$:e,$types:{$:h}};}else isObject(e)&&e.hasOwnProperty("$types")&&(e={$:e,$types:!0});return !f.returnTypeNames&&e}return b.length?l&&f.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(e,t){return Promise.all(t.map(function(e){return e[1].p})).then(function(r){return Promise.all(r.map(function(r){var i=[],o=t.splice(0,1)[0],s=n(o,7),c=s[0],a=s[2],u=s[3],y=s[4],p=s[5],f=s[6],l=_encapsulate(c,r,a,u,i,!0,f),h=hasConstructorOf(l,TypesonPromise);return c&&h?l.p.then(function(n){return y[p]=n,checkPromises(e,i)}):(c?y[p]=l:e=h?l.p:l,checkPromises(e,i))}))}).then(function(){return e})}(T,b)).then(finish):!l&&f.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():f.stringification&&l?[finish(T)]:l?finish(T):Promise.resolve(finish(T));function _adaptBuiltinStateObjectProperties(e,n,t){Object.assign(e,n);var r=u.map(function(n){var t=e[n];return delete e[n],t});t(),u.forEach(function(n,t){e[n]=r[t];});}function _encapsulate(n,t,o,c,a,u,y){var p=void 0,l={},b=void 0===t?"undefined":e(t),O=m?function(e){var r=y||c.type||Typeson.getJSONType(t);m(Object.assign(e||l,{keypath:n,value:t,cyclic:o,stateObj:c,promisesData:a,resolvingTypesonPromise:u,awaitingTypesonPromise:hasConstructorOf(t,TypesonPromise)},void 0!==r?{type:r}:{}));}:null;if(b in{string:1,boolean:1,number:1,undefined:1})return void 0===t||"number"===b&&(isNaN(t)||t===-1/0||t===1/0)?(p=replace(n,t,c,a,!1,u,O))!==t&&(l={replaced:p}):p=t,O&&O(),p;if(null===t)return O&&O(),t;if(o&&!c.iterateIn&&!c.iterateUnsetNumeric){var T=v.indexOf(t);if(!(T<0))return h[n]="#",O&&O({cyclicKeypath:d[T]}),"#"+d[T];!0===o&&(v.push(t),d.push(n));}var g=isPlainObject(t),P=i(t),j=(g||P)&&(!s.length||c.replaced)||c.iterateIn?t:replace(n,t,c,a,g||P,null,O),S=void 0;if(j!==t?(p=j,l={replaced:j}):P||"array"===c.iterateIn?(S=new Array(t.length),l={clone:S}):g||"object"===c.iterateIn?l={clone:S={}}:""===n&&hasConstructorOf(t,TypesonPromise)?(a.push([n,t,o,c,void 0,void 0,c.type]),p=t):p=t,O&&O(),f.iterateNone)return S||p;if(!S)return p;if(c.iterateIn){var w=function _loop(e){var r={ownKeys:t.hasOwnProperty(e)};_adaptBuiltinStateObjectProperties(c,r,function(){var r=n+(n?".":"")+escapeKeyPathComponent(e),i=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(i,TypesonPromise)?a.push([r,i,!!o,c,S,e,c.type]):void 0!==i&&(S[e]=i);});};for(var A in t)w(A);O&&O({endIterateIn:!0,end:!0});}else r(t).forEach(function(e){var r=n+(n?".":"")+escapeKeyPathComponent(e);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},function(){var n=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n);});}),O&&O({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var C=t.length,N=function _loop2(e){if(!(e in t)){var r=n+(n?".":"")+e;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},function(){var n=_encapsulate(r,void 0,!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n);});}},B=0;B-1){var r=e[unescapeKeyPathComponent(n.substr(0,t))];return void 0===r?void 0:getByKeyPath(r,n.substr(t+1))}return e[unescapeKeyPathComponent(n)]}function Undefined(){}function TypesonPromise(e){this.p=new Promise(e);}return TypesonPromise.prototype.then=function(e,n){var t=this;return new TypesonPromise(function(r,i){t.p.then(function(n){r(e?e(n):n);},function(e){t.p.catch(function(e){return n?n(e):Promise.reject(e)}).then(r,i);});})},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise(function(n){n(e);})},TypesonPromise.reject=function(e){return new TypesonPromise(function(n,t){t(e);})},["all","race"].map(function(e){TypesonPromise[e]=function(n){return new TypesonPromise(function(t,r){Promise[e](n.map(function(e){return e.p})).then(t,r);})};}),Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return !1;var n=s(e);return !n||hasConstructorOf(e,Object)||isUserObject(n)},Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=function(n){return null===n?"null":i(n)?"array":void 0===n?"undefined":e(n)},Typeson.JSON_TYPES=["null","boolean","number","string","array","object"],Typeson}); + }); + + var structuredCloning = createCommonjsModule(function (module, exports) { + !function(e,t){module.exports=t();}(commonjsGlobal,function(){var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function sliceIterator(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(r=(s=a.next()).done)&&(n.push(s.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e;}finally{try{!r&&a.return&&a.return();}finally{if(i)throw o}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),n=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)},this.rootTypeName=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)};var y=this.encapsulate=function(f,p,l){var y=(l=Object.assign({sync:!0},o,l)).sync,v={},d=[],h=[],g=[],b=!(l&&"cyclic"in l)||l.cyclic,m=l.encapsulateObserver,T=_encapsulate("",f,b,p||{},g);function finish(e){var t=Object.values(v);if(l.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(l.returnTypeNames)return [].concat(n(new Set(t)));e&&isPlainObject(e)&&!e.hasOwnProperty("$types")?e.$types=v:e={$:e,$types:{$:v}};}else isObject(e)&&e.hasOwnProperty("$types")&&(e={$:e,$types:!0});return !l.returnTypeNames&&e}return g.length?y&&l.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(e,n){return Promise.all(n.map(function(e){return e[1].p})).then(function(r){return Promise.all(r.map(function(r){var i=[],o=n.splice(0,1)[0],s=t(o,7),a=s[0],c=s[2],u=s[3],f=s[4],p=s[5],l=s[6],y=_encapsulate(a,r,c,u,i,!0,l),v=hasConstructorOf(y,TypesonPromise);return a&&v?y.p.then(function(t){return f[p]=t,checkPromises(e,i)}):(a?f[p]=y:e=v?y.p:y,checkPromises(e,i))}))}).then(function(){return e})}(T,g)).then(finish):!y&&l.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():l.stringification&&y?[finish(T)]:y?finish(T):Promise.resolve(finish(T));function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=u.map(function(t){var n=e[t];return delete e[t],n});n(),u.forEach(function(t,n){e[t]=r[n];});}function _encapsulate(t,n,o,a,c,u,f){var p=void 0,y={},g=void 0===n?"undefined":e(n),b=m?function(e){var r=f||a.type||Typeson.getJSONType(n);m(Object.assign(e||y,{keypath:t,value:n,cyclic:o,stateObj:a,promisesData:c,resolvingTypesonPromise:u,awaitingTypesonPromise:hasConstructorOf(n,TypesonPromise)},void 0!==r?{type:r}:{}));}:null;if(g in{string:1,boolean:1,number:1,undefined:1})return void 0===n||"number"===g&&(isNaN(n)||n===-1/0||n===1/0)?(p=replace(t,n,a,c,!1,u,b))!==n&&(y={replaced:p}):p=n,b&&b(),p;if(null===n)return b&&b(),n;if(o&&!a.iterateIn&&!a.iterateUnsetNumeric){var T=d.indexOf(n);if(!(T<0))return v[t]="#",b&&b({cyclicKeypath:h[T]}),"#"+h[T];!0===o&&(d.push(n),h.push(t));}var O=isPlainObject(n),w=i(n),S=(O||w)&&(!s.length||a.replaced)||a.iterateIn?n:replace(t,n,a,c,O||w,null,b),P=void 0;if(S!==n?(p=S,y={replaced:S}):w||"array"===a.iterateIn?(P=new Array(n.length),y={clone:P}):O||"object"===a.iterateIn?y={clone:P={}}:""===t&&hasConstructorOf(n,TypesonPromise)?(c.push([t,n,o,a,void 0,void 0,a.type]),p=n):p=n,b&&b(),l.iterateNone)return P||p;if(!P)return p;if(a.iterateIn){var j=function _loop(e){var r={ownKeys:n.hasOwnProperty(e)};_adaptBuiltinStateObjectProperties(a,r,function(){var r=t+(t?".":"")+escapeKeyPathComponent(e),i=_encapsulate(r,n[e],!!o,a,c,u);hasConstructorOf(i,TypesonPromise)?c.push([r,i,!!o,a,P,e,a.type]):void 0!==i&&(P[e]=i);});};for(var A in n)j(A);b&&b({endIterateIn:!0,end:!0});}else r(n).forEach(function(e){var r=t+(t?".":"")+escapeKeyPathComponent(e);_adaptBuiltinStateObjectProperties(a,{ownKeys:!0},function(){var t=_encapsulate(r,n[e],!!o,a,c,u);hasConstructorOf(t,TypesonPromise)?c.push([r,t,!!o,a,P,e,a.type]):void 0!==t&&(P[e]=t);});}),b&&b({endIterateOwn:!0,end:!0});if(a.iterateUnsetNumeric){for(var C=n.length,N=function _loop2(e){if(!(e in n)){var r=t+(t?".":"")+e;_adaptBuiltinStateObjectProperties(a,{ownKeys:!1},function(){var t=_encapsulate(r,void 0,!!o,a,c,u);hasConstructorOf(t,TypesonPromise)?c.push([r,t,!!o,a,P,e,a.type]):void 0!==t&&(P[e]=t);});}},B=0;B-1){var r=e[unescapeKeyPathComponent(t.substr(0,n))];return void 0===r?void 0:getByKeyPath(r,t.substr(n+1))}return e[unescapeKeyPathComponent(t)]}function Undefined(){}function TypesonPromise(e){this.p=new Promise(e);}TypesonPromise.prototype.then=function(e,t){var n=this;return new TypesonPromise(function(r,i){n.p.then(function(t){r(e?e(t):t);},function(e){n.p.catch(function(e){return t?t(e):Promise.reject(e)}).then(r,i);});})},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise(function(t){t(e);})},TypesonPromise.reject=function(e){return new TypesonPromise(function(t,n){n(e);})},["all","race"].map(function(e){TypesonPromise[e]=function(t){return new TypesonPromise(function(n,r){Promise[e](t.map(function(e){return e.p})).then(n,r);})};}),Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return !1;var t=s(e);return !t||hasConstructorOf(e,Object)||isUserObject(t)},Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=function(t){return null===t?"null":i(t)?"array":void 0===t?"undefined":e(t)},Typeson.JSON_TYPES=["null","boolean","number","string","array","object"];for(var f={userObject:{test:function test(e,t){return Typeson.isUserObject(e)},replace:function replace(e){return Object.assign({},e)},revive:function revive(e){return e}}},p=[[{sparseArrays:{testPlainObjects:!0,test:function test(e){return Array.isArray(e)},replace:function replace(e,t){return t.iterateUnsetNumeric=!0,e}}},{sparseUndefined:{test:function test(e,t){return void 0===e&&!1===t.ownKeys},replace:function replace(e){return null},revive:function revive(e){}}}],{undef:{test:function test(e,t){return void 0===e&&(t.ownKeys||!("ownKeys"in t))},replace:function replace(e){return null},revive:function revive(e){return new Typeson.Undefined}}}],l={StringObject:{test:function test(t){return "String"===Typeson.toStringTag(t)&&"object"===(void 0===t?"undefined":e(t))},replace:function replace(e){return String(e)},revive:function revive(e){return new String(e)}},BooleanObject:{test:function test(t){return "Boolean"===Typeson.toStringTag(t)&&"object"===(void 0===t?"undefined":e(t))},replace:function replace(e){return Boolean(e)},revive:function revive(e){return new Boolean(e)}},NumberObject:{test:function test(t){return "Number"===Typeson.toStringTag(t)&&"object"===(void 0===t?"undefined":e(t))},replace:function replace(e){return Number(e)},revive:function revive(e){return new Number(e)}}},y=[{nan:{test:function test(e){return "number"==typeof e&&isNaN(e)},replace:function replace(e){return "NaN"},revive:function revive(e){return NaN}}},{infinity:{test:function test(e){return e===1/0},replace:function replace(e){return "Infinity"},revive:function revive(e){return 1/0}}},{negativeInfinity:{test:function test(e){return e===-1/0},replace:function replace(e){return "-Infinity"},revive:function revive(e){return -1/0}}}],v={date:{test:function test(e){return "Date"===Typeson.toStringTag(e)},replace:function replace(e){var t=e.getTime();return isNaN(t)?"NaN":t},revive:function revive(e){return "NaN"===e?new Date(NaN):new Date(e)}}},d={regexp:{test:function test(e){return "RegExp"===Typeson.toStringTag(e)},replace:function replace(e){return {source:e.source,flags:(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.sticky?"y":"")+(e.unicode?"u":"")}},revive:function revive(e){var t=e.source,n=e.flags;return new RegExp(t,n)}}},h={map:{test:function test(e){return "Map"===Typeson.toStringTag(e)},replace:function replace(e){return Array.from(e.entries())},revive:function revive(e){return new Map(e)}}},g={set:{test:function test(e){return "Set"===Typeson.toStringTag(e)},replace:function replace(e){return Array.from(e.values())},revive:function revive(e){return new Set(e)}}},b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",m=new Uint8Array(256),T=0;T>2],o+=b[(3&r[s])<<4|r[s+1]>>4],o+=b[(15&r[s+1])<<2|r[s+2]>>6],o+=b[63&r[s+2]];return i%3==2?o=o.substring(0,o.length-1)+"=":i%3==1&&(o=o.substring(0,o.length-2)+"=="),o},w=function decode(e){var t=e.length,n=.75*e.length,r=0,i=void 0,o=void 0,s=void 0,a=void 0;"="===e[e.length-1]&&(n--,"="===e[e.length-2]&&n--);for(var c=new ArrayBuffer(n),u=new Uint8Array(c),f=0;f>4,u[r++]=(15&o)<<4|s>>2,u[r++]=(3&s)<<6|63&a;return c},S={arraybuffer:{test:function test(e){return "ArrayBuffer"===Typeson.toStringTag(e)},replace:function replace(e,t){t.buffers||(t.buffers=[]);var n=t.buffers.indexOf(e);return n>-1?{index:n}:(t.buffers.push(e),O(e))},revive:function revive(t,n){if(n.buffers||(n.buffers=[]),"object"===(void 0===t?"undefined":e(t)))return n.buffers[t.index];var r=w(t);return n.buffers.push(r),r}}},P="undefined"==typeof self?commonjsGlobal:self,j={};["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"].forEach(function(e){var t=e,n=P[t];n&&(j[e.toLowerCase()]={test:function test(e){return Typeson.toStringTag(e)===t},replace:function replace(e,t){var n=e.buffer,r=e.byteOffset,i=e.length;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(n);return o>-1?{index:o,byteOffset:r,length:i}:(t.buffers.push(n),{encoded:O(n),byteOffset:r,length:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var r=e.byteOffset,i=e.length,o=e.encoded,s=e.index,a=void 0;return "index"in e?a=t.buffers[s]:(a=w(o),t.buffers.push(a)),new n(a,r,i)}});});var A={dataview:{test:function test(e){return "DataView"===Typeson.toStringTag(e)},replace:function replace(e,t){var n=e.buffer,r=e.byteOffset,i=e.byteLength;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(n);return o>-1?{index:o,byteOffset:r,byteLength:i}:(t.buffers.push(n),{encoded:O(n),byteOffset:r,byteLength:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var n=e.byteOffset,r=e.byteLength,i=e.encoded,o=e.index,s=void 0;return "index"in e?s=t.buffers[o]:(s=w(i),t.buffers.push(s)),new DataView(s,n,r)}}},C={IntlCollator:{test:function test(e){return Typeson.hasConstructorOf(e,Intl.Collator)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.Collator(e.locale,e)}},IntlDateTimeFormat:{test:function test(e){return Typeson.hasConstructorOf(e,Intl.DateTimeFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.DateTimeFormat(e.locale,e)}},IntlNumberFormat:{test:function test(e){return Typeson.hasConstructorOf(e,Intl.NumberFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.NumberFormat(e.locale,e)}}};function string2arraybuffer(e){for(var t=new Uint16Array(e.length),n=0;n> 2]; + base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4]; + base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6]; + base64 += chars[bytes[_i + 2] & 63]; + } + + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; + } else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + + return base64; + }; + var decode = function decode(base64) { + var len = base64.length; + var bufferLength = base64.length * 0.75; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (var _i2 = 0; _i2 < len; _i2 += 4) { + encoded1 = lookup[base64.charCodeAt(_i2)]; + encoded2 = lookup[base64.charCodeAt(_i2 + 1)]; + encoded3 = lookup[base64.charCodeAt(_i2 + 2)]; + encoded4 = lookup[base64.charCodeAt(_i2 + 3)]; + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + + return arraybuffer; + }; + + /* eslint-env browser, node */ + var _global = typeof self === 'undefined' ? global : self; + var exportObj = {}; + [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array' + ].forEach(function (typeName) { + var arrType = typeName; + var TypedArray = _global[arrType]; + if (TypedArray) { + exportObj[typeName.toLowerCase() + "2"] = { + test: function (x) { return typeson.toStringTag(x) === arrType; }, + replace: function (_a) { + var buffer = _a.buffer, byteOffset = _a.byteOffset, length = _a.length; + return { + buffer: buffer, + byteOffset: byteOffset, + length: length + }; + }, + revive: function (b64Obj) { + var buffer = b64Obj.buffer, byteOffset = b64Obj.byteOffset, length = b64Obj.length; + return new TypedArray(buffer, byteOffset, length); + } + }; + } + }); + + var arrayBuffer = { + arraybuffer: { + test: function (x) { return typeson.toStringTag(x) === 'ArrayBuffer'; }, + replace: function (b) { + return encode(b, 0, b.byteLength); + }, + revive: function (b64) { + var buffer = decode(b64); + return buffer; + } + } + }; + // See also typed-arrays! + + var TSON = new typeson().register(structuredCloning); + var readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only. + var blobsToAwait = []; + var blobsToAwaitPos = 0; + // Need to patch encapsulateAsync as it does not work as of typeson 5.8.2 + // Also, current version of typespn-registry-1.0.0-alpha.21 does not + // encapsulate/revive Blobs correctly (fails one of the unit tests in + // this library (test 'export-format')) + TSON.register([ + arrayBuffer, + exportObj, { + blob2: { + test: function (x) { return typeson.toStringTag(x) === 'Blob'; }, + replace: function (b) { + if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob + throw new Error('The Blob is closed'); + } + if (readBlobsSynchronously) { + var data = readBlobSync(b, 'binary'); + var base64 = encode(data, 0, data.byteLength); + return { + type: b.type, + data: base64 + }; + } + else { + blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true. + var result = { + type: b.type, + data: { start: blobsToAwaitPos, end: blobsToAwaitPos + b.size } + }; + console.log("b.size: " + b.size); + blobsToAwaitPos += b.size; + return result; + } + }, + finalize: function (b, ba) { + b.data = encode(ba, 0, ba.byteLength); + }, + revive: function (_a) { + var type = _a.type, data = _a.data; + return new Blob([decode(data)], { type: type }); + } + } + } + ]); + TSON.mustFinalize = function () { return blobsToAwait.length > 0; }; + TSON.finalize = function (items) { return __awaiter(void 0, void 0, void 0, function () { + var allChunks, _i, items_1, item, types, arrayType, keyPath, typeName, typeSpec, b; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, readBlobAsync(new Blob(blobsToAwait), 'binary')]; + case 1: + allChunks = _a.sent(); + if (items) { + for (_i = 0, items_1 = items; _i < items_1.length; _i++) { + item = items_1[_i]; + // Manually go through all "blob" types in the result + // and lookup the data slice they point at. + if (item.$types) { + types = item.$types; + arrayType = types.$; + if (arrayType) + types = types.$; + for (keyPath in types) { + typeName = types[keyPath]; + typeSpec = TSON.types[typeName]; + if (typeSpec && typeSpec.finalize) { + b = Dexie.getByKeyPath(item, arrayType ? "$." + keyPath : keyPath); + typeSpec.finalize(b, allChunks.slice(b.start, b.end)); + } + } + } + } + } + // Free up memory + blobsToAwait = []; + return [2 /*return*/]; + } + }); + }); }; + + var DEFAULT_ROWS_PER_CHUNK = 2000; + function exportDB(db, options) { + return __awaiter(this, void 0, void 0, function () { + function exportAll() { + return __awaiter(this, void 0, void 0, function () { + var tablesRowCounts, emptyExportJson, posEndDataArray, firstJsonSlice, filter, _loop_1, _i, tables_1, tableName; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all(db.tables.map(function (table) { return table.count(); }))]; + case 1: + tablesRowCounts = _a.sent(); + tablesRowCounts.forEach(function (rowCount, i) { return tables[i].rowCount = rowCount; }); + progress.totalRows = tablesRowCounts.reduce(function (p, c) { return p + c; }); + emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined); + posEndDataArray = emptyExportJson.lastIndexOf(']'); + firstJsonSlice = emptyExportJson.substring(0, posEndDataArray); + slices.push(firstJsonSlice); + filter = options.filter; + _loop_1 = function (tableName) { + var table, primKey, inbound, LIMIT, emptyTableExport, emptyTableExportJson, posEndRowsArray, lastKey, lastNumRows, mayHaveMoreRows, _loop_2, state_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + table = db.table(tableName); + primKey = table.schema.primKey; + inbound = !!primKey.keyPath; + LIMIT = options.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK; + emptyTableExport = inbound ? { + tableName: table.name, + inbound: true, + rows: [] + } : { + tableName: table.name, + inbound: false, + rows: [] + }; + emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined); + if (prettyJson) { + // Increase indentation according to this: + // { + // ... + // data: [ + // ... + // data: [ + // 123456<---- here + // ] + // ] + // } + emptyTableExportJson = emptyTableExportJson.split('\n').join('\n '); + } + posEndRowsArray = emptyTableExportJson.lastIndexOf(']'); + slices.push(emptyTableExportJson.substring(0, posEndRowsArray)); + lastKey = null; + lastNumRows = 0; + mayHaveMoreRows = true; + _loop_2 = function () { + var chunkedCollection, values, filteredValues, tsonValues, json, keys, keyvals, tsonTuples, json; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + chunkedCollection = lastKey == null ? + table.limit(LIMIT) : + table.where(':id').above(lastKey).limit(LIMIT); + return [4 /*yield*/, chunkedCollection.toArray()]; + case 1: + values = _a.sent(); + if (values.length === 0) + return [2 /*return*/, "break"]; + if (lastKey != null && lastNumRows > 0) { + // Not initial chunk. Must add a comma: + slices.push(","); + if (prettyJson) { + slices.push("\n "); + } + } + mayHaveMoreRows = values.length === LIMIT; + if (!inbound) return [3 /*break*/, 4]; + filteredValues = filter ? + values.filter(function (value) { return filter(tableName, value); }) : + values; + tsonValues = filteredValues.map(function (value) { return TSON.encapsulate(value); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 3]; + return [4 /*yield*/, Dexie.waitFor(TSON.finalize(tsonValues))]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = filteredValues.length; + lastKey = values.length > 0 ? + Dexie.getByKeyPath(values[values.length - 1], primKey.keyPath) : + null; + return [3 /*break*/, 8]; + case 4: return [4 /*yield*/, chunkedCollection.primaryKeys()]; + case 5: + keys = _a.sent(); + keyvals = keys.map(function (key, i) { return [key, values[i]]; }); + if (filter) + keyvals = keyvals.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }); + tsonTuples = keyvals.map(function (tuple) { return TSON.encapsulate(tuple); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 7]; + return [4 /*yield*/, Dexie.waitFor(TSON.finalize(tsonTuples))]; + case 6: + _a.sent(); + _a.label = 7; + case 7: + json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = keyvals.length; + lastKey = keys.length > 0 ? + keys[keys.length - 1] : + null; + _a.label = 8; + case 8: + progress.completedRows += values.length; + return [2 /*return*/]; + } + }); + }; + _a.label = 1; + case 1: + if (!mayHaveMoreRows) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_2()]; + case 2: + state_1 = _a.sent(); + if (state_1 === "break") + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + slices.push(emptyTableExportJson.substr(posEndRowsArray)); // "]}" + progress.completedTables += 1; + if (progress.completedTables < progress.totalTables) { + slices.push(","); + } + return [2 /*return*/]; + } + }); + }; + _i = 0, tables_1 = tables; + _a.label = 2; + case 2: + if (!(_i < tables_1.length)) return [3 /*break*/, 5]; + tableName = tables_1[_i].name; + return [5 /*yield**/, _loop_1(tableName)]; + case 3: + _a.sent(); + _a.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + slices.push(emptyExportJson.substr(posEndDataArray)); + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); + } + var slices, tables, prettyJson, emptyExport, progressCallback, progress; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; + slices = []; + tables = db.tables.map(function (table) { return ({ + name: table.name, + schema: getSchemaString(table), + rowCount: 0 + }); }); + prettyJson = options.prettyJson; + emptyExport = { + formatName: "dexie", + formatVersion: 1, + data: { + databaseName: db.name, + databaseVersion: db.verno, + tables: tables, + data: [] + } + }; + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: NaN, + totalTables: db.tables.length + }; + _a.label = 1; + case 1: + _a.trys.push([1, , 6, 7]); + if (!options.noTransaction) return [3 /*break*/, 3]; + return [4 /*yield*/, exportAll()]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, db.transaction('r', db.tables, exportAll)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: return [3 /*break*/, 7]; + case 6: + TSON.finalize(); // Free up mem if error has occurred + return [7 /*endfinally*/]; + case 7: + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/, new Blob(slices, { type: "text/json" })]; + } + }); + }); + } + + var VERSION = 1; + + var fakeStream = {Stream: function(){}}; + + var clarinet_1 = createCommonjsModule(function (module, exports) { + (function (clarinet) { + + // non node-js needs to set clarinet debug on root + var env =(typeof process === 'object' && process.env) + ? process.env + : self; + + clarinet.parser = function (opt) { return new CParser(opt);}; + clarinet.CParser = CParser; + clarinet.CStream = CStream; + clarinet.createStream = createStream; + clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024; + clarinet.DEBUG = (env.CDEBUG==='debug'); + clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info'); + clarinet.EVENTS = + [ "value" + , "string" + , "key" + , "openobject" + , "closeobject" + , "openarray" + , "closearray" + , "error" + , "end" + , "ready" + ]; + + var buffers = { + textNode: undefined, + numberNode: "" + } + , streamWraps = clarinet.EVENTS.filter(function (ev) { + return ev !== "error" && ev !== "end"; + }) + , S = 0 + , Stream + ; + + clarinet.STATE = + { BEGIN : S++ + , VALUE : S++ // general stuff + , OPEN_OBJECT : S++ // { + , CLOSE_OBJECT : S++ // } + , OPEN_ARRAY : S++ // [ + , CLOSE_ARRAY : S++ // ] + , TEXT_ESCAPE : S++ // \ stuff + , STRING : S++ // "" + , BACKSLASH : S++ + , END : S++ // No more stack + , OPEN_KEY : S++ // , "a" + , CLOSE_KEY : S++ // : + , TRUE : S++ // r + , TRUE2 : S++ // u + , TRUE3 : S++ // e + , FALSE : S++ // a + , FALSE2 : S++ // l + , FALSE3 : S++ // s + , FALSE4 : S++ // e + , NULL : S++ // u + , NULL2 : S++ // l + , NULL3 : S++ // l + , NUMBER_DECIMAL_POINT : S++ // . + , NUMBER_DIGIT : S++ // [0-9] + }; + + for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_; + + // switcharoo + S = clarinet.STATE; + + const Char = { + tab : 0x09, // \t + lineFeed : 0x0A, // \n + carriageReturn : 0x0D, // \r + space : 0x20, // " " + + doubleQuote : 0x22, // " + plus : 0x2B, // + + comma : 0x2C, // , + minus : 0x2D, // - + period : 0x2E, // . + + _0 : 0x30, // 0 + _9 : 0x39, // 9 + + colon : 0x3A, // : + + E : 0x45, // E + + openBracket : 0x5B, // [ + backslash : 0x5C, // \ + closeBracket : 0x5D, // ] + + a : 0x61, // a + b : 0x62, // b + e : 0x65, // e + f : 0x66, // f + l : 0x6C, // l + n : 0x6E, // n + r : 0x72, // r + s : 0x73, // s + t : 0x74, // t + u : 0x75, // u + + openBrace : 0x7B, // { + closeBrace : 0x7D, // } + }; + + if (!Object.create) { + Object.create = function (o) { + function f () { this["__proto__"] = o; } + f.prototype = o; + return new f; + }; + } + + if (!Object.getPrototypeOf) { + Object.getPrototypeOf = function (o) { + return o["__proto__"]; + }; + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = []; + for (var i in o) if (o.hasOwnProperty(i)) a.push(i); + return a; + }; + } + + function checkBufferLength (parser) { + var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10) + , maxActual = 0 + ; + for (var buffer in buffers) { + var len = parser[buffer] === undefined ? 0 : parser[buffer].length; + if (len > maxAllowed) { + switch (buffer) { + case "text": + closeText(parser); + break; + + default: + error(parser, "Max buffer length exceeded: "+ buffer); + } + } + maxActual = Math.max(maxActual, len); + } + parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual) + + parser.position; + } + + function clearBuffers (parser) { + for (var buffer in buffers) { + parser[buffer] = buffers[buffer]; + } + } + + var stringTokenPattern = /[\\"\n]/g; + + function CParser (opt) { + if (!(this instanceof CParser)) return new CParser (opt); + + var parser = this; + clearBuffers(parser); + parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH; + parser.q = parser.c = parser.p = ""; + parser.opt = opt || {}; + parser.closed = parser.closedRoot = parser.sawRoot = false; + parser.tag = parser.error = null; + parser.state = S.BEGIN; + parser.stack = new Array(); + // mostly just for error reporting + parser.position = parser.column = 0; + parser.line = 1; + parser.slashed = false; + parser.unicodeI = 0; + parser.unicodeS = null; + parser.depth = 0; + emit(parser, "onready"); + } + + CParser.prototype = + { end : function () { end(this); } + , write : write + , resume : function () { this.error = null; return this; } + , close : function () { return this.write(null); } + }; + + try { Stream = fakeStream.Stream; } + catch (ex) { Stream = function () {}; } + + function createStream (opt) { return new CStream(opt); } + + function CStream (opt) { + if (!(this instanceof CStream)) return new CStream(opt); + + this._parser = new CParser(opt); + this.writable = true; + this.readable = true; + + //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error + this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary + this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read + this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached + this.string = ''; + + var me = this; + Stream.apply(me); + + this._parser.onend = function () { me.emit("end"); }; + this._parser.onerror = function (er) { + me.emit("error", er); + me._parser.error = null; + }; + + streamWraps.forEach(function (ev) { + Object.defineProperty(me, "on" + ev, + { get : function () { return me._parser["on" + ev]; } + , set : function (h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on"+ev] = h; + return h; + } + me.on(ev, h); + } + , enumerable : true + , configurable : false + }); + }); + } + + CStream.prototype = Object.create(Stream.prototype, + { constructor: { value: CStream } }); + + CStream.prototype.write = function (data) { + data = new Buffer(data); + for (var i = 0; i < data.length; i++) { + var n = data[i]; + + // check for carry over of a multi byte char split between data chunks + // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration + if (this.bytes_remaining > 0) { + for (var j = 0; j < this.bytes_remaining; j++) { + this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j]; + } + this.string = this.temp_buffs[this.bytes_in_sequence].toString(); + this.bytes_in_sequence = this.bytes_remaining = 0; + + // move iterator forward by number of byte read during sequencing + i = i + j - 1; + + // pass data to parser and move forward to parse rest of data + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + + // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time + if (this.bytes_remaining === 0 && n >= 128) { + if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; + if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; + if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; + if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split + + for (var k = 0; k <= (data.length - 1 - i); k++) { + this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk + } + this.bytes_remaining = (i + this.bytes_in_sequence) - data.length; + + // immediately return as we need another chunk to sequence the character + return true; + } else { + this.string = data.slice(i, (i + this.bytes_in_sequence)).toString(); + i = i + this.bytes_in_sequence - 1; + + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + } + + // is there a range of characters that are immediately parsable? + for (var p = i; p < data.length; p++) { + if (data[p] >= 128) break; + } + this.string = data.slice(i, p).toString(); + this._parser.write(this.string); + this.emit("data", this.string); + i = p - 1; + + // handle any remaining characters using multibyte logic + continue; + } + }; + + CStream.prototype.end = function (chunk) { + if (chunk && chunk.length) this._parser.write(chunk.toString()); + this._parser.end(); + return true; + }; + + CStream.prototype.on = function (ev, handler) { + var me = this; + if (!me._parser["on"+ev] && streamWraps.indexOf(ev) !== -1) { + me._parser["on"+ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] + : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + } + return Stream.prototype.on.call(me, ev, handler); + }; + + CStream.prototype.destroy = function () { + clearBuffers(this._parser); + this.emit("close"); + }; + + function emit(parser, event, data) { + if(clarinet.INFO) console.log('-- emit', event, data); + if (parser[event]) parser[event](data); + } + + function emitNode(parser, event, data) { + closeValue(parser); + emit(parser, event, data); + } + + function closeValue(parser, event) { + parser.textNode = textopts(parser.opt, parser.textNode); + if (parser.textNode !== undefined) { + emit(parser, (event ? event : "onvalue"), parser.textNode); + } + parser.textNode = undefined; + } + + function closeNumber(parser) { + if (parser.numberNode) + emit(parser, "onvalue", parseFloat(parser.numberNode)); + parser.numberNode = ""; + } + + function textopts (opt, text) { + if (text === undefined) { + return text; + } + if (opt.trim) text = text.trim(); + if (opt.normalize) text = text.replace(/\s+/g, " "); + return text; + } + + function error (parser, er) { + closeValue(parser); + er += "\nLine: "+parser.line+ + "\nColumn: "+parser.column+ + "\nChar: "+parser.c; + er = new Error(er); + parser.error = er; + emit(parser, "onerror", er); + return parser; + } + + function end(parser) { + if (parser.state !== S.VALUE || parser.depth !== 0) + error(parser, "Unexpected end"); + + closeValue(parser); + parser.c = ""; + parser.closed = true; + emit(parser, "onend"); + CParser.call(parser, parser.opt); + return parser; + } + + function isWhitespace(c) { + return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab; + } + + function write (chunk) { + var parser = this; + if (this.error) throw this.error; + if (parser.closed) return error(parser, + "Cannot write after close. Assign an onready handler."); + if (chunk === null) return end(parser); + var i = 0, c = chunk.charCodeAt(0), p = parser.p; + if (clarinet.DEBUG) console.log('write -> [' + chunk + ']'); + while (c) { + p = c; + parser.c = c = chunk.charCodeAt(i++); + // if chunk doesnt have next, like streaming char by char + // this way we need to check if previous is really previous + // if not we need to reset to what the parser says is the previous + // from buffer + if(p !== c ) parser.p = p; + else p = parser.p; + + if(!c) break; + + if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]); + parser.position ++; + if (c === Char.lineFeed) { + parser.line ++; + parser.column = 0; + } else parser.column ++; + switch (parser.state) { + + case S.BEGIN: + if (c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if (!isWhitespace(c)) + error(parser, "Non-whitespace before {[."); + continue; + + case S.OPEN_KEY: + case S.OPEN_OBJECT: + if (isWhitespace(c)) continue; + if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY); + else { + if(c === Char.closeBrace) { + emit(parser, 'onopenobject'); + this.depth++; + emit(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else parser.stack.push(S.CLOSE_OBJECT); + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else error(parser, "Malformed object key should start with \""); + continue; + + case S.CLOSE_KEY: + case S.CLOSE_OBJECT: + if (isWhitespace(c)) continue; + var event = (parser.state === S.CLOSE_KEY) ? 'key' : 'object'; + if(c === Char.colon) { + if(parser.state === S.CLOSE_OBJECT) { + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser, 'onopenobject'); + this.depth++; + } else closeValue(parser, 'onkey'); + parser.state = S.VALUE; + } else if (c === Char.closeBrace) { + emitNode(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if(c === Char.comma) { + if(parser.state === S.CLOSE_OBJECT) + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser); + parser.state = S.OPEN_KEY; + } else error(parser, 'Bad object'); + continue; + + case S.OPEN_ARRAY: // after an array there always a value + case S.VALUE: + if (isWhitespace(c)) continue; + if(parser.state===S.OPEN_ARRAY) { + emit(parser, 'onopenarray'); + this.depth++; + parser.state = S.VALUE; + if(c === Char.closeBracket) { + emit(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else { + parser.stack.push(S.CLOSE_ARRAY); + } + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if(c === Char.t) parser.state = S.TRUE; + else if(c === Char.f) parser.state = S.FALSE; + else if(c === Char.n) parser.state = S.NULL; + else if(c === Char.minus) { // keep and continue + parser.numberNode += "-"; + } else if(Char._0 <= c && c <= Char._9) { + parser.numberNode += String.fromCharCode(c); + parser.state = S.NUMBER_DIGIT; + } else error(parser, "Bad value"); + continue; + + case S.CLOSE_ARRAY: + if(c === Char.comma) { + parser.stack.push(S.CLOSE_ARRAY); + closeValue(parser, 'onvalue'); + parser.state = S.VALUE; + } else if (c === Char.closeBracket) { + emitNode(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if (isWhitespace(c)) + continue; + else error(parser, 'Bad array'); + continue; + + case S.STRING: + if (parser.textNode === undefined) { + parser.textNode = ""; + } + + // thanks thejh, this is an about 50% performance improvement. + var starti = i-1 + , slashed = parser.slashed + , unicodeI = parser.unicodeI + ; + STRING_BIGLOOP: while (true) { + if (clarinet.DEBUG) + console.log(i,c,clarinet.STATE[parser.state] + ,slashed); + // zero means "no unicode active". 1-4 mean "parse some more". end after 4. + while (unicodeI > 0) { + parser.unicodeS += String.fromCharCode(c); + c = chunk.charCodeAt(i++); + parser.position++; + if (unicodeI === 4) { + // TODO this might be slow? well, probably not used too often anyway + parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16)); + unicodeI = 0; + starti = i-1; + } else { + unicodeI++; + } + // we can just break here: no stuff we skipped that still has to be sliced out or so + if (!c) break STRING_BIGLOOP; + } + if (c === Char.doubleQuote && !slashed) { + parser.state = parser.stack.pop() || S.VALUE; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + if (c === Char.backslash && !slashed) { + slashed = true; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + c = chunk.charCodeAt(i++); + parser.position++; + if (!c) break; + } + if (slashed) { + slashed = false; + if (c === Char.n) { parser.textNode += '\n'; } + else if (c === Char.r) { parser.textNode += '\r'; } + else if (c === Char.t) { parser.textNode += '\t'; } + else if (c === Char.f) { parser.textNode += '\f'; } + else if (c === Char.b) { parser.textNode += '\b'; } + else if (c === Char.u) { + // \uxxxx. meh! + unicodeI = 1; + parser.unicodeS = ''; + } else { + parser.textNode += String.fromCharCode(c); + } + c = chunk.charCodeAt(i++); + parser.position++; + starti = i-1; + if (!c) break; + else continue; + } + + stringTokenPattern.lastIndex = i; + var reResult = stringTokenPattern.exec(chunk); + if (reResult === null) { + i = chunk.length+1; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + i = reResult.index+1; + c = chunk.charCodeAt(reResult.index); + if (!c) { + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + } + parser.slashed = slashed; + parser.unicodeI = unicodeI; + continue; + + case S.TRUE: + if (c === Char.r) parser.state = S.TRUE2; + else error(parser, 'Invalid true started with t'+ c); + continue; + + case S.TRUE2: + if (c === Char.u) parser.state = S.TRUE3; + else error(parser, 'Invalid true started with tr'+ c); + continue; + + case S.TRUE3: + if(c === Char.e) { + emit(parser, "onvalue", true); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid true started with tru'+ c); + continue; + + case S.FALSE: + if (c === Char.a) parser.state = S.FALSE2; + else error(parser, 'Invalid false started with f'+ c); + continue; + + case S.FALSE2: + if (c === Char.l) parser.state = S.FALSE3; + else error(parser, 'Invalid false started with fa'+ c); + continue; + + case S.FALSE3: + if (c === Char.s) parser.state = S.FALSE4; + else error(parser, 'Invalid false started with fal'+ c); + continue; + + case S.FALSE4: + if (c === Char.e) { + emit(parser, "onvalue", false); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid false started with fals'+ c); + continue; + + case S.NULL: + if (c === Char.u) parser.state = S.NULL2; + else error(parser, 'Invalid null started with n'+ c); + continue; + + case S.NULL2: + if (c === Char.l) parser.state = S.NULL3; + else error(parser, 'Invalid null started with nu'+ c); + continue; + + case S.NULL3: + if(c === Char.l) { + emit(parser, "onvalue", null); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid null started with nul'+ c); + continue; + + case S.NUMBER_DECIMAL_POINT: + if(c === Char.period) { + parser.numberNode += "."; + parser.state = S.NUMBER_DIGIT; + } else error(parser, 'Leading zero not followed by .'); + continue; + + case S.NUMBER_DIGIT: + if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c); + else if (c === Char.period) { + if(parser.numberNode.indexOf('.')!==-1) + error(parser, 'Invalid number has two dots'); + parser.numberNode += "."; + } else if (c === Char.e || c === Char.E) { + if(parser.numberNode.indexOf('e')!==-1 || + parser.numberNode.indexOf('E')!==-1 ) + error(parser, 'Invalid number has two exponential'); + parser.numberNode += "e"; + } else if (c === Char.plus || c === Char.minus) { + if(!(p === Char.e || p === Char.E)) + error(parser, 'Invalid symbol in number'); + parser.numberNode += String.fromCharCode(c); + } else { + closeNumber(parser); + i--; // go back one + parser.state = parser.stack.pop() || S.VALUE; + } + continue; + + default: + error(parser, "Unknown state: " + parser.state); + } + } + if (parser.position >= parser.bufferCheckPosition) + checkBufferLength(parser); + return parser; + } + + })(exports); + }); + + function JsonStream(blob) { + var pos = 0; + var parser = JsonParser(true); + var rv = { + pullAsync: function (numBytes) { + return __awaiter(this, void 0, void 0, function () { + var slize, jsonPart, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + return [4 /*yield*/, readBlobAsync(slize, 'text')]; + case 1: + jsonPart = _a.sent(); + result = parser.write(jsonPart); + rv.result = result || {}; + return [2 /*return*/, result]; + } + }); + }); + }, + pullSync: function (numBytes) { + var slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + var jsonPart = readBlobSync(slize, 'text'); + var result = parser.write(jsonPart); + rv.result = result || {}; + return result; + }, + done: function () { + return parser.done(); + }, + eof: function () { + return pos >= blob.size; + }, + result: {} + }; + return rv; + } + function JsonParser(allowPartial) { + var parser = clarinet_1.parser(); + var level = 0; + var result; + var stack = []; + var obj; + var key; + var done = false; + var array = false; + parser.onopenobject = function (newKey) { + var newObj = {}; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + key = newKey; + array = false; + ++level; + }; + parser.onkey = function (newKey) { return key = newKey; }; + parser.onvalue = function (value) { return array ? obj.push(value) : obj[key] = value; }; + parser.oncloseobject = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + parser.onopenarray = function () { + var newObj = []; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + array = true; + key = null; + ++level; + }; + parser.onclosearray = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + return { + write: function (jsonPart) { + parser.write(jsonPart); + return result; + }, + done: function () { + return done; + } + }; + } + + var DEFAULT_KILOBYTES_PER_CHUNK = 1024; + function importDB(exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + var CHUNK_SIZE, stream, dbExport, db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + stream = _a.sent(); + dbExport = stream.result.data; + db = new Dexie(dbExport.databaseName); + db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport)); + return [4 /*yield*/, importInto(db, stream, options)]; + case 2: + _a.sent(); + return [2 /*return*/, db]; + } + }); + }); + } + function importInto(db, exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + function importAll() { + return __awaiter(this, void 0, void 0, function () { + var _loop_1, _i, _a, tableExport, state_1; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _loop_1 = function (tableExport) { + var tableName, table, tableSchemaStr, sourceRows, rows, i, obj, filter, filteredRows, _a, keys, values; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!tableExport.rows) + return [2 /*return*/, "break"]; // Need to pull more! + if (!tableExport.rows.incomplete && tableExport.rows.length === 0) + return [2 /*return*/, "continue"]; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + tableName = tableExport.tableName; + table = db.table(tableName); + tableSchemaStr = dbExport.tables.filter(function (t) { return t.name === tableName; })[0].schema; + if (!table) { + if (!options.acceptMissingTables) + throw new Error("Exported table " + tableExport.tableName + " is missing in installed database"); + else + return [2 /*return*/, "continue"]; + } + if (!options.acceptChangedPrimaryKey && + tableSchemaStr.split(',')[0] != table.schema.primKey.src) { + throw new Error("Primary key differs for table " + tableExport.tableName + ". "); + } + sourceRows = tableExport.rows; + rows = []; + for (i = 0; i < sourceRows.length; i++) { + obj = sourceRows[i]; + if (!obj.incomplete) { + rows.push(TSON.revive(obj)); + } + else { + break; + } + } + filter = options.filter; + filteredRows = filter ? + tableExport.inbound ? + rows.filter(function (value) { return filter(tableName, value); }) : + rows.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }) : + rows; + _a = tableExport.inbound ? + [undefined, filteredRows] : + [filteredRows.map(function (row) { return row[0]; }), rows.map(function (row) { return row[1]; })], keys = _a[0], values = _a[1]; + if (!options.clearTablesBeforeImport) return [3 /*break*/, 2]; + return [4 /*yield*/, table.clear()]; + case 1: + _b.sent(); + _b.label = 2; + case 2: + if (!options.overwriteValues) return [3 /*break*/, 4]; + return [4 /*yield*/, table.bulkPut(values, keys)]; + case 3: + _b.sent(); + return [3 /*break*/, 6]; + case 4: return [4 /*yield*/, table.bulkAdd(values, keys)]; + case 5: + _b.sent(); + _b.label = 6; + case 6: + progress.completedRows += rows.length; + if (!rows.incomplete) { + progress.completedTables += 1; + } + sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance. + return [2 /*return*/]; + } + }); + }; + _i = 0, _a = dbExport.data; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + tableExport = _a[_i]; + return [5 /*yield**/, _loop_1(tableExport)]; + case 2: + state_1 = _b.sent(); + if (state_1 === "break") + return [3 /*break*/, 4]; + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: + // Avoid unnescessary loops in "for (const tableExport of dbExport.data)" + while (dbExport.data.length > 0 && dbExport.data[0].rows && !dbExport.data[0].rows.incomplete) { + // We've already imported all rows from the first table. Delete its occurrence + dbExport.data.splice(0, 1); + } + if (!(!jsonStream.done() && !jsonStream.eof())) return [3 /*break*/, 8]; + if (!readBlobsSynchronously) return [3 /*break*/, 5]; + // If we can pull from blob synchronically, we don't have to + // keep transaction alive using Dexie.waitFor(). + // This will only be possible in workers. + jsonStream.pullSync(CHUNK_SIZE); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, Dexie.waitFor(jsonStream.pullAsync(CHUNK_SIZE))]; + case 6: + _b.sent(); + _b.label = 7; + case 7: return [3 /*break*/, 9]; + case 8: return [3 /*break*/, 10]; + case 9: + return [3 /*break*/, 0]; + _b.label = 10; + case 10: return [2 /*return*/]; + } + }); + }); + } + var CHUNK_SIZE, jsonStream, dbExportFile, readBlobsSynchronously, dbExport, progressCallback, progress; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + jsonStream = _a.sent(); + dbExportFile = jsonStream.result; + readBlobsSynchronously = 'FileReaderSync' in self; + dbExport = dbExportFile.data; + if (!options.acceptNameDiff && db.name !== dbExport.databaseName) + throw new Error("Name differs. Current database name is " + db.name + " but export is " + dbExport.databaseName); + if (!options.acceptVersionDiff && db.verno !== dbExport.databaseVersion) { + // Possible feature: Call upgraders in some isolated way if this happens... ? + throw new Error("Database version differs. Current database is in version " + db.verno + " but export is " + dbExport.databaseVersion); + } + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: dbExport.tables.reduce(function (p, c) { return p + c.rowCount; }, 0), + totalTables: dbExport.tables.length + }; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + if (!options.noTransaction) return [3 /*break*/, 3]; + return [4 /*yield*/, importAll()]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, db.transaction('rw', db.tables, importAll)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); + } + function loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE) { + return __awaiter(this, void 0, void 0, function () { + var stream, dbExportFile; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = ('slice' in exportedData ? + JsonStream(exportedData) : + exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(CHUNK_SIZE)]; + case 2: + _a.sent(); + if (stream.result.data && stream.result.data.data) + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + dbExportFile = stream.result; + if (!dbExportFile || dbExportFile.formatName != "dexie") + throw new Error("Given file is not a dexie export"); + if (dbExportFile.formatVersion > VERSION) { + throw new Error("Format version " + dbExportFile.formatVersion + " not supported"); + } + if (!dbExportFile.data) { + throw new Error("No data in export file"); + } + if (!dbExportFile.data.databaseName) { + throw new Error("Missing databaseName in export file"); + } + if (!dbExportFile.data.databaseVersion) { + throw new Error("Missing databaseVersion in export file"); + } + if (!dbExportFile.data.tables) { + throw new Error("Missing tables in export file"); + } + return [2 /*return*/, stream]; + } + }); + }); + } + + // + // Extend Dexie interface (runtime wise) + // + Dexie.prototype.export = function (options) { + return exportDB(this, options); + }; + Dexie.prototype.import = function (blob, options) { + return importInto(this, blob, options); + }; + Dexie.import = function (blob, options) { return importDB(blob, options); }; + var dexieExportImport = (function () { + throw new Error("This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options."); + }); + + exports.exportDB = exportDB; + exports.importDB = importDB; + exports.importInto = importInto; + exports.default = dexieExportImport; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=dexie-export-import.js.map diff --git a/addons/dexie-export-import/dist/dexie-export-import.js.map b/addons/dexie-export-import/dist/dexie-export-import.js.map new file mode 100644 index 000000000..f6fbd2e6a --- /dev/null +++ b/addons/dexie-export-import/dist/dexie-export-import.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-export-import.js","sources":["../node_modules/tslib/tslib.es6.js","../src/helpers.ts","../node_modules/typeson/dist/typeson.js","../node_modules/typeson-registry/node_modules/typeson/typeson.js","../node_modules/typeson-registry/node_modules/base64-arraybuffer-es6/src/base64-arraybuffer.js","../node_modules/typeson-registry/types/user-object.js","../node_modules/typeson-registry/presets/sparse-undefined.js","../node_modules/typeson-registry/types/undef.js","../node_modules/typeson-registry/types/primitive-objects.js","../node_modules/typeson-registry/types/nan.js","../node_modules/typeson-registry/types/infinity.js","../node_modules/typeson-registry/types/negative-infinity.js","../node_modules/typeson-registry/types/date.js","../node_modules/typeson-registry/types/regexp.js","../node_modules/typeson-registry/types/map.js","../node_modules/typeson-registry/types/set.js","../node_modules/typeson-registry/types/arraybuffer.js","../node_modules/typeson-registry/types/typed-arrays.js","../node_modules/typeson-registry/types/dataview.js","../node_modules/typeson-registry/types/intl-types.js","../node_modules/typeson-registry/utils/stringArrayBuffer.js","../node_modules/typeson-registry/types/file.js","../node_modules/typeson-registry/presets/structured-cloning.js","../node_modules/typeson-registry/types/imagedata.js","../node_modules/typeson-registry/types/imagebitmap.js","../node_modules/typeson-registry/types/filelist.js","../node_modules/typeson-registry/types/blob.js","../node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js","../src/tson-typed-array.ts","../src/tson-arraybuffer.ts","../src/tson.ts","../src/export.ts","../src/json-structure.ts","../tools/build-configs/fake-stream.js","../node_modules/clarinet/clarinet.js","../src/json-stream.ts","../src/import.ts","../src/dexie-export-import.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","import Dexie from 'dexie';\nimport { DexieExportedDatabase } from './json-structure';\n\nexport function getSchemaString(table: Dexie.Table) {\n const primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes);\n return primKeyAndIndexes.map(index => index.src).join(',');\n}\n\nexport function extractDbSchema(exportedDb: DexieExportedDatabase) {\n const schema: {\n [tableName: string]: string;\n } = {};\n for (const table of exportedDb.tables) {\n schema[table.name] = table.schema;\n }\n return schema;\n}\n\n\n// Missing FileReaderSync type in standard typescript libs:\ninterface FileReaderSync {\n readAsArrayBuffer(blob: Blob): ArrayBuffer;\n readAsBinaryString(blob: Blob): string;\n readAsDataURL(blob: Blob): string;\n readAsText(blob: Blob, encoding?: string): string;\n}\ndeclare var FileReaderSync: {\n prototype: FileReaderSync;\n new(): FileReaderSync;\n};\n// -----------------------------------------------\n\nexport interface TypeMapper {\n binary: ArrayBuffer;\n text: string;\n}\n\nexport function readBlobAsync(blob: Blob, type: T): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = ev => reject(new Error(\"file read aborted\"));\n reader.onerror = ev => reject((ev.target as any).error);\n reader.onload = ev => resolve((ev.target as any).result);\n if (type === 'binary')\n reader.readAsArrayBuffer(blob);\n else\n reader.readAsText(blob);\n });\n}\n\nexport function readBlobSync(blob: Blob, type: T): TypeMapper[T] {\n if (typeof FileReaderSync === 'undefined') {\n throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.');\n }\n const reader = new FileReaderSync(); // Requires worker environment\n const data = type === 'binary' ?\n reader.readAsArrayBuffer(blob) :\n reader.readAsText(blob);\n\n return data as TypeMapper[T];\n}\n","!function(e,n){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=n():\"function\"==typeof define&&define.amd?define(n):e.Typeson=n()}(this,function(){\"use strict\";var e=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&\"function\"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e},n=function(){return function(e,n){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function sliceIterator(e,n){var t=[],r=!0,i=!1,o=void 0;try{for(var s,c=e[Symbol.iterator]();!(r=(s=c.next()).done)&&(t.push(s.value),!n||t.length!==n);r=!0);}catch(e){i=!0,o=e}finally{try{!r&&c.return&&c.return()}finally{if(i)throw o}}return t}(e,n);throw new TypeError(\"Invalid attempt to destructure non-iterable instance\")}}(),t=function(e){if(Array.isArray(e)){for(var n=0,t=Array(e.length);n2&&void 0!==arguments[2]?arguments[2]:{};return t.returnTypeNames=!0,this.encapsulate(e,n,t)},this.rootTypeName=function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.iterateNone=!0,this.encapsulate(e,n,t)};var l=this.encapsulate=function(y,p,f){var l=(f=Object.assign({sync:!0},o,f)).sync,h={},v=[],d=[],b=[],O=!(f&&\"cyclic\"in f)||f.cyclic,m=f.encapsulateObserver,T=_encapsulate(\"\",y,O,p||{},b);function finish(e){var n=Object.values(h);if(f.iterateNone)return n.length?n[0]:Typeson.getJSONType(e);if(n.length){if(f.returnTypeNames)return[].concat(t(new Set(n)));e&&isPlainObject(e)&&!e.hasOwnProperty(\"$types\")?e.$types=h:e={$:e,$types:{$:h}}}else isObject(e)&&e.hasOwnProperty(\"$types\")&&(e={$:e,$types:!0});return!f.returnTypeNames&&e}return b.length?l&&f.throwOnBadSyncType?function(){throw new TypeError(\"Sync method requested but async result obtained\")}():Promise.resolve(function checkPromises(e,t){return Promise.all(t.map(function(e){return e[1].p})).then(function(r){return Promise.all(r.map(function(r){var i=[],o=t.splice(0,1)[0],s=n(o,7),c=s[0],a=s[2],u=s[3],y=s[4],p=s[5],f=s[6],l=_encapsulate(c,r,a,u,i,!0,f),h=hasConstructorOf(l,TypesonPromise);return c&&h?l.p.then(function(n){return y[p]=n,checkPromises(e,i)}):(c?y[p]=l:e=h?l.p:l,checkPromises(e,i))}))}).then(function(){return e})}(T,b)).then(finish):!l&&f.throwOnBadSyncType?function(){throw new TypeError(\"Async method requested but sync result obtained\")}():f.stringification&&l?[finish(T)]:l?finish(T):Promise.resolve(finish(T));function _adaptBuiltinStateObjectProperties(e,n,t){Object.assign(e,n);var r=u.map(function(n){var t=e[n];return delete e[n],t});t(),u.forEach(function(n,t){e[n]=r[t]})}function _encapsulate(n,t,o,c,a,u,y){var p=void 0,l={},b=void 0===t?\"undefined\":e(t),O=m?function(e){var r=y||c.type||Typeson.getJSONType(t);m(Object.assign(e||l,{keypath:n,value:t,cyclic:o,stateObj:c,promisesData:a,resolvingTypesonPromise:u,awaitingTypesonPromise:hasConstructorOf(t,TypesonPromise)},void 0!==r?{type:r}:{}))}:null;if(b in{string:1,boolean:1,number:1,undefined:1})return void 0===t||\"number\"===b&&(isNaN(t)||t===-1/0||t===1/0)?(p=replace(n,t,c,a,!1,u,O))!==t&&(l={replaced:p}):p=t,O&&O(),p;if(null===t)return O&&O(),t;if(o&&!c.iterateIn&&!c.iterateUnsetNumeric){var T=v.indexOf(t);if(!(T<0))return h[n]=\"#\",O&&O({cyclicKeypath:d[T]}),\"#\"+d[T];!0===o&&(v.push(t),d.push(n))}var g=isPlainObject(t),P=i(t),j=(g||P)&&(!s.length||c.replaced)||c.iterateIn?t:replace(n,t,c,a,g||P,null,O),S=void 0;if(j!==t?(p=j,l={replaced:j}):P||\"array\"===c.iterateIn?(S=new Array(t.length),l={clone:S}):g||\"object\"===c.iterateIn?l={clone:S={}}:\"\"===n&&hasConstructorOf(t,TypesonPromise)?(a.push([n,t,o,c,void 0,void 0,c.type]),p=t):p=t,O&&O(),f.iterateNone)return S||p;if(!S)return p;if(c.iterateIn){var w=function _loop(e){var r={ownKeys:t.hasOwnProperty(e)};_adaptBuiltinStateObjectProperties(c,r,function(){var r=n+(n?\".\":\"\")+escapeKeyPathComponent(e),i=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(i,TypesonPromise)?a.push([r,i,!!o,c,S,e,c.type]):void 0!==i&&(S[e]=i)})};for(var A in t)w(A);O&&O({endIterateIn:!0,end:!0})}else r(t).forEach(function(e){var r=n+(n?\".\":\"\")+escapeKeyPathComponent(e);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},function(){var n=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n)})}),O&&O({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var C=t.length,N=function _loop2(e){if(!(e in t)){var r=n+(n?\".\":\"\")+e;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},function(){var n=_encapsulate(r,void 0,!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n)})}},B=0;B-1){var r=e[unescapeKeyPathComponent(n.substr(0,t))];return void 0===r?void 0:getByKeyPath(r,n.substr(t+1))}return e[unescapeKeyPathComponent(n)]}function Undefined(){}function TypesonPromise(e){this.p=new Promise(e)}return TypesonPromise.prototype.then=function(e,n){var t=this;return new TypesonPromise(function(r,i){t.p.then(function(n){r(e?e(n):n)},function(e){t.p.catch(function(e){return n?n(e):Promise.reject(e)}).then(r,i)})})},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise(function(n){n(e)})},TypesonPromise.reject=function(e){return new TypesonPromise(function(n,t){t(e)})},[\"all\",\"race\"].map(function(e){TypesonPromise[e]=function(n){return new TypesonPromise(function(t,r){Promise[e](n.map(function(e){return e.p})).then(t,r)})}}),Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=function isUserObject(e){if(!e||\"Object\"!==toStringTag(e))return!1;var n=s(e);return!n||hasConstructorOf(e,Object)||isUserObject(n)},Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=function(n){return null===n?\"null\":i(n)?\"array\":void 0===n?\"undefined\":e(n)},Typeson.JSON_TYPES=[\"null\",\"boolean\",\"number\",\"string\",\"array\",\"object\"],Typeson});\n","const keys = Object.keys,\n isArray = Array.isArray,\n toString = ({}.toString),\n getProto = Object.getPrototypeOf,\n hasOwn = ({}.hasOwnProperty),\n fnToString = hasOwn.toString,\n internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric'];\n\nfunction isThenable (v, catchCheck) {\n return Typeson.isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v.catch === 'function');\n}\n\nfunction toStringTag (val) {\n return toString.call(val).slice(8, -1);\n}\n\n// This function is dependent on both constructors\n// being identical so any minimization is expected of both\nfunction hasConstructorOf (a, b) {\n if (!a || typeof a !== 'object') {\n return false;\n }\n const proto = getProto(a);\n if (!proto) {\n return false;\n }\n const Ctor = hasOwn.call(proto, 'constructor') && proto.constructor;\n if (typeof Ctor !== 'function') {\n return b === null;\n }\n return typeof Ctor === 'function' && b !== null && fnToString.call(Ctor) === fnToString.call(b);\n}\n\nfunction isPlainObject (val) { // Mirrors jQuery's\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n const proto = getProto(val);\n if (!proto) { // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object);\n}\n\nfunction isUserObject (val) {\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n const proto = getProto(val);\n if (!proto) { // `Object.create(null)`\n return true;\n }\n return hasConstructorOf(val, Object) || isUserObject(proto);\n}\n\nfunction isObject (v) {\n return v && typeof v === 'object';\n}\n\n/* Typeson - JSON with types\n * License: The MIT License (MIT)\n * Copyright (c) 2016 David Fahlander\n */\n\n/** An instance of this class can be used to call stringify() and parse().\n * Typeson resolves cyclic references by default. Can also be extended to\n * support custom types using the register() method.\n *\n * @constructor\n * @param {{cyclic: boolean}} [options] - if cyclic (default true), cyclic references will be handled gracefully.\n */\nfunction Typeson (options) {\n // Replacers signature: replace (value). Returns falsy if not replacing. Otherwise ['Date', value.getTime()]\n const plainObjectReplacers = [];\n const nonplainObjectReplacers = [];\n // Revivers: map {type => reviver}. Sample: {'Date': value => new Date(value)}\n const revivers = {};\n\n /** Types registered via register() */\n const regTypes = this.types = {};\n\n /** Serialize given object to Typeson.\n *\n * Arguments works identical to those of JSON.stringify().\n */\n const stringify = this.stringify = function (obj, replacer, space, opts) { // replacer here has nothing to do with our replacers.\n opts = Object.assign({}, options, opts, {stringification: true});\n const encapsulated = encapsulate(obj, null, opts);\n if (isArray(encapsulated)) {\n return JSON.stringify(encapsulated[0], replacer, space);\n }\n return encapsulated.then((res) => {\n return JSON.stringify(res, replacer, space);\n });\n };\n\n // Also sync but throws on non-sync result\n this.stringifySync = function (obj, replacer, space, opts) {\n return stringify(obj, replacer, space, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true}));\n };\n this.stringifyAsync = function (obj, replacer, space, opts) {\n return stringify(obj, replacer, space, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false}));\n };\n\n /** Parse Typeson back into an obejct.\n *\n * Arguments works identical to those of JSON.parse().\n */\n const parse = this.parse = function (text, reviver, opts) {\n opts = Object.assign({}, options, opts, {parse: true});\n return revive(JSON.parse(text, reviver), opts); // This reviver has nothing to do with our revivers.\n };\n\n // Also sync but throws on non-sync result\n this.parseSync = function (text, reviver, opts) {\n return parse(text, reviver, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true})); // This reviver has nothing to do with our revivers.\n };\n this.parseAsync = function (text, reviver, opts) {\n return parse(text, reviver, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false})); // This reviver has nothing to do with our revivers.\n };\n\n this.specialTypeNames = function (obj, stateObj, opts = {}) {\n opts.returnTypeNames = true;\n return this.encapsulate(obj, stateObj, opts);\n };\n this.rootTypeName = function (obj, stateObj, opts = {}) {\n opts.iterateNone = true;\n return this.encapsulate(obj, stateObj, opts);\n };\n\n /** Encapsulate a complex object into a plain Object by replacing registered types with\n * plain objects representing the types data.\n *\n * This method is used internally by Typeson.stringify().\n * @param {Object} obj - Object to encapsulate.\n */\n const encapsulate = this.encapsulate = function (obj, stateObj, opts) {\n opts = Object.assign({sync: true}, options, opts);\n const sync = opts.sync;\n const types = {},\n refObjs = [], // For checking cyclic references\n refKeys = [], // For checking cyclic references\n promisesDataRoot = [];\n // Clone the object deeply while at the same time replacing any special types or cyclic reference:\n const cyclic = opts && ('cyclic' in opts) ? opts.cyclic : true;\n const encapsulateObserver = opts.encapsulateObserver;\n const ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot);\n function finish (ret) {\n // Add $types to result only if we ever bumped into a special type (or special case where object has own `$types`)\n const typeNames = Object.values(types);\n if (opts.iterateNone) {\n if (typeNames.length) {\n return typeNames[0];\n }\n return Typeson.getJSONType(ret);\n }\n if (typeNames.length) {\n if (opts.returnTypeNames) {\n return [...new Set(typeNames)];\n }\n if (!ret || !isPlainObject(ret) || // Special if array (or a primitive) was serialized because JSON would ignore custom `$types` prop on it\n ret.hasOwnProperty('$types') // Also need to handle if this is an object with its own `$types` property (to avoid ambiguity)\n ) {\n ret = {$: ret, $types: {$: types}};\n } else {\n ret.$types = types;\n }\n } else if (isObject(ret) && ret.hasOwnProperty('$types')) { // No special types\n ret = {$: ret, $types: true};\n }\n if (opts.returnTypeNames) {\n return false;\n }\n return ret;\n }\n function checkPromises (ret, promisesData) {\n return Promise.all(\n promisesData.map((pd) => { return pd[1].p; })\n ).then(function (promResults) {\n return Promise.all(\n promResults.map(function (promResult) {\n const newPromisesData = [];\n const prData = promisesData.splice(0, 1)[0];\n const [keyPath, , cyclic, stateObj, parentObj, key, detectedType] = prData;\n\n const encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType);\n const isTypesonPromise = hasConstructorOf(encaps, TypesonPromise);\n if (keyPath && isTypesonPromise) { // Handle case where an embedded custom type itself returns a `Typeson.Promise`\n return encaps.p.then(function (encaps2) {\n parentObj[key] = encaps2;\n return checkPromises(ret, newPromisesData);\n });\n }\n if (keyPath) parentObj[key] = encaps;\n else if (isTypesonPromise) {\n ret = encaps.p;\n } else ret = encaps; // If this is itself a `Typeson.Promise` (because the original value supplied was a promise or because the supplied custom type value resolved to one), returning it below will be fine since a promise is expected anyways given current config (and if not a promise, it will be ready as the resolve value)\n return checkPromises(ret, newPromisesData);\n })\n );\n }).then(() => ret);\n };\n return promisesDataRoot.length\n ? sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Sync method requested but async result obtained');\n })()\n : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish)\n : !sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Async method requested but sync result obtained');\n })()\n : (opts.stringification && sync // If this is a synchronous request for stringification, yet a promise is the result, we don't want to resolve leading to an async result, so we return an array to avoid ambiguity\n ? [finish(ret)]\n : (sync\n ? finish(ret)\n : Promise.resolve(finish(ret))\n ));\n\n function _adaptBuiltinStateObjectProperties (stateObj, ownKeysObj, cb) {\n Object.assign(stateObj, ownKeysObj);\n const vals = internalStateObjPropsToIgnore.map((prop) => {\n const tmp = stateObj[prop];\n delete stateObj[prop];\n return tmp;\n });\n cb();\n internalStateObjPropsToIgnore.forEach((prop, i) => {\n stateObj[prop] = vals[i];\n });\n }\n function _encapsulate (keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) {\n let ret;\n let observerData = {};\n const $typeof = typeof value;\n const runObserver = encapsulateObserver ? function (obj) {\n const type = detectedType || stateObj.type || (\n Typeson.getJSONType(value)\n );\n encapsulateObserver(Object.assign(obj || observerData, {\n keypath,\n value,\n cyclic,\n stateObj,\n promisesData,\n resolvingTypesonPromise,\n awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise)\n }, type !== undefined ? {type} : {}));\n } : null;\n if ($typeof in {string: 1, boolean: 1, number: 1, undefined: 1}) {\n if (value === undefined || ($typeof === 'number' &&\n (isNaN(value) || value === -Infinity || value === Infinity))) {\n ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver);\n if (ret !== value) {\n observerData = {replaced: ret};\n }\n } else {\n ret = value;\n }\n if (runObserver) runObserver();\n return ret;\n }\n if (value === null) {\n if (runObserver) runObserver();\n return value;\n }\n if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric) {\n // Options set to detect cyclic references and be able to rewrite them.\n const refIndex = refObjs.indexOf(value);\n if (refIndex < 0) {\n if (cyclic === true) {\n refObjs.push(value);\n refKeys.push(keypath);\n }\n } else {\n types[keypath] = '#';\n if (runObserver) {\n runObserver({\n cyclicKeypath: refKeys[refIndex]\n });\n }\n return '#' + refKeys[refIndex];\n }\n }\n const isPlainObj = isPlainObject(value);\n const isArr = isArray(value);\n const replaced = (\n ((isPlainObj || isArr) && (!plainObjectReplacers.length || stateObj.replaced)) ||\n stateObj.iterateIn // Running replace will cause infinite loop as will test positive again\n )\n // Optimization: if plain object and no plain-object replacers, don't try finding a replacer\n ? value\n : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver);\n let clone;\n if (replaced !== value) {\n ret = replaced;\n observerData = {replaced: replaced};\n } else {\n if (isArr || stateObj.iterateIn === 'array') {\n clone = new Array(value.length);\n observerData = {clone: clone};\n } else if (isPlainObj || stateObj.iterateIn === 'object') {\n clone = {};\n observerData = {clone: clone};\n } else if (keypath === '' && hasConstructorOf(value, TypesonPromise)) {\n promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]);\n ret = value;\n } else {\n ret = value; // Only clone vanilla objects and arrays\n }\n }\n if (runObserver) runObserver();\n\n if (opts.iterateNone) {\n return clone || ret;\n }\n\n if (!clone) {\n return ret;\n }\n\n // Iterate object or array\n if (stateObj.iterateIn) {\n for (const key in value) {\n const ownKeysObj = {ownKeys: value.hasOwnProperty(key)};\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, () => {\n const kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n const val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise);\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) clone[key] = val;\n });\n }\n if (runObserver) runObserver({endIterateIn: true, end: true});\n } else { // Note: Non-indexes on arrays won't survive stringify so somewhat wasteful for arrays, but so too is iterating all numeric indexes on sparse arrays when not wanted or filtering own keys for positive integers\n keys(value).forEach(function (key) {\n const kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n const ownKeysObj = {ownKeys: true};\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, () => {\n const val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise);\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) clone[key] = val;\n });\n });\n if (runObserver) runObserver({endIterateOwn: true, end: true});\n }\n // Iterate array for non-own numeric properties (we can't replace the prior loop though as it iterates non-integer keys)\n if (stateObj.iterateUnsetNumeric) {\n const vl = value.length;\n for (let i = 0; i < vl; i++) {\n if (!(i in value)) {\n const kp = keypath + (keypath ? '.' : '') + i; // No need to escape numeric\n const ownKeysObj = {ownKeys: false};\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, () => {\n const val = _encapsulate(kp, undefined, !!cyclic, stateObj, promisesData, resolvingTypesonPromise);\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, !!cyclic, stateObj, clone, i, stateObj.type]);\n } else if (val !== undefined) clone[i] = val;\n });\n }\n }\n if (runObserver) runObserver({endIterateUnsetNumeric: true, end: true});\n }\n return clone;\n }\n\n function replace (keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) {\n // Encapsulate registered types\n const replacers = plainObject ? plainObjectReplacers : nonplainObjectReplacers;\n let i = replacers.length;\n while (i--) {\n const replacer = replacers[i];\n if (replacer.test(value, stateObj)) {\n const type = replacer.type;\n if (revivers[type]) {\n // Record the type only if a corresponding reviver exists.\n // This is to support specs where only replacement is done.\n // For example ensuring deep cloning of the object, or\n // replacing a type to its equivalent without the need to revive it.\n const existing = types[keypath];\n // type can comprise an array of types (see test shouldSupportIntermediateTypes)\n types[keypath] = existing ? [type].concat(existing) : type;\n }\n // Now, also traverse the result in case it contains its own types to replace\n Object.assign(stateObj, {type, replaced: true});\n if ((sync || !replacer.replaceAsync) && !replacer.replace) {\n if (runObserver) runObserver({typeDetected: true});\n return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n if (runObserver) runObserver({replacing: true});\n\n const replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync';\n return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n }\n return value;\n }\n };\n\n // Also sync but throws on non-sync result\n this.encapsulateSync = function (obj, stateObj, opts) {\n return encapsulate(obj, stateObj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true}));\n };\n this.encapsulateAsync = function (obj, stateObj, opts) {\n return encapsulate(obj, stateObj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false}));\n };\n\n /** Revive an encapsulated object.\n * This method is used internally by Typeson.parse().\n * @param {Object} obj - Object to revive. If it has $types member, the properties that are listed there\n * will be replaced with its true type instead of just plain objects.\n */\n const revive = this.revive = function (obj, opts) {\n opts = Object.assign({sync: true}, options, opts);\n const sync = opts.sync;\n let types = obj && obj.$types,\n ignore$Types = true;\n if (!types) return obj; // No type info added. Revival not needed.\n if (types === true) return obj.$; // Object happened to have own `$types` property but with no actual types, so we unescape and return that object\n if (types.$ && isPlainObject(types.$)) {\n // Special when root object is not a trivial Object, it will be encapsulated in $. It will also be encapsulated in $ if it has its own `$` property to avoid ambiguity\n obj = obj.$;\n types = types.$;\n ignore$Types = false;\n }\n const keyPathResolutions = [];\n const stateObj = {};\n let ret = _revive('', obj, null, opts);\n ret = hasConstructorOf(ret, Undefined) ? undefined : ret;\n return isThenable(ret)\n ? sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Sync method requested but async result obtained');\n })()\n : ret\n : !sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Async method requested but sync result obtained');\n })()\n : sync\n ? ret\n : Promise.resolve(ret);\n\n function _revive (keypath, value, target, opts, clone, key) {\n if (ignore$Types && keypath === '$types') return;\n const type = types[keypath];\n if (isArray(value) || isPlainObject(value)) {\n const clone = isArray(value) ? new Array(value.length) : {};\n // Iterate object or array\n keys(value).forEach((key) => {\n const val = _revive(\n keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key), value[key],\n target || clone,\n opts,\n clone,\n key\n );\n if (hasConstructorOf(val, Undefined)) clone[key] = undefined;\n else if (val !== undefined) clone[key] = val;\n });\n value = clone;\n while (keyPathResolutions.length) { // Try to resolve cyclic reference as soon as available\n const [[target, keyPath, clone, key]] = keyPathResolutions;\n const val = getByKeyPath(target, keyPath);\n if (hasConstructorOf(val, Undefined)) clone[key] = undefined;\n else if (val !== undefined) clone[key] = val;\n else break;\n keyPathResolutions.splice(0, 1);\n }\n }\n if (!type) return value;\n if (type === '#') {\n const ret = getByKeyPath(target, value.substr(1));\n if (ret === undefined) { // Cyclic reference not yet available\n keyPathResolutions.push([target, value.substr(1), clone, key]);\n }\n return ret;\n }\n const sync = opts.sync;\n return [].concat(type).reduce((val, type) => {\n const reviver = revivers[type];\n if (!reviver) throw new Error('Unregistered type: ' + type);\n return reviver[ // eslint-disable-line standard/computed-property-even-spacing\n sync && reviver.revive\n ? 'revive'\n : !sync && reviver.reviveAsync\n ? 'reviveAsync'\n : 'revive'\n ](val, stateObj);\n }, value);\n }\n };\n\n // Also sync but throws on non-sync result\n this.reviveSync = function (obj, opts) {\n return revive(obj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true}));\n };\n this.reviveAsync = function (obj, opts) {\n return revive(obj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false}));\n };\n\n /** Register types.\n * For examples how to use this method, see https://github.com/dfahlander/typeson-registry/tree/master/types\n * @param {Array.>} typeSpec - Types and their functions [test, encapsulate, revive];\n */\n this.register = function (typeSpecSets, opts) {\n opts = opts || {};\n [].concat(typeSpecSets).forEach(function R (typeSpec) {\n if (isArray(typeSpec)) return typeSpec.map(R); // Allow arrays of arrays of arrays...\n typeSpec && keys(typeSpec).forEach(function (typeId) {\n if (typeId === '#') {\n throw new TypeError('# cannot be used as a type name as it is reserved for cyclic objects');\n } else if (Typeson.JSON_TYPES.includes(typeId)) {\n throw new TypeError('Plain JSON object types are reserved as type names');\n }\n let spec = typeSpec[typeId];\n const replacers = spec.testPlainObjects ? plainObjectReplacers : nonplainObjectReplacers;\n const existingReplacer = replacers.filter(function (r) { return r.type === typeId; });\n if (existingReplacer.length) {\n // Remove existing spec and replace with this one.\n replacers.splice(replacers.indexOf(existingReplacer[0]), 1);\n delete revivers[typeId];\n delete regTypes[typeId];\n }\n if (spec) {\n if (typeof spec === 'function') {\n // Support registering just a class without replacer/reviver\n const Class = spec;\n spec = {\n test: (x) => x && x.constructor === Class,\n replace: (x) => assign({}, x),\n revive: (x) => assign(Object.create(Class.prototype), x)\n };\n } else if (isArray(spec)) {\n spec = {\n test: spec[0],\n replace: spec[1],\n revive: spec[2]\n };\n }\n const replacerObj = {\n type: typeId,\n test: spec.test.bind(spec)\n };\n if (spec.replace) {\n replacerObj.replace = spec.replace.bind(spec);\n }\n if (spec.replaceAsync) {\n replacerObj.replaceAsync = spec.replaceAsync.bind(spec);\n }\n const start = typeof opts.fallback === 'number' ? opts.fallback : (opts.fallback ? 0 : Infinity);\n if (spec.testPlainObjects) {\n plainObjectReplacers.splice(start, 0, replacerObj);\n } else {\n nonplainObjectReplacers.splice(start, 0, replacerObj);\n }\n // Todo: We might consider a testAsync type\n if (spec.revive || spec.reviveAsync) {\n const reviverObj = {};\n if (spec.revive) reviverObj.revive = spec.revive.bind(spec);\n if (spec.reviveAsync) reviverObj.reviveAsync = spec.reviveAsync.bind(spec);\n revivers[typeId] = reviverObj;\n }\n\n regTypes[typeId] = spec; // Record to be retrieved via public types property.\n }\n });\n });\n return this;\n };\n}\n\nfunction assign (t, s) {\n keys(s).map((k) => { t[k] = s[k]; });\n return t;\n}\n\n/** escapeKeyPathComponent() utility */\nfunction escapeKeyPathComponent (keyPathComponent) {\n return keyPathComponent.replace(/~/g, '~0').replace(/\\./g, '~1');\n}\n\n/** unescapeKeyPathComponent() utility */\nfunction unescapeKeyPathComponent (keyPathComponent) {\n return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~');\n}\n\n/** getByKeyPath() utility */\nfunction getByKeyPath (obj, keyPath) {\n if (keyPath === '') return obj;\n const period = keyPath.indexOf('.');\n if (period > -1) {\n const innerObj = obj[unescapeKeyPathComponent(keyPath.substr(0, period))];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return obj[unescapeKeyPathComponent(keyPath)];\n}\n\n// We keep these two functions minimized so if using two instances of this\n// library, where one is minimized and one is not, it will still work\nfunction Undefined(){} // eslint-disable-line space-before-function-paren, space-before-blocks\n// With ES6 classes, we may be able to simply use `class TypesonPromise extends Promise` and add a string tag for detection\nfunction TypesonPromise(f){this.p=new Promise(f)} // eslint-disable-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi\n\nTypesonPromise.prototype.then = function (onFulfilled, onRejected) {\n return new TypesonPromise((typesonResolve, typesonReject) => {\n this.p.then(function (res) {\n typesonResolve(onFulfilled ? onFulfilled(res) : res);\n }, (r) => {\n this.p['catch'](function (res) {\n return onRejected ? onRejected(res) : Promise.reject(res);\n }).then(typesonResolve, typesonReject);\n });\n });\n};\nTypesonPromise.prototype['catch'] = function (onRejected) {\n return this.then(null, onRejected);\n};\nTypesonPromise.resolve = function (v) {\n return new TypesonPromise((typesonResolve) => {\n typesonResolve(v);\n });\n};\nTypesonPromise.reject = function (v) {\n return new TypesonPromise((typesonResolve, typesonReject) => {\n typesonReject(v);\n });\n};\n['all', 'race'].map(function (meth) {\n TypesonPromise[meth] = function (promArr) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n Promise[meth](promArr.map((prom) => { return prom.p; })).then(typesonResolve, typesonReject);\n });\n };\n});\n\n// The following provide classes meant to avoid clashes with other values\nTypeson.Undefined = Undefined; // To insist `undefined` should be added\nTypeson.Promise = TypesonPromise; // To support async encapsulation/stringification\n\n// Some fundamental type-checking utilities\nTypeson.isThenable = isThenable;\nTypeson.toStringTag = toStringTag;\nTypeson.hasConstructorOf = hasConstructorOf;\nTypeson.isObject = isObject;\nTypeson.isPlainObject = isPlainObject;\nTypeson.isUserObject = isUserObject;\n\nTypeson.escapeKeyPathComponent = escapeKeyPathComponent;\nTypeson.unescapeKeyPathComponent = unescapeKeyPathComponent;\nTypeson.getByKeyPath = getByKeyPath;\nTypeson.getJSONType = (value) =>\n value === null ? 'null' : (\n isArray(value)\n ? 'array'\n : typeof value);\nTypeson.JSON_TYPES = [\n 'null', 'boolean', 'number', 'string', 'array', 'object'\n];\n\nexport default Typeson;\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n// Use a lookup table to find the index.\nconst lookup = new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n\nexport const encode = function (arraybuffer, byteOffset, length) {\n const bytes = new Uint8Array(arraybuffer, byteOffset, length),\n len = bytes.length;\n let base64 = '';\n\n for (let i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n\n if ((len % 3) === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n\n return base64;\n};\n\nexport const decode = function (base64) {\n const len = base64.length;\n\n let bufferLength = base64.length * 0.75;\n let p = 0;\n let encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n const arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (let i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n\n return arraybuffer;\n};\n","import Typeson from 'typeson';\n\nexport default {\n userObject: {\n test (x, stateObj) { return Typeson.isUserObject(x); },\n replace (n) { return Object.assign({}, n); },\n revive (s) { return s; }\n }\n};\n","export default [\n {\n sparseArrays: {\n testPlainObjects: true,\n test (x) { return Array.isArray(x); },\n replace (a, stateObj) {\n stateObj.iterateUnsetNumeric = true;\n return a;\n }\n }\n },\n {\n sparseUndefined: {\n test (x, stateObj) {\n return typeof x === 'undefined' && stateObj.ownKeys === false;\n },\n replace (n) { return null; },\n revive (s) { return undefined; } // Will avoid adding anything\n }\n }\n];\n","// This does not preserve `undefined` in sparse arrays; see the `undefined` or `sparse-undefined` preset\nimport Typeson from 'typeson';\n\nexport default {\n undef: {\n test (x, stateObj) {\n return typeof x === 'undefined' &&\n (stateObj.ownKeys || !('ownKeys' in stateObj));\n },\n replace (n) { return null; },\n revive (s) { return new Typeson.Undefined(); } // Will add `undefined` (returning `undefined` would instead avoid explicitly setting)\n }\n};\n","// This module is for objectified primitives (such as `new Number(3)` or\n// `new String(\"foo\")`)\n/* eslint-disable no-new-wrappers */\nimport Typeson from 'typeson';\nexport default {\n // String Object (not primitive string which need no type spec)\n StringObject: {\n test (x) { return Typeson.toStringTag(x) === 'String' && typeof x === 'object'; },\n replace (s) { return String(s); }, // convert to primitive string\n revive (s) { return new String(s); } // Revive to an objectified string\n },\n // Boolean Object (not primitive boolean which need no type spec)\n BooleanObject: {\n test (x) { return Typeson.toStringTag(x) === 'Boolean' && typeof x === 'object'; },\n replace (b) { return Boolean(b); }, // convert to primitive boolean\n revive (b) { return new Boolean(b); } // Revive to an objectified Boolean\n },\n // Number Object (not primitive number which need no type spec)\n NumberObject: {\n test (x) { return Typeson.toStringTag(x) === 'Number' && typeof x === 'object'; },\n replace (n) { return Number(n); }, // convert to primitive number\n revive (n) { return new Number(n); } // Revive to an objectified number\n }\n};\n/* eslint-enable no-new-wrappers */\n","export default {\n nan: {\n test (x) { return typeof x === 'number' && isNaN(x); },\n replace (n) { return 'NaN'; },\n revive (s) { return NaN; }\n }\n};\n","export default {\n infinity: {\n test (x) { return x === Infinity; },\n replace (n) { return 'Infinity'; },\n revive (s) { return Infinity; }\n }\n};\n","export default {\n negativeInfinity: {\n test (x) { return x === -Infinity; },\n replace (n) { return '-Infinity'; },\n revive (s) { return -Infinity; }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n date: {\n test (x) { return Typeson.toStringTag(x) === 'Date'; },\n replace (date) {\n const time = date.getTime();\n if (isNaN(time)) {\n return 'NaN';\n }\n return time;\n },\n revive (time) {\n if (time === 'NaN') {\n return new Date(NaN);\n }\n return new Date(time);\n }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n regexp: {\n test (x) { return Typeson.toStringTag(x) === 'RegExp'; },\n replace (rexp) {\n return {\n source: rexp.source,\n flags: (rexp.global ? 'g' : '') +\n (rexp.ignoreCase ? 'i' : '') +\n (rexp.multiline ? 'm' : '') +\n (rexp.sticky ? 'y' : '') +\n (rexp.unicode ? 'u' : '')\n };\n },\n revive ({source, flags}) { return new RegExp(source, flags); }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n map: {\n test (x) { return Typeson.toStringTag(x) === 'Map'; },\n replace (map) { return Array.from(map.entries()); },\n revive (entries) { return new Map(entries); }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n set: {\n test (x) { return Typeson.toStringTag(x) === 'Set'; },\n replace (set) { return Array.from(set.values()); },\n revive (values) { return new Set(values); }\n }\n};\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nexport default {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(b);\n if (index > -1) {\n return {index};\n }\n stateObj.buffers.push(b);\n return encode(b);\n },\n revive (b64, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n if (typeof b64 === 'object') {\n return stateObj.buffers[b64.index];\n }\n const buffer = decode(b64);\n stateObj.buffers.push(buffer);\n return buffer;\n }\n }\n};\n\n// See also typed-arrays!\n","/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst exportObj = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n if (TypedArray) {\n exportObj[typeName.toLowerCase()] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, length};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n length\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, length, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new TypedArray(buffer, byteOffset, length);\n }\n };\n }\n});\n\nexport default exportObj;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\nexport default {\n dataview: {\n test (x) { return Typeson.toStringTag(x) === 'DataView'; },\n replace ({buffer, byteOffset, byteLength}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, byteLength};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n byteLength\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, byteLength, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new DataView(buffer, byteOffset, byteLength);\n }\n }\n};\n","import Typeson from 'typeson';\n\nconst IntlCollator = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.Collator); },\n replace (c) { return c.resolvedOptions(); },\n revive (options) { return new Intl.Collator(options.locale, options); }\n};\n\nconst IntlDateTimeFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.DateTimeFormat); },\n replace (dtf) { return dtf.resolvedOptions(); },\n revive (options) { return new Intl.DateTimeFormat(options.locale, options); }\n};\n\nconst IntlNumberFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.NumberFormat); },\n replace (nf) { return nf.resolvedOptions(); },\n revive (options) { return new Intl.NumberFormat(options.locale, options); }\n};\n\nexport default {\n IntlCollator,\n IntlDateTimeFormat,\n IntlNumberFormat\n};\n","function arraybuffer2string (buf) {\n return new Uint16Array(buf).reduce((s, byte) => s + String.fromCharCode(byte), '');\n}\n\nfunction string2arraybuffer (str) {\n /*\n // UTF-8 approaches\n const utf8 = unescape(encodeURIComponent(str));\n const arr = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n arr[i] = utf8.charCodeAt(i);\n }\n return arr.buffer;\n\n const utf8 = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 0x80) utf8.push(charcode);\n else if (charcode < 0x800) {\n utf8.push(0xc0 | (charcode >> 6),\n 0x80 | (charcode & 0x3f));\n } else if (charcode < 0xd800 || charcode >= 0xe000) {\n utf8.push(0xe0 | (charcode >> 12),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n // surrogate pair\n } else {\n i++;\n // UTF-16 encodes 0x10000-0x10FFFF by\n // subtracting 0x10000 and splitting the\n // 20 bits of 0x0-0xFFFFF into two halves\n charcode = 0x10000 + (((charcode & 0x3ff) << 10) |\n (str.charCodeAt(i) & 0x3ff));\n utf8.push(0xf0 | (charcode >> 18),\n 0x80 | ((charcode >> 12) & 0x3f),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n }\n }\n return utf8;\n */\n /*\n // Working UTF-16 options (equivalents)\n const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char\n const bufView = new Uint16Array(buf);\n for (let i = 0, strLen = str.length; i < strLen; i++) {\n bufView[i] = str.charCodeAt(i);\n }\n return buf;\n */\n\n const array = new Uint16Array(str.length);\n for (let i = 0; i < str.length; i++) {\n array[i] = str.charCodeAt(i);\n }\n return array.buffer;\n}\nexport {arraybuffer2string, string2arraybuffer};\n","import Typeson from 'typeson';\n\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nexport default {\n file: {\n test (x) { return Typeson.toStringTag(x) === 'File'; },\n replace (f) { // Sync\n const req = new XMLHttpRequest();\n req.open('GET', URL.createObjectURL(f), false); // Sync\n if (typeof TextEncoder !== 'undefined') { // Using TextDecoder/TextEncoder used too much space\n req.overrideMimeType('text/plain; charset=utf-16le');\n }\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad Blob access: ' + req.status);\n }\n req.send();\n return {\n type: f.type,\n stringContents: req.responseText,\n name: f.name,\n lastModified: f.lastModified\n };\n },\n revive ({name, type, stringContents, lastModified}) {\n // stringContents = new TextEncoder().encode(stringContents);\n const buffer = string2arraybuffer(stringContents);\n // stringContents = new TextDecoder('utf-16le').decode(buffer);\n return new File([buffer], name, {\n type,\n lastModified\n });\n },\n replaceAsync (f) {\n return new Typeson.Promise(function (resolve, reject) {\n if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The File is closed'));\n return;\n }\n const reader = new FileReader();\n reader.addEventListener('load', function () {\n resolve({\n type: f.type,\n stringContents: reader.result,\n name: f.name,\n lastModified: f.lastModified\n });\n });\n reader.addEventListener('error', function () {\n reject(reader.error);\n });\n reader.readAsText(f, 'UTF-16');\n });\n }\n }\n};\n","/* This preset includes types for the Structured Cloning Algorithm. */\n\nimport userObject from '../types/user-object.js';\nimport presetUndefined from '../presets/undef.js';\nimport primitiveObjects from '../types/primitive-objects.js';\nimport specialNumbers from '../presets/special-numbers.js';\nimport date from '../types/date.js';\nimport regexp from '../types/regexp.js';\nimport map from '../types/map.js';\nimport set from '../types/set.js';\nimport arraybuffer from '../types/arraybuffer.js';\nimport typedArrays from '../types/typed-arrays.js';\nimport dataview from '../types/dataview.js';\nimport intlTypes from '../types/intl-types.js';\n\nimport imagedata from '../types/imagedata.js';\nimport imagebitmap from '../types/imagebitmap.js'; // Async return\nimport file from '../types/file.js';\nimport filelist from '../types/filelist.js';\nimport blob from '../types/blob.js';\n\nconst expObj = [\n // Todo: Might also register synchronous `ImageBitmap` and `Blob`/`File`/`FileList`?\n // ES5\n userObject, // Processed last (non-builtin)\n\n presetUndefined, primitiveObjects, specialNumbers,\n date, regexp,\n\n // Non-built-ins\n imagedata,\n imagebitmap, // Async return\n file,\n filelist,\n blob\n].concat(\n // ES2015 (ES6)\n typeof Map === 'function' ? map : [],\n typeof Set === 'function' ? set : [],\n typeof ArrayBuffer === 'function' ? arraybuffer : [],\n typeof Uint8Array === 'function' ? typedArrays : [],\n typeof DataView === 'function' ? dataview : [],\n typeof Intl !== 'undefined' ? intlTypes : []\n);\nexport default expObj;\n","/** ImageData is browser / DOM specific (though `node-canvas` has it available on `Canvas`).\n*/\nimport Typeson from 'typeson';\nexport default {\n imagedata: {\n test (x) { return Typeson.toStringTag(x) === 'ImageData'; },\n replace (d) {\n return {\n array: Array.from(d.data), // Ensure `length` gets preserved for revival\n width: d.width,\n height: d.height\n };\n },\n revive (o) {\n return new ImageData(new Uint8ClampedArray(o.array), o.width, o.height);\n }\n }\n};\n","/** ImageBitmap is browser / DOM specific. It also can only work same-domain (or CORS)\n*/\nimport Typeson from 'typeson';\nexport default {\n imagebitmap: {\n test (x) {\n return Typeson.toStringTag(x) === 'ImageBitmap' ||\n // In Node, our polyfill sets the dataset on a canvas element as JSDom no longer allows overriding toStringTag\n (x && x.dataset && x.dataset.toStringTag === 'ImageBitmap');\n },\n replace (bm) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n ctx.drawImage(bm, 0, 0);\n // Although `width` and `height` are part of `ImageBitMap`, these will\n // be auto-created for us when reviving with the data URL (and they are\n // not settable even if they weren't)\n // return {width: bm.width, height: bm.height, dataURL: canvas.toDataURL()};\n return canvas.toDataURL();\n },\n revive (o) {\n /*\n var req = new XMLHttpRequest();\n req.open('GET', o, false); // Sync\n if (req.status !== 200 && req.status !== 0) throw new Error('Bad ImageBitmap access: ' + req.status);\n req.send();\n return req.responseText;\n */\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.onload = function () {\n ctx.drawImage(img, 0, 0);\n };\n img.src = o;\n return canvas; // Works in contexts allowing an ImageBitmap (We might use `OffscreenCanvas.transferToBitmap` when supported)\n },\n reviveAsync (o) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.onload = function () {\n ctx.drawImage(img, 0, 0);\n };\n img.src = o; // o.dataURL;\n return createImageBitmap(canvas); // Returns a promise\n }\n }\n};\n","import Typeson from 'typeson';\nimport file from './file.js';\nexport default {\n file: file.file,\n filelist: {\n test (x) { return Typeson.toStringTag(x) === 'FileList'; },\n replace (fl) {\n const arr = [];\n for (let i = 0; i < fl.length; i++) {\n arr[i] = fl.item(i);\n }\n return arr;\n },\n revive (o) {\n function FileList () {\n this._files = arguments[0];\n this.length = this._files.length;\n }\n FileList.prototype.item = function (index) {\n return this._files[index];\n };\n FileList.prototype[Symbol.toStringTag] = 'FileList';\n return new FileList(o);\n }\n }\n};\n","import Typeson from 'typeson';\n\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nexport default {\n blob: {\n test (x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace (b) { // Sync\n const req = new XMLHttpRequest();\n req.open('GET', URL.createObjectURL(b), false); // Sync\n if (typeof TextEncoder !== 'undefined') { // Using TextDecoder/TextEncoder used too much space\n req.overrideMimeType('text/plain; charset=utf-16le');\n }\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad Blob access: ' + req.status);\n }\n req.send();\n return {\n type: b.type,\n stringContents: req.responseText\n };\n },\n revive ({type, stringContents}) {\n return new Blob([string2arraybuffer(stringContents)], {type});\n },\n replaceAsync (b) {\n return new Typeson.Promise((resolve, reject) => {\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The Blob is closed'));\n return;\n }\n const reader = new FileReader();\n reader.addEventListener('load', () => {\n resolve({\n type: b.type,\n stringContents: reader.result\n });\n });\n reader.addEventListener('error', () => {\n reject(reader.error);\n });\n reader.readAsText(b, 'UTF-16');\n });\n }\n }\n};\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.\n\nvar lookup = new Uint8Array(256);\n\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n\nvar encode = function encode(arraybuffer, byteOffset, length) {\n if (length === null || length === undefined) {\n length = arraybuffer.byteLength; // Needed for Safari\n }\n\n var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari\n length);\n var len = bytes.length;\n var base64 = '';\n\n for (var _i = 0; _i < len; _i += 3) {\n base64 += chars[bytes[_i] >> 2];\n base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4];\n base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6];\n base64 += chars[bytes[_i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n\n return base64;\n};\nvar decode = function decode(base64) {\n var len = base64.length;\n var bufferLength = base64.length * 0.75;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (var _i2 = 0; _i2 < len; _i2 += 4) {\n encoded1 = lookup[base64.charCodeAt(_i2)];\n encoded2 = lookup[base64.charCodeAt(_i2 + 1)];\n encoded3 = lookup[base64.charCodeAt(_i2 + 2)];\n encoded4 = lookup[base64.charCodeAt(_i2 + 3)];\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n\n return arraybuffer;\n};\n\nexport { decode, encode };\n","declare var global;\n\n/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst exportObj = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n if (TypedArray) {\n exportObj[typeName.toLowerCase()+\"2\"] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length}) {\n return {\n buffer,\n byteOffset,\n length\n };\n },\n revive (b64Obj) {\n const {buffer, byteOffset, length} = b64Obj;\n return new TypedArray(buffer, byteOffset, length);\n }\n };\n }\n});\n\nexport default exportObj;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nexport default {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b) {\n return encode(b, 0, b.byteLength);\n },\n revive (b64) {\n const buffer = decode(b64);\n return buffer;\n }\n }\n};\n\n// See also typed-arrays!\n","import Typeson from 'typeson';\nimport StructuredCloning from 'typeson-registry/dist/presets/structured-cloning';\nimport { encode as encodeB64, decode as decodeB64 } from 'base64-arraybuffer-es6';\nimport Dexie from 'dexie';\nimport { readBlobSync, readBlobAsync } from './helpers';\nimport typedArray from './tson-typed-array';\nimport arrayBuffer from './tson-arraybuffer';\n\nexport const TSON = new Typeson().register(StructuredCloning);\n\nconst readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\nlet blobsToAwait: any[] = [];\nlet blobsToAwaitPos = 0;\n\n// Need to patch encapsulateAsync as it does not work as of typeson 5.8.2\n// Also, current version of typespn-registry-1.0.0-alpha.21 does not\n// encapsulate/revive Blobs correctly (fails one of the unit tests in\n// this library (test 'export-format'))\nTSON.register([\n arrayBuffer,\n typedArray, {\n blob2: {\n test(x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace(b) {\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n throw new Error('The Blob is closed');\n }\n if (readBlobsSynchronously) {\n const data = readBlobSync(b, 'binary');\n const base64 = encodeB64(data, 0, data.byteLength);\n return {\n type: b.type,\n data: base64\n }\n } else {\n blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true.\n const result = {\n type: b.type,\n data: {start: blobsToAwaitPos, end: blobsToAwaitPos + b.size}\n }\n console.log(\"b.size: \" + b.size);\n blobsToAwaitPos += b.size;\n return result;\n }\n },\n finalize(b, ba: ArrayBuffer) {\n b.data = encodeB64(ba, 0, ba.byteLength);\n },\n revive ({type, data}) {\n return new Blob([decodeB64(data)], {type});\n }\n }\n }\n]);\n\nTSON.mustFinalize = ()=>blobsToAwait.length > 0;\n\nTSON.finalize = async (items?: any[]) => {\n const allChunks = await readBlobAsync(new Blob(blobsToAwait), 'binary');\n if (items) {\n for (const item of items) {\n // Manually go through all \"blob\" types in the result\n // and lookup the data slice they point at.\n if (item.$types) {\n let types = item.$types;\n const arrayType = types.$;\n if (arrayType) types = types.$;\n for (let keyPath in types) {\n const typeName = types[keyPath];\n const typeSpec = TSON.types[typeName];\n if (typeSpec && typeSpec.finalize) {\n const b = Dexie.getByKeyPath(item, arrayType ? \"$.\" + keyPath : keyPath);\n typeSpec.finalize(b, allChunks.slice(b.start, b.end));\n }\n }\n }\n }\n }\n // Free up memory\n blobsToAwait = [];\n}\n","\nimport Dexie from 'dexie';\nimport { getSchemaString, extractDbSchema } from './helpers';\nimport { DexieExportedTable, DexieExportJsonStructure } from './json-structure';\nimport { TSON } from './tson';\n\nexport interface ExportOptions {\n noTransaction?: boolean;\n numRowsPerChunk?: number;\n prettyJson?: boolean;\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ExportProgress) => boolean;\n}\n\nexport interface ExportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nconst DEFAULT_ROWS_PER_CHUNK = 2000;\n\nexport async function exportDB(db: Dexie, options?: ExportOptions): Promise {\n options = options || {};\n const slices: (string | Blob)[] = [];\n const tables = db.tables.map(table => ({\n name: table.name,\n schema: getSchemaString(table),\n rowCount: 0\n }));\n const {prettyJson} = options!;\n const emptyExport: DexieExportJsonStructure = {\n formatName: \"dexie\",\n formatVersion: 1,\n data: {\n databaseName: db.name,\n databaseVersion: db.verno,\n tables: tables,\n data: []\n }\n };\n \n const {progressCallback} = options!;\n const progress: ExportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: NaN,\n totalTables: db.tables.length\n };\n\n try {\n if (options!.noTransaction) {\n await exportAll();\n } else {\n await db.transaction('r', db.tables, exportAll);\n }\n } finally {\n TSON.finalize(); // Free up mem if error has occurred\n }\n\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n return new Blob(slices,{type: \"text/json\"});\n\n async function exportAll() {\n // Count rows:\n const tablesRowCounts = await Promise.all(db.tables.map(table => table.count()));\n tablesRowCounts.forEach((rowCount, i) => tables[i].rowCount = rowCount);\n progress.totalRows = tablesRowCounts.reduce((p,c)=>p+c);\n\n // Write first JSON slice\n const emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined);\n const posEndDataArray = emptyExportJson.lastIndexOf(']');\n const firstJsonSlice = emptyExportJson.substring(0, posEndDataArray);\n slices.push(firstJsonSlice);\n\n const filter = options!.filter;\n\n for (const {name: tableName} of tables) {\n const table = db.table(tableName);\n const {primKey} = table.schema;\n const inbound = !!primKey.keyPath;\n const LIMIT = options!.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK;\n const emptyTableExport: DexieExportedTable = inbound ? {\n tableName: table.name,\n inbound: true,\n rows: []\n } : {\n tableName: table.name,\n inbound: false,\n rows: []\n };\n let emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) {\n // Increase indentation according to this:\n // {\n // ...\n // data: [\n // ...\n // data: [\n // 123456<---- here\n // ] \n // ]\n // }\n emptyTableExportJson = emptyTableExportJson.split('\\n').join('\\n ');\n }\n const posEndRowsArray = emptyTableExportJson.lastIndexOf(']');\n slices.push(emptyTableExportJson.substring(0, posEndRowsArray));\n let lastKey: any = null;\n let lastNumRows = 0;\n let mayHaveMoreRows = true;\n while (mayHaveMoreRows) {\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const chunkedCollection = lastKey == null ?\n table.limit(LIMIT) :\n table.where(':id').above(lastKey).limit(LIMIT);\n\n const values = await chunkedCollection.toArray();\n\n if (values.length === 0) break;\n\n if (lastKey != null && lastNumRows > 0) {\n // Not initial chunk. Must add a comma:\n slices.push(\",\");\n if (prettyJson) {\n slices.push(\"\\n \");\n }\n }\n\n mayHaveMoreRows = values.length === LIMIT;\n \n if (inbound) {\n const filteredValues = filter ?\n values.filter(value => filter(tableName, value)) :\n values;\n\n const tsonValues = filteredValues.map(value => TSON.encapsulate(value));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonValues));\n }\n\n let json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = filteredValues.length;\n lastKey = values.length > 0 ?\n Dexie.getByKeyPath(values[values.length -1], primKey.keyPath as string) :\n null;\n } else {\n const keys = await chunkedCollection.primaryKeys();\n let keyvals = keys.map((key, i) => [key, values[i]]);\n if (filter) keyvals = keyvals.filter(([key, value]) => filter(tableName, value, key));\n\n const tsonTuples = keyvals.map(tuple => TSON.encapsulate(tuple));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonTuples));\n }\n\n let json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = keyvals.length;\n lastKey = keys.length > 0 ?\n keys[keys.length - 1] :\n null;\n }\n progress.completedRows += values.length;\n }\n slices.push(emptyTableExportJson.substr(posEndRowsArray)); // \"]}\"\n progress.completedTables += 1;\n if (progress.completedTables < progress.totalTables) {\n slices.push(\",\");\n }\n }\n slices.push(emptyExportJson.substr(posEndDataArray));\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n }\n}\n","export const VERSION = 1;\n\nexport interface DexieExportJsonStructure {\n formatName: 'dexie';\n formatVersion: typeof VERSION;\n data: {\n databaseName: string;\n databaseVersion: number;\n tables: Array<{\n name: string;\n schema: string;\n rowCount: number;\n }>;\n data: Array<{\n tableName: string;\n inbound: boolean;\n rows: any[];\n }>;\n }\n}\n\nexport type DexieExportedDatabase = DexieExportJsonStructure[\"data\"];\nexport type DexieExportedTable = DexieExportedDatabase[\"data\"][number];\n","module.exports = {Stream: function(){}};\n\n",";(function (clarinet) {\n \"use strict\";\n\n // non node-js needs to set clarinet debug on root\n var env =(typeof process === 'object' && process.env)\n ? process.env\n : self;\n\n clarinet.parser = function (opt) { return new CParser(opt);};\n clarinet.CParser = CParser;\n clarinet.CStream = CStream;\n clarinet.createStream = createStream;\n clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024;\n clarinet.DEBUG = (env.CDEBUG==='debug');\n clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info');\n clarinet.EVENTS =\n [ \"value\"\n , \"string\"\n , \"key\"\n , \"openobject\"\n , \"closeobject\"\n , \"openarray\"\n , \"closearray\"\n , \"error\"\n , \"end\"\n , \"ready\"\n ];\n\n var buffers = {\n textNode: undefined,\n numberNode: \"\"\n }\n , streamWraps = clarinet.EVENTS.filter(function (ev) {\n return ev !== \"error\" && ev !== \"end\";\n })\n , S = 0\n , Stream\n ;\n\n clarinet.STATE =\n { BEGIN : S++\n , VALUE : S++ // general stuff\n , OPEN_OBJECT : S++ // {\n , CLOSE_OBJECT : S++ // }\n , OPEN_ARRAY : S++ // [\n , CLOSE_ARRAY : S++ // ]\n , TEXT_ESCAPE : S++ // \\ stuff\n , STRING : S++ // \"\"\n , BACKSLASH : S++\n , END : S++ // No more stack\n , OPEN_KEY : S++ // , \"a\"\n , CLOSE_KEY : S++ // :\n , TRUE : S++ // r\n , TRUE2 : S++ // u\n , TRUE3 : S++ // e\n , FALSE : S++ // a\n , FALSE2 : S++ // l\n , FALSE3 : S++ // s\n , FALSE4 : S++ // e\n , NULL : S++ // u\n , NULL2 : S++ // l\n , NULL3 : S++ // l\n , NUMBER_DECIMAL_POINT : S++ // .\n , NUMBER_DIGIT : S++ // [0-9]\n };\n\n for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_;\n\n // switcharoo\n S = clarinet.STATE;\n\n const Char = {\n tab : 0x09, // \\t\n lineFeed : 0x0A, // \\n\n carriageReturn : 0x0D, // \\r\n space : 0x20, // \" \"\n\n doubleQuote : 0x22, // \"\n plus : 0x2B, // +\n comma : 0x2C, // ,\n minus : 0x2D, // -\n period : 0x2E, // .\n\n _0 : 0x30, // 0\n _9 : 0x39, // 9\n\n colon : 0x3A, // :\n\n E : 0x45, // E\n\n openBracket : 0x5B, // [\n backslash : 0x5C, // \\\n closeBracket : 0x5D, // ]\n\n a : 0x61, // a\n b : 0x62, // b\n e : 0x65, // e \n f : 0x66, // f\n l : 0x6C, // l\n n : 0x6E, // n\n r : 0x72, // r\n s : 0x73, // s\n t : 0x74, // t\n u : 0x75, // u\n\n openBrace : 0x7B, // {\n closeBrace : 0x7D, // }\n }\n\n if (!Object.create) {\n Object.create = function (o) {\n function f () { this[\"__proto__\"] = o; }\n f.prototype = o;\n return new f;\n };\n }\n\n if (!Object.getPrototypeOf) {\n Object.getPrototypeOf = function (o) {\n return o[\"__proto__\"];\n };\n }\n\n if (!Object.keys) {\n Object.keys = function (o) {\n var a = [];\n for (var i in o) if (o.hasOwnProperty(i)) a.push(i);\n return a;\n };\n }\n\n function checkBufferLength (parser) {\n var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10)\n , maxActual = 0\n ;\n for (var buffer in buffers) {\n var len = parser[buffer] === undefined ? 0 : parser[buffer].length;\n if (len > maxAllowed) {\n switch (buffer) {\n case \"text\":\n closeText(parser);\n break;\n\n default:\n error(parser, \"Max buffer length exceeded: \"+ buffer);\n }\n }\n maxActual = Math.max(maxActual, len);\n }\n parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual)\n + parser.position;\n }\n\n function clearBuffers (parser) {\n for (var buffer in buffers) {\n parser[buffer] = buffers[buffer];\n }\n }\n\n var stringTokenPattern = /[\\\\\"\\n]/g;\n\n function CParser (opt) {\n if (!(this instanceof CParser)) return new CParser (opt);\n\n var parser = this;\n clearBuffers(parser);\n parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH;\n parser.q = parser.c = parser.p = \"\";\n parser.opt = opt || {};\n parser.closed = parser.closedRoot = parser.sawRoot = false;\n parser.tag = parser.error = null;\n parser.state = S.BEGIN;\n parser.stack = new Array();\n // mostly just for error reporting\n parser.position = parser.column = 0;\n parser.line = 1;\n parser.slashed = false;\n parser.unicodeI = 0;\n parser.unicodeS = null;\n parser.depth = 0;\n emit(parser, \"onready\");\n }\n\n CParser.prototype =\n { end : function () { end(this); }\n , write : write\n , resume : function () { this.error = null; return this; }\n , close : function () { return this.write(null); }\n };\n\n try { Stream = require(\"stream\").Stream; }\n catch (ex) { Stream = function () {}; }\n\n function createStream (opt) { return new CStream(opt); }\n\n function CStream (opt) {\n if (!(this instanceof CStream)) return new CStream(opt);\n\n this._parser = new CParser(opt);\n this.writable = true;\n this.readable = true;\n\n //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error\n this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary\n this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read\n this.temp_buffs = { \"2\": new Buffer(2), \"3\": new Buffer(3), \"4\": new Buffer(4) }; // for rebuilding chars split before boundary is reached\n this.string = '';\n\n var me = this;\n Stream.apply(me);\n\n this._parser.onend = function () { me.emit(\"end\"); };\n this._parser.onerror = function (er) {\n me.emit(\"error\", er);\n me._parser.error = null;\n };\n\n streamWraps.forEach(function (ev) {\n Object.defineProperty(me, \"on\" + ev,\n { get : function () { return me._parser[\"on\" + ev]; }\n , set : function (h) {\n if (!h) {\n me.removeAllListeners(ev);\n me._parser[\"on\"+ev] = h;\n return h;\n }\n me.on(ev, h);\n }\n , enumerable : true\n , configurable : false\n });\n });\n }\n\n CStream.prototype = Object.create(Stream.prototype,\n { constructor: { value: CStream } });\n\n CStream.prototype.write = function (data) {\n data = new Buffer(data);\n for (var i = 0; i < data.length; i++) {\n var n = data[i];\n\n // check for carry over of a multi byte char split between data chunks\n // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration\n if (this.bytes_remaining > 0) {\n for (var j = 0; j < this.bytes_remaining; j++) {\n this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j];\n }\n this.string = this.temp_buffs[this.bytes_in_sequence].toString();\n this.bytes_in_sequence = this.bytes_remaining = 0;\n\n // move iterator forward by number of byte read during sequencing\n i = i + j - 1;\n\n // pass data to parser and move forward to parse rest of data\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n\n // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time\n if (this.bytes_remaining === 0 && n >= 128) {\n if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;\n if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;\n if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;\n if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split\n\n for (var k = 0; k <= (data.length - 1 - i); k++) {\n this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk\n }\n this.bytes_remaining = (i + this.bytes_in_sequence) - data.length;\n\n // immediately return as we need another chunk to sequence the character\n return true;\n } else {\n this.string = data.slice(i, (i + this.bytes_in_sequence)).toString();\n i = i + this.bytes_in_sequence - 1;\n\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n }\n\n // is there a range of characters that are immediately parsable?\n for (var p = i; p < data.length; p++) {\n if (data[p] >= 128) break;\n }\n this.string = data.slice(i, p).toString();\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n i = p - 1;\n\n // handle any remaining characters using multibyte logic\n continue;\n }\n };\n\n CStream.prototype.end = function (chunk) {\n if (chunk && chunk.length) this._parser.write(chunk.toString());\n this._parser.end();\n return true;\n };\n\n CStream.prototype.on = function (ev, handler) {\n var me = this;\n if (!me._parser[\"on\"+ev] && streamWraps.indexOf(ev) !== -1) {\n me._parser[\"on\"+ev] = function () {\n var args = arguments.length === 1 ? [arguments[0]]\n : Array.apply(null, arguments);\n args.splice(0, 0, ev);\n me.emit.apply(me, args);\n };\n }\n return Stream.prototype.on.call(me, ev, handler);\n };\n\n CStream.prototype.destroy = function () {\n clearBuffers(this._parser);\n this.emit(\"close\");\n };\n\n function emit(parser, event, data) {\n if(clarinet.INFO) console.log('-- emit', event, data);\n if (parser[event]) parser[event](data);\n }\n\n function emitNode(parser, event, data) {\n closeValue(parser);\n emit(parser, event, data);\n }\n\n function closeValue(parser, event) {\n parser.textNode = textopts(parser.opt, parser.textNode);\n if (parser.textNode !== undefined) {\n emit(parser, (event ? event : \"onvalue\"), parser.textNode);\n }\n parser.textNode = undefined;\n }\n\n function closeNumber(parser) {\n if (parser.numberNode)\n emit(parser, \"onvalue\", parseFloat(parser.numberNode));\n parser.numberNode = \"\";\n }\n\n function textopts (opt, text) {\n if (text === undefined) {\n return text;\n }\n if (opt.trim) text = text.trim();\n if (opt.normalize) text = text.replace(/\\s+/g, \" \");\n return text;\n }\n\n function error (parser, er) {\n closeValue(parser);\n er += \"\\nLine: \"+parser.line+\n \"\\nColumn: \"+parser.column+\n \"\\nChar: \"+parser.c;\n er = new Error(er);\n parser.error = er;\n emit(parser, \"onerror\", er);\n return parser;\n }\n\n function end(parser) {\n if (parser.state !== S.VALUE || parser.depth !== 0)\n error(parser, \"Unexpected end\");\n\n closeValue(parser);\n parser.c = \"\";\n parser.closed = true;\n emit(parser, \"onend\");\n CParser.call(parser, parser.opt);\n return parser;\n }\n\n function isWhitespace(c) {\n return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab;\n }\n\n function write (chunk) {\n var parser = this;\n if (this.error) throw this.error;\n if (parser.closed) return error(parser,\n \"Cannot write after close. Assign an onready handler.\");\n if (chunk === null) return end(parser);\n var i = 0, c = chunk.charCodeAt(0), p = parser.p;\n if (clarinet.DEBUG) console.log('write -> [' + chunk + ']');\n while (c) {\n p = c;\n parser.c = c = chunk.charCodeAt(i++);\n // if chunk doesnt have next, like streaming char by char\n // this way we need to check if previous is really previous\n // if not we need to reset to what the parser says is the previous\n // from buffer\n if(p !== c ) parser.p = p;\n else p = parser.p;\n\n if(!c) break;\n\n if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]);\n parser.position ++;\n if (c === Char.lineFeed) {\n parser.line ++;\n parser.column = 0;\n } else parser.column ++;\n switch (parser.state) {\n\n case S.BEGIN:\n if (c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if (!isWhitespace(c))\n error(parser, \"Non-whitespace before {[.\");\n continue;\n\n case S.OPEN_KEY:\n case S.OPEN_OBJECT:\n if (isWhitespace(c)) continue;\n if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY);\n else {\n if(c === Char.closeBrace) {\n emit(parser, 'onopenobject');\n this.depth++;\n emit(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else parser.stack.push(S.CLOSE_OBJECT);\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else error(parser, \"Malformed object key should start with \\\"\");\n continue;\n\n case S.CLOSE_KEY:\n case S.CLOSE_OBJECT:\n if (isWhitespace(c)) continue;\n var event = (parser.state === S.CLOSE_KEY) ? 'key' : 'object';\n if(c === Char.colon) {\n if(parser.state === S.CLOSE_OBJECT) {\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser, 'onopenobject');\n this.depth++;\n } else closeValue(parser, 'onkey');\n parser.state = S.VALUE;\n } else if (c === Char.closeBrace) {\n emitNode(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if(c === Char.comma) {\n if(parser.state === S.CLOSE_OBJECT)\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser);\n parser.state = S.OPEN_KEY;\n } else error(parser, 'Bad object');\n continue;\n\n case S.OPEN_ARRAY: // after an array there always a value\n case S.VALUE:\n if (isWhitespace(c)) continue;\n if(parser.state===S.OPEN_ARRAY) {\n emit(parser, 'onopenarray');\n this.depth++;\n parser.state = S.VALUE;\n if(c === Char.closeBracket) {\n emit(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else {\n parser.stack.push(S.CLOSE_ARRAY);\n }\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if(c === Char.t) parser.state = S.TRUE;\n else if(c === Char.f) parser.state = S.FALSE;\n else if(c === Char.n) parser.state = S.NULL;\n else if(c === Char.minus) { // keep and continue\n parser.numberNode += \"-\";\n } else if(Char._0 <= c && c <= Char._9) {\n parser.numberNode += String.fromCharCode(c);\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, \"Bad value\");\n continue;\n\n case S.CLOSE_ARRAY:\n if(c === Char.comma) {\n parser.stack.push(S.CLOSE_ARRAY);\n closeValue(parser, 'onvalue');\n parser.state = S.VALUE;\n } else if (c === Char.closeBracket) {\n emitNode(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if (isWhitespace(c))\n continue;\n else error(parser, 'Bad array');\n continue;\n\n case S.STRING:\n if (parser.textNode === undefined) {\n parser.textNode = \"\";\n }\n\n // thanks thejh, this is an about 50% performance improvement.\n var starti = i-1\n , slashed = parser.slashed\n , unicodeI = parser.unicodeI\n ;\n STRING_BIGLOOP: while (true) {\n if (clarinet.DEBUG)\n console.log(i,c,clarinet.STATE[parser.state]\n ,slashed);\n // zero means \"no unicode active\". 1-4 mean \"parse some more\". end after 4.\n while (unicodeI > 0) {\n parser.unicodeS += String.fromCharCode(c);\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (unicodeI === 4) {\n // TODO this might be slow? well, probably not used too often anyway\n parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16));\n unicodeI = 0;\n starti = i-1;\n } else {\n unicodeI++;\n }\n // we can just break here: no stuff we skipped that still has to be sliced out or so\n if (!c) break STRING_BIGLOOP;\n }\n if (c === Char.doubleQuote && !slashed) {\n parser.state = parser.stack.pop() || S.VALUE;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n if (c === Char.backslash && !slashed) {\n slashed = true;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (!c) break;\n }\n if (slashed) {\n slashed = false;\n if (c === Char.n) { parser.textNode += '\\n'; }\n else if (c === Char.r) { parser.textNode += '\\r'; }\n else if (c === Char.t) { parser.textNode += '\\t'; }\n else if (c === Char.f) { parser.textNode += '\\f'; }\n else if (c === Char.b) { parser.textNode += '\\b'; }\n else if (c === Char.u) {\n // \\uxxxx. meh!\n unicodeI = 1;\n parser.unicodeS = '';\n } else {\n parser.textNode += String.fromCharCode(c);\n }\n c = chunk.charCodeAt(i++);\n parser.position++;\n starti = i-1;\n if (!c) break;\n else continue;\n }\n\n stringTokenPattern.lastIndex = i;\n var reResult = stringTokenPattern.exec(chunk);\n if (reResult === null) {\n i = chunk.length+1;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n i = reResult.index+1;\n c = chunk.charCodeAt(reResult.index);\n if (!c) {\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n }\n parser.slashed = slashed;\n parser.unicodeI = unicodeI;\n continue;\n\n case S.TRUE:\n if (c === Char.r) parser.state = S.TRUE2;\n else error(parser, 'Invalid true started with t'+ c);\n continue;\n\n case S.TRUE2:\n if (c === Char.u) parser.state = S.TRUE3;\n else error(parser, 'Invalid true started with tr'+ c);\n continue;\n\n case S.TRUE3:\n if(c === Char.e) {\n emit(parser, \"onvalue\", true);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid true started with tru'+ c);\n continue;\n\n case S.FALSE:\n if (c === Char.a) parser.state = S.FALSE2;\n else error(parser, 'Invalid false started with f'+ c);\n continue;\n\n case S.FALSE2:\n if (c === Char.l) parser.state = S.FALSE3;\n else error(parser, 'Invalid false started with fa'+ c);\n continue;\n\n case S.FALSE3:\n if (c === Char.s) parser.state = S.FALSE4;\n else error(parser, 'Invalid false started with fal'+ c);\n continue;\n\n case S.FALSE4:\n if (c === Char.e) {\n emit(parser, \"onvalue\", false);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid false started with fals'+ c);\n continue;\n\n case S.NULL:\n if (c === Char.u) parser.state = S.NULL2;\n else error(parser, 'Invalid null started with n'+ c);\n continue;\n\n case S.NULL2:\n if (c === Char.l) parser.state = S.NULL3;\n else error(parser, 'Invalid null started with nu'+ c);\n continue;\n\n case S.NULL3:\n if(c === Char.l) {\n emit(parser, \"onvalue\", null);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid null started with nul'+ c);\n continue;\n\n case S.NUMBER_DECIMAL_POINT:\n if(c === Char.period) {\n parser.numberNode += \".\";\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, 'Leading zero not followed by .');\n continue;\n\n case S.NUMBER_DIGIT:\n if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c);\n else if (c === Char.period) {\n if(parser.numberNode.indexOf('.')!==-1)\n error(parser, 'Invalid number has two dots');\n parser.numberNode += \".\";\n } else if (c === Char.e || c === Char.E) {\n if(parser.numberNode.indexOf('e')!==-1 ||\n parser.numberNode.indexOf('E')!==-1 )\n error(parser, 'Invalid number has two exponential');\n parser.numberNode += \"e\";\n } else if (c === Char.plus || c === Char.minus) {\n if(!(p === Char.e || p === Char.E))\n error(parser, 'Invalid symbol in number');\n parser.numberNode += String.fromCharCode(c);\n } else {\n closeNumber(parser);\n i--; // go back one\n parser.state = parser.stack.pop() || S.VALUE;\n }\n continue;\n\n default:\n error(parser, \"Unknown state: \" + parser.state);\n }\n }\n if (parser.position >= parser.bufferCheckPosition)\n checkBufferLength(parser);\n return parser;\n }\n\n})(typeof exports === \"undefined\" ? clarinet = {} : exports);\n","import clarinet from 'clarinet';\nimport { readBlobAsync, readBlobSync } from './helpers';\n\nexport interface JsonStream {\n pullAsync(numBytes: number): Promise>;\n pullSync(numBytes: number): Partial;\n done(): boolean;\n eof(): boolean;\n result: Partial;\n}\n\nexport function JsonStream(blob: Blob): JsonStream {\n let pos = 0;\n const parser = JsonParser(true);\n\n const rv = {\n async pullAsync(numBytes: number): Promise> {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = await readBlobAsync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n pullSync(numBytes: number): Partial {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = readBlobSync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n done() {\n return parser.done();\n },\n eof() {\n return pos >= blob.size;\n },\n result: {}\n }\n\n return rv;\n}\n\n\nexport function JsonParser (allowPartial: boolean) {\n const parser = (clarinet as any).parser();\n let level = 0;\n let result: any;\n const stack: any[][] = [];\n let obj: any;\n let key: string | null;\n let done = false;\n let array = false;\n\n parser.onopenobject = newKey => {\n const newObj = {};\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n key = newKey;\n array = false;\n ++level;\n }\n parser.onkey = newKey => key = newKey;\n parser.onvalue = value => array ? obj.push(value) : obj[key!] = value;\n parser.oncloseobject = ()=>{\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n parser.onopenarray = () => {\n const newObj = [];\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n array = true;\n key = null;\n ++level;\n }\n parser.onclosearray = () => {\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n\n return {\n write(jsonPart: string) {\n parser.write(jsonPart);\n return result;\n },\n done() {\n return done;\n }\n }\n}\n","import Dexie from 'dexie';\nimport { extractDbSchema } from './helpers';\nimport { DexieExportJsonStructure, VERSION } from './json-structure';\nimport { TSON } from './tson';\nimport { JsonStream } from './json-stream';\n\nexport interface StaticImportOptions {\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nexport interface ImportOptions extends StaticImportOptions {\n acceptMissingTables?: boolean;\n acceptVersionDiff?: boolean;\n acceptNameDiff?: boolean;\n acceptChangedPrimaryKey?: boolean;\n overwriteValues?: boolean;\n clearTablesBeforeImport?: boolean;\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nconst DEFAULT_KILOBYTES_PER_CHUNK = 1024;\n\nexport interface ImportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nexport async function importDB(exportedData: Blob | JsonStream, options?: StaticImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const stream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n const dbExport = stream.result.data!;\n const db = new Dexie(dbExport.databaseName);\n db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport));\n await importInto(db, stream, options);\n return db;\n}\n\nexport async function importInto(db: Dexie, exportedData: Blob | JsonStream, options?: ImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const jsonStream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n let dbExportFile = jsonStream.result;\n const readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\n const dbExport = dbExportFile.data!;\n\n if (!options!.acceptNameDiff && db.name !== dbExport.databaseName)\n throw new Error(`Name differs. Current database name is ${db.name} but export is ${dbExport.databaseName}`);\n if (!options!.acceptVersionDiff && db.verno !== dbExport.databaseVersion) {\n // Possible feature: Call upgraders in some isolated way if this happens... ?\n throw new Error(`Database version differs. Current database is in version ${db.verno} but export is ${dbExport.databaseVersion}`);\n }\n \n const { progressCallback } = options;\n const progress: ImportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: dbExport.tables.reduce((p, c) => p + c.rowCount, 0),\n totalTables: dbExport.tables.length\n };\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n\n if (options.noTransaction) {\n await importAll();\n } else {\n await db.transaction('rw', db.tables, importAll);\n } \n\n async function importAll () {\n do {\n for (const tableExport of dbExport.data) {\n if (!tableExport.rows) break; // Need to pull more!\n if (!(tableExport.rows as any).incomplete && tableExport.rows.length === 0)\n continue;\n\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const tableName = tableExport.tableName;\n const table = db.table(tableName);\n const tableSchemaStr = dbExport.tables.filter(t => t.name === tableName)[0].schema;\n if (!table) {\n if (!options!.acceptMissingTables)\n throw new Error(`Exported table ${tableExport.tableName} is missing in installed database`);\n else\n continue;\n }\n if (!options!.acceptChangedPrimaryKey &&\n tableSchemaStr.split(',')[0] != table.schema.primKey.src) {\n throw new Error(`Primary key differs for table ${tableExport.tableName}. `);\n }\n\n const sourceRows = tableExport.rows\n \n // Our rows may be partial, so we need to ensure each one is completed before using it\n const rows: any[] = [];\n for(let i = 0; i < sourceRows.length; i++) {\n const obj = sourceRows[i];\n if (!obj.incomplete) {\n rows.push(TSON.revive(obj));\n } else {\n break;\n }\n }\n\n const filter = options!.filter;\n const filteredRows = filter ?\n tableExport.inbound ?\n rows.filter(value => filter(tableName, value)) :\n rows.filter(([key, value]) => filter(tableName, value, key)) :\n rows;\n const [keys, values] = tableExport.inbound ?\n [undefined, filteredRows] :\n [filteredRows.map(row=>row[0]), rows.map(row=>row[1])];\n\n if (options!.clearTablesBeforeImport) {\n await table.clear();\n }\n if (options!.overwriteValues)\n await table.bulkPut(values, keys);\n else\n await table.bulkAdd(values, keys);\n \n progress.completedRows += rows.length;\n if (!(rows as any).incomplete) {\n progress.completedTables += 1;\n }\n sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance.\n }\n\n // Avoid unnescessary loops in \"for (const tableExport of dbExport.data)\" \n while (dbExport.data.length > 0 && dbExport.data[0].rows && !(dbExport.data[0].rows as any).incomplete) {\n // We've already imported all rows from the first table. Delete its occurrence\n dbExport.data.splice(0, 1); \n }\n if (!jsonStream.done() && !jsonStream.eof()) {\n // Pull some more (keeping transaction alive)\n if (readBlobsSynchronously) {\n // If we can pull from blob synchronically, we don't have to\n // keep transaction alive using Dexie.waitFor().\n // This will only be possible in workers.\n jsonStream.pullSync(CHUNK_SIZE);\n } else {\n await Dexie.waitFor(jsonStream.pullAsync(CHUNK_SIZE));\n }\n } else break;\n } while (true)\n }\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n}\n\nasync function loadUntilWeGotEnoughData(exportedData: Blob | JsonStream, CHUNK_SIZE: number): Promise> {\n const stream = ('slice' in exportedData ?\n JsonStream(exportedData) :\n exportedData);\n\n while (!stream.eof()) {\n await stream.pullAsync(CHUNK_SIZE);\n\n if (stream.result.data && stream.result.data!.data)\n break;\n }\n const dbExportFile = stream.result;\n if (!dbExportFile || dbExportFile.formatName != \"dexie\")\n throw new Error(`Given file is not a dexie export`);\n if (dbExportFile.formatVersion! > VERSION) {\n throw new Error(`Format version ${dbExportFile.formatVersion} not supported`);\n }\n if (!dbExportFile.data!) {\n throw new Error(`No data in export file`);\n }\n if (!dbExportFile.data!.databaseName) {\n throw new Error(`Missing databaseName in export file`);\n }\n if (!dbExportFile.data!.databaseVersion) {\n throw new Error(`Missing databaseVersion in export file`);\n }\n if (!dbExportFile.data!.tables) {\n throw new Error(`Missing tables in export file`);\n }\n return stream; \n}\n","import Dexie from 'dexie';\nimport { ExportOptions, exportDB } from './export';\nimport { importDB, ImportOptions, importInto, StaticImportOptions } from './import';\n\nexport { exportDB, ExportOptions};\nexport { importDB, importInto, ImportOptions};\n\n//\n// Extend Dexie interface (typescript-wise)\n//\ndeclare module 'dexie' {\n // Extend methods on db\n interface Dexie {\n export(options?: ExportOptions): Promise;\n import(blob: Blob, options?: ImportOptions): Promise;\n }\n interface DexieConstructor {\n import(blob: Blob, options?: StaticImportOptions): Promise;\n }\n}\n\n//\n// Extend Dexie interface (runtime wise)\n//\n\nDexie.prototype.export = function (this: Dexie, options?: ExportOptions) {\n return exportDB(this, options);\n};\nDexie.prototype.import = function (this: Dexie, blob: Blob, options?: ImportOptions) {\n return importInto(this, blob, options);\n};\nDexie.import = (blob: Blob, options?: StaticImportOptions) => importDB(blob, options);\n\nexport default ()=>{\n throw new Error(\"This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options.\")\n};\n"],"names":["this","keys","Object","isArray","Array","toString","getProto","getPrototypeOf","hasOwn","hasOwnProperty","fnToString","internalStateObjPropsToIgnore","isThenable","v","catchCheck","Typeson","isObject","then","catch","toStringTag","val","call","slice","hasConstructorOf","a","b","proto","Ctor","constructor","isPlainObject","options","plainObjectReplacers","nonplainObjectReplacers","revivers","regTypes","types","stringify","obj","replacer","space","opts","assign","stringification","encapsulated","encapsulate","JSON","res","stringifySync","throwOnBadSyncType","sync","stringifyAsync","parse","text","reviver","revive","parseSync","parseAsync","specialTypeNames","stateObj","returnTypeNames","rootTypeName","iterateNone","refObjs","cyclic","encapsulateObserver","ret","_encapsulate","promisesDataRoot","finish","typeNames","values","length","getJSONType","Set","$types","$","TypeError","Promise","resolve","checkPromises","promisesData","all","map","pd","p","promResults","promResult","newPromisesData","prData","splice","keyPath","parentObj","key","detectedType","encaps","isTypesonPromise","TypesonPromise","encaps2","_adaptBuiltinStateObjectProperties","ownKeysObj","cb","vals","prop","tmp","forEach","i","keypath","value","resolvingTypesonPromise","observerData","$typeof","runObserver","type","undefined","string","boolean","number","isNaN","Infinity","replace","replaced","iterateIn","iterateUnsetNumeric","refIndex","indexOf","refKeys","push","isPlainObj","isArr","clone","ownKeys","kp","escapeKeyPathComponent","endIterateIn","end","endIterateOwn","vl","endIterateUnsetNumeric","plainObject","replacers","test","existing","concat","replaceAsync","replacing","typeDetected","encapsulateSync","encapsulateAsync","ignore$Types","keyPathResolutions","_revive","target","Undefined","getByKeyPath","substr","reduce","Error","reviveAsync","reviveSync","register","typeSpecSets","R","typeSpec","typeId","JSON_TYPES","includes","spec","testPlainObjects","existingReplacer","filter","r","Class","x","create","prototype","replacerObj","bind","start","fallback","reviverObj","t","s","k","keyPathComponent","unescapeKeyPathComponent","period","innerObj","f","onFulfilled","onRejected","typesonResolve","typesonReject","reject","meth","promArr","prom","isUserObject","n","String","Boolean","Number","NaN","date","time","getTime","Date","rexp","source","global","ignoreCase","multiline","sticky","unicode","flags","RegExp","from","entries","Map","set","chars","lookup","Uint8Array","charCodeAt","encode","arraybuffer","byteOffset","bytes","len","base64","substring","decode","bufferLength","encoded1","encoded2","encoded3","encoded4","ArrayBuffer","buffers","index","b64","buffer","_global","self","exportObj","typeName","arrType","TypedArray","toLowerCase","b64Obj","encoded","byteLength","DataView","Intl","Collator","c","resolvedOptions","locale","DateTimeFormat","dtf","NumberFormat","nf","string2arraybuffer","str","array","Uint16Array","req","XMLHttpRequest","open","URL","createObjectURL","TextEncoder","overrideMimeType","status","send","responseText","name","lastModified","stringContents","File","isClosed","reader","FileReader","addEventListener","result","error","readAsText","userObject","presetUndefined","primitiveObjects","specialNumbers","regexp","d","data","width","height","o","ImageData","Uint8ClampedArray","dataset","bm","canvas","document","createElement","getContext","drawImage","toDataURL","ctx","img","onload","src","createImageBitmap","file","fl","arr","item","FileList","_files","arguments","Symbol","Blob","typedArrays","dataview","intlTypes","StructuredCloning","typedArray","encodeB64","decodeB64","require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,CAAC,IAAK,CAAC,eAAe,EAAE;4BACvC,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;yBAC3D;wBACD,IAAI,CAAC,YAAY,CAAC,IAAK,CAAC,MAAM,EAAE;4BAC9B,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;yBAClD;wBACD,sBAAO,MAAM,EAAC;;;;KACf;;ICnLD;IACA;IACA;IAEA,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,OAAuB;QACrE,OAAO,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACjC,CAAC,CAAC;IACF,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,IAAU,EAAE,OAAuB;QACjF,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IACzC,CAAC,CAAC;IACF,KAAK,CAAC,MAAM,GAAG,UAAC,IAAU,EAAE,OAA6B,IAAK,OAAA,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,GAAA,CAAC;AAEtF,6BAAe;QACb,MAAM,IAAI,KAAK,CAAC,kHAAkH,CAAC,CAAA;IACrI,CAAC,EAAC;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/addons/dexie-export-import/dist/dexie-export-import.mjs b/addons/dexie-export-import/dist/dexie-export-import.mjs new file mode 100644 index 000000000..d4cbdbba2 --- /dev/null +++ b/addons/dexie-export-import/dist/dexie-export-import.mjs @@ -0,0 +1,1646 @@ +/* ========================================================================== + * dexie-export-import.js + * ========================================================================== + * + * Dexie addon for exporting and importing databases to / from Blobs. + * + * By David Fahlander, david.fahlander@gmail.com, + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function getSchemaString(table) { + var primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes); + return primKeyAndIndexes.map(function (index) { return index.src; }).join(','); +} +function extractDbSchema(exportedDb) { + var schema = {}; + for (var _i = 0, _a = exportedDb.tables; _i < _a.length; _i++) { + var table = _a[_i]; + schema[table.name] = table.schema; + } + return schema; +} +function readBlobAsync(blob, type) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onabort = function (ev) { return reject(new Error("file read aborted")); }; + reader.onerror = function (ev) { return reject(ev.target.error); }; + reader.onload = function (ev) { return resolve(ev.target.result); }; + if (type === 'binary') + reader.readAsArrayBuffer(blob); + else + reader.readAsText(blob); + }); +} +function readBlobSync(blob, type) { + if (typeof FileReaderSync === 'undefined') { + throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.'); + } + var reader = new FileReaderSync(); // Requires worker environment + var data = type === 'binary' ? + reader.readAsArrayBuffer(blob) : + reader.readAsText(blob); + return data; +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var typeson = createCommonjsModule(function (module, exports) { +!function(e,n){module.exports=n();}(commonjsGlobal,function(){var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=function(){return function(e,n){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function sliceIterator(e,n){var t=[],r=!0,i=!1,o=void 0;try{for(var s,c=e[Symbol.iterator]();!(r=(s=c.next()).done)&&(t.push(s.value),!n||t.length!==n);r=!0);}catch(e){i=!0,o=e;}finally{try{!r&&c.return&&c.return();}finally{if(i)throw o}}return t}(e,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),t=function(e){if(Array.isArray(e)){for(var n=0,t=Array(e.length);n2&&void 0!==arguments[2]?arguments[2]:{};return t.returnTypeNames=!0,this.encapsulate(e,n,t)},this.rootTypeName=function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.iterateNone=!0,this.encapsulate(e,n,t)};var l=this.encapsulate=function(y,p,f){var l=(f=Object.assign({sync:!0},o,f)).sync,h={},v=[],d=[],b=[],O=!(f&&"cyclic"in f)||f.cyclic,m=f.encapsulateObserver,T=_encapsulate("",y,O,p||{},b);function finish(e){var n=Object.values(h);if(f.iterateNone)return n.length?n[0]:Typeson.getJSONType(e);if(n.length){if(f.returnTypeNames)return [].concat(t(new Set(n)));e&&isPlainObject(e)&&!e.hasOwnProperty("$types")?e.$types=h:e={$:e,$types:{$:h}};}else isObject(e)&&e.hasOwnProperty("$types")&&(e={$:e,$types:!0});return !f.returnTypeNames&&e}return b.length?l&&f.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(e,t){return Promise.all(t.map(function(e){return e[1].p})).then(function(r){return Promise.all(r.map(function(r){var i=[],o=t.splice(0,1)[0],s=n(o,7),c=s[0],a=s[2],u=s[3],y=s[4],p=s[5],f=s[6],l=_encapsulate(c,r,a,u,i,!0,f),h=hasConstructorOf(l,TypesonPromise);return c&&h?l.p.then(function(n){return y[p]=n,checkPromises(e,i)}):(c?y[p]=l:e=h?l.p:l,checkPromises(e,i))}))}).then(function(){return e})}(T,b)).then(finish):!l&&f.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():f.stringification&&l?[finish(T)]:l?finish(T):Promise.resolve(finish(T));function _adaptBuiltinStateObjectProperties(e,n,t){Object.assign(e,n);var r=u.map(function(n){var t=e[n];return delete e[n],t});t(),u.forEach(function(n,t){e[n]=r[t];});}function _encapsulate(n,t,o,c,a,u,y){var p=void 0,l={},b=void 0===t?"undefined":e(t),O=m?function(e){var r=y||c.type||Typeson.getJSONType(t);m(Object.assign(e||l,{keypath:n,value:t,cyclic:o,stateObj:c,promisesData:a,resolvingTypesonPromise:u,awaitingTypesonPromise:hasConstructorOf(t,TypesonPromise)},void 0!==r?{type:r}:{}));}:null;if(b in{string:1,boolean:1,number:1,undefined:1})return void 0===t||"number"===b&&(isNaN(t)||t===-1/0||t===1/0)?(p=replace(n,t,c,a,!1,u,O))!==t&&(l={replaced:p}):p=t,O&&O(),p;if(null===t)return O&&O(),t;if(o&&!c.iterateIn&&!c.iterateUnsetNumeric){var T=v.indexOf(t);if(!(T<0))return h[n]="#",O&&O({cyclicKeypath:d[T]}),"#"+d[T];!0===o&&(v.push(t),d.push(n));}var g=isPlainObject(t),P=i(t),j=(g||P)&&(!s.length||c.replaced)||c.iterateIn?t:replace(n,t,c,a,g||P,null,O),S=void 0;if(j!==t?(p=j,l={replaced:j}):P||"array"===c.iterateIn?(S=new Array(t.length),l={clone:S}):g||"object"===c.iterateIn?l={clone:S={}}:""===n&&hasConstructorOf(t,TypesonPromise)?(a.push([n,t,o,c,void 0,void 0,c.type]),p=t):p=t,O&&O(),f.iterateNone)return S||p;if(!S)return p;if(c.iterateIn){var w=function _loop(e){var r={ownKeys:t.hasOwnProperty(e)};_adaptBuiltinStateObjectProperties(c,r,function(){var r=n+(n?".":"")+escapeKeyPathComponent(e),i=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(i,TypesonPromise)?a.push([r,i,!!o,c,S,e,c.type]):void 0!==i&&(S[e]=i);});};for(var A in t)w(A);O&&O({endIterateIn:!0,end:!0});}else r(t).forEach(function(e){var r=n+(n?".":"")+escapeKeyPathComponent(e);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},function(){var n=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n);});}),O&&O({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var C=t.length,N=function _loop2(e){if(!(e in t)){var r=n+(n?".":"")+e;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},function(){var n=_encapsulate(r,void 0,!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n);});}},B=0;B-1){var r=e[unescapeKeyPathComponent(n.substr(0,t))];return void 0===r?void 0:getByKeyPath(r,n.substr(t+1))}return e[unescapeKeyPathComponent(n)]}function Undefined(){}function TypesonPromise(e){this.p=new Promise(e);}return TypesonPromise.prototype.then=function(e,n){var t=this;return new TypesonPromise(function(r,i){t.p.then(function(n){r(e?e(n):n);},function(e){t.p.catch(function(e){return n?n(e):Promise.reject(e)}).then(r,i);});})},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise(function(n){n(e);})},TypesonPromise.reject=function(e){return new TypesonPromise(function(n,t){t(e);})},["all","race"].map(function(e){TypesonPromise[e]=function(n){return new TypesonPromise(function(t,r){Promise[e](n.map(function(e){return e.p})).then(t,r);})};}),Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return !1;var n=s(e);return !n||hasConstructorOf(e,Object)||isUserObject(n)},Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=function(n){return null===n?"null":i(n)?"array":void 0===n?"undefined":e(n)},Typeson.JSON_TYPES=["null","boolean","number","string","array","object"],Typeson}); +}); + +var structuredCloning = createCommonjsModule(function (module, exports) { +!function(e,t){module.exports=t();}(commonjsGlobal,function(){var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function sliceIterator(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(r=(s=a.next()).done)&&(n.push(s.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e;}finally{try{!r&&a.return&&a.return();}finally{if(i)throw o}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),n=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)},this.rootTypeName=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)};var y=this.encapsulate=function(f,p,l){var y=(l=Object.assign({sync:!0},o,l)).sync,v={},d=[],h=[],g=[],b=!(l&&"cyclic"in l)||l.cyclic,m=l.encapsulateObserver,T=_encapsulate("",f,b,p||{},g);function finish(e){var t=Object.values(v);if(l.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(l.returnTypeNames)return [].concat(n(new Set(t)));e&&isPlainObject(e)&&!e.hasOwnProperty("$types")?e.$types=v:e={$:e,$types:{$:v}};}else isObject(e)&&e.hasOwnProperty("$types")&&(e={$:e,$types:!0});return !l.returnTypeNames&&e}return g.length?y&&l.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(e,n){return Promise.all(n.map(function(e){return e[1].p})).then(function(r){return Promise.all(r.map(function(r){var i=[],o=n.splice(0,1)[0],s=t(o,7),a=s[0],c=s[2],u=s[3],f=s[4],p=s[5],l=s[6],y=_encapsulate(a,r,c,u,i,!0,l),v=hasConstructorOf(y,TypesonPromise);return a&&v?y.p.then(function(t){return f[p]=t,checkPromises(e,i)}):(a?f[p]=y:e=v?y.p:y,checkPromises(e,i))}))}).then(function(){return e})}(T,g)).then(finish):!y&&l.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():l.stringification&&y?[finish(T)]:y?finish(T):Promise.resolve(finish(T));function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=u.map(function(t){var n=e[t];return delete e[t],n});n(),u.forEach(function(t,n){e[t]=r[n];});}function _encapsulate(t,n,o,a,c,u,f){var p=void 0,y={},g=void 0===n?"undefined":e(n),b=m?function(e){var r=f||a.type||Typeson.getJSONType(n);m(Object.assign(e||y,{keypath:t,value:n,cyclic:o,stateObj:a,promisesData:c,resolvingTypesonPromise:u,awaitingTypesonPromise:hasConstructorOf(n,TypesonPromise)},void 0!==r?{type:r}:{}));}:null;if(g in{string:1,boolean:1,number:1,undefined:1})return void 0===n||"number"===g&&(isNaN(n)||n===-1/0||n===1/0)?(p=replace(t,n,a,c,!1,u,b))!==n&&(y={replaced:p}):p=n,b&&b(),p;if(null===n)return b&&b(),n;if(o&&!a.iterateIn&&!a.iterateUnsetNumeric){var T=d.indexOf(n);if(!(T<0))return v[t]="#",b&&b({cyclicKeypath:h[T]}),"#"+h[T];!0===o&&(d.push(n),h.push(t));}var O=isPlainObject(n),w=i(n),S=(O||w)&&(!s.length||a.replaced)||a.iterateIn?n:replace(t,n,a,c,O||w,null,b),P=void 0;if(S!==n?(p=S,y={replaced:S}):w||"array"===a.iterateIn?(P=new Array(n.length),y={clone:P}):O||"object"===a.iterateIn?y={clone:P={}}:""===t&&hasConstructorOf(n,TypesonPromise)?(c.push([t,n,o,a,void 0,void 0,a.type]),p=n):p=n,b&&b(),l.iterateNone)return P||p;if(!P)return p;if(a.iterateIn){var j=function _loop(e){var r={ownKeys:n.hasOwnProperty(e)};_adaptBuiltinStateObjectProperties(a,r,function(){var r=t+(t?".":"")+escapeKeyPathComponent(e),i=_encapsulate(r,n[e],!!o,a,c,u);hasConstructorOf(i,TypesonPromise)?c.push([r,i,!!o,a,P,e,a.type]):void 0!==i&&(P[e]=i);});};for(var A in n)j(A);b&&b({endIterateIn:!0,end:!0});}else r(n).forEach(function(e){var r=t+(t?".":"")+escapeKeyPathComponent(e);_adaptBuiltinStateObjectProperties(a,{ownKeys:!0},function(){var t=_encapsulate(r,n[e],!!o,a,c,u);hasConstructorOf(t,TypesonPromise)?c.push([r,t,!!o,a,P,e,a.type]):void 0!==t&&(P[e]=t);});}),b&&b({endIterateOwn:!0,end:!0});if(a.iterateUnsetNumeric){for(var C=n.length,N=function _loop2(e){if(!(e in n)){var r=t+(t?".":"")+e;_adaptBuiltinStateObjectProperties(a,{ownKeys:!1},function(){var t=_encapsulate(r,void 0,!!o,a,c,u);hasConstructorOf(t,TypesonPromise)?c.push([r,t,!!o,a,P,e,a.type]):void 0!==t&&(P[e]=t);});}},B=0;B-1){var r=e[unescapeKeyPathComponent(t.substr(0,n))];return void 0===r?void 0:getByKeyPath(r,t.substr(n+1))}return e[unescapeKeyPathComponent(t)]}function Undefined(){}function TypesonPromise(e){this.p=new Promise(e);}TypesonPromise.prototype.then=function(e,t){var n=this;return new TypesonPromise(function(r,i){n.p.then(function(t){r(e?e(t):t);},function(e){n.p.catch(function(e){return t?t(e):Promise.reject(e)}).then(r,i);});})},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise(function(t){t(e);})},TypesonPromise.reject=function(e){return new TypesonPromise(function(t,n){n(e);})},["all","race"].map(function(e){TypesonPromise[e]=function(t){return new TypesonPromise(function(n,r){Promise[e](t.map(function(e){return e.p})).then(n,r);})};}),Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return !1;var t=s(e);return !t||hasConstructorOf(e,Object)||isUserObject(t)},Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=function(t){return null===t?"null":i(t)?"array":void 0===t?"undefined":e(t)},Typeson.JSON_TYPES=["null","boolean","number","string","array","object"];for(var f={userObject:{test:function test(e,t){return Typeson.isUserObject(e)},replace:function replace(e){return Object.assign({},e)},revive:function revive(e){return e}}},p=[[{sparseArrays:{testPlainObjects:!0,test:function test(e){return Array.isArray(e)},replace:function replace(e,t){return t.iterateUnsetNumeric=!0,e}}},{sparseUndefined:{test:function test(e,t){return void 0===e&&!1===t.ownKeys},replace:function replace(e){return null},revive:function revive(e){}}}],{undef:{test:function test(e,t){return void 0===e&&(t.ownKeys||!("ownKeys"in t))},replace:function replace(e){return null},revive:function revive(e){return new Typeson.Undefined}}}],l={StringObject:{test:function test(t){return "String"===Typeson.toStringTag(t)&&"object"===(void 0===t?"undefined":e(t))},replace:function replace(e){return String(e)},revive:function revive(e){return new String(e)}},BooleanObject:{test:function test(t){return "Boolean"===Typeson.toStringTag(t)&&"object"===(void 0===t?"undefined":e(t))},replace:function replace(e){return Boolean(e)},revive:function revive(e){return new Boolean(e)}},NumberObject:{test:function test(t){return "Number"===Typeson.toStringTag(t)&&"object"===(void 0===t?"undefined":e(t))},replace:function replace(e){return Number(e)},revive:function revive(e){return new Number(e)}}},y=[{nan:{test:function test(e){return "number"==typeof e&&isNaN(e)},replace:function replace(e){return "NaN"},revive:function revive(e){return NaN}}},{infinity:{test:function test(e){return e===1/0},replace:function replace(e){return "Infinity"},revive:function revive(e){return 1/0}}},{negativeInfinity:{test:function test(e){return e===-1/0},replace:function replace(e){return "-Infinity"},revive:function revive(e){return -1/0}}}],v={date:{test:function test(e){return "Date"===Typeson.toStringTag(e)},replace:function replace(e){var t=e.getTime();return isNaN(t)?"NaN":t},revive:function revive(e){return "NaN"===e?new Date(NaN):new Date(e)}}},d={regexp:{test:function test(e){return "RegExp"===Typeson.toStringTag(e)},replace:function replace(e){return {source:e.source,flags:(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.sticky?"y":"")+(e.unicode?"u":"")}},revive:function revive(e){var t=e.source,n=e.flags;return new RegExp(t,n)}}},h={map:{test:function test(e){return "Map"===Typeson.toStringTag(e)},replace:function replace(e){return Array.from(e.entries())},revive:function revive(e){return new Map(e)}}},g={set:{test:function test(e){return "Set"===Typeson.toStringTag(e)},replace:function replace(e){return Array.from(e.values())},revive:function revive(e){return new Set(e)}}},b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",m=new Uint8Array(256),T=0;T>2],o+=b[(3&r[s])<<4|r[s+1]>>4],o+=b[(15&r[s+1])<<2|r[s+2]>>6],o+=b[63&r[s+2]];return i%3==2?o=o.substring(0,o.length-1)+"=":i%3==1&&(o=o.substring(0,o.length-2)+"=="),o},w=function decode(e){var t=e.length,n=.75*e.length,r=0,i=void 0,o=void 0,s=void 0,a=void 0;"="===e[e.length-1]&&(n--,"="===e[e.length-2]&&n--);for(var c=new ArrayBuffer(n),u=new Uint8Array(c),f=0;f>4,u[r++]=(15&o)<<4|s>>2,u[r++]=(3&s)<<6|63&a;return c},S={arraybuffer:{test:function test(e){return "ArrayBuffer"===Typeson.toStringTag(e)},replace:function replace(e,t){t.buffers||(t.buffers=[]);var n=t.buffers.indexOf(e);return n>-1?{index:n}:(t.buffers.push(e),O(e))},revive:function revive(t,n){if(n.buffers||(n.buffers=[]),"object"===(void 0===t?"undefined":e(t)))return n.buffers[t.index];var r=w(t);return n.buffers.push(r),r}}},P="undefined"==typeof self?commonjsGlobal:self,j={};["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"].forEach(function(e){var t=e,n=P[t];n&&(j[e.toLowerCase()]={test:function test(e){return Typeson.toStringTag(e)===t},replace:function replace(e,t){var n=e.buffer,r=e.byteOffset,i=e.length;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(n);return o>-1?{index:o,byteOffset:r,length:i}:(t.buffers.push(n),{encoded:O(n),byteOffset:r,length:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var r=e.byteOffset,i=e.length,o=e.encoded,s=e.index,a=void 0;return "index"in e?a=t.buffers[s]:(a=w(o),t.buffers.push(a)),new n(a,r,i)}});});var A={dataview:{test:function test(e){return "DataView"===Typeson.toStringTag(e)},replace:function replace(e,t){var n=e.buffer,r=e.byteOffset,i=e.byteLength;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(n);return o>-1?{index:o,byteOffset:r,byteLength:i}:(t.buffers.push(n),{encoded:O(n),byteOffset:r,byteLength:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var n=e.byteOffset,r=e.byteLength,i=e.encoded,o=e.index,s=void 0;return "index"in e?s=t.buffers[o]:(s=w(i),t.buffers.push(s)),new DataView(s,n,r)}}},C={IntlCollator:{test:function test(e){return Typeson.hasConstructorOf(e,Intl.Collator)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.Collator(e.locale,e)}},IntlDateTimeFormat:{test:function test(e){return Typeson.hasConstructorOf(e,Intl.DateTimeFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.DateTimeFormat(e.locale,e)}},IntlNumberFormat:{test:function test(e){return Typeson.hasConstructorOf(e,Intl.NumberFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.NumberFormat(e.locale,e)}}};function string2arraybuffer(e){for(var t=new Uint16Array(e.length),n=0;n> 2]; + base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4]; + base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6]; + base64 += chars[bytes[_i + 2] & 63]; + } + + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; + } else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + + return base64; +}; +var decode = function decode(base64) { + var len = base64.length; + var bufferLength = base64.length * 0.75; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (var _i2 = 0; _i2 < len; _i2 += 4) { + encoded1 = lookup[base64.charCodeAt(_i2)]; + encoded2 = lookup[base64.charCodeAt(_i2 + 1)]; + encoded3 = lookup[base64.charCodeAt(_i2 + 2)]; + encoded4 = lookup[base64.charCodeAt(_i2 + 3)]; + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + + return arraybuffer; +}; + +/* eslint-env browser, node */ +var _global = typeof self === 'undefined' ? global : self; +var exportObj = {}; +[ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array' +].forEach(function (typeName) { + var arrType = typeName; + var TypedArray = _global[arrType]; + if (TypedArray) { + exportObj[typeName.toLowerCase() + "2"] = { + test: function (x) { return typeson.toStringTag(x) === arrType; }, + replace: function (_a) { + var buffer = _a.buffer, byteOffset = _a.byteOffset, length = _a.length; + return { + buffer: buffer, + byteOffset: byteOffset, + length: length + }; + }, + revive: function (b64Obj) { + var buffer = b64Obj.buffer, byteOffset = b64Obj.byteOffset, length = b64Obj.length; + return new TypedArray(buffer, byteOffset, length); + } + }; + } +}); + +var arrayBuffer = { + arraybuffer: { + test: function (x) { return typeson.toStringTag(x) === 'ArrayBuffer'; }, + replace: function (b) { + return encode(b, 0, b.byteLength); + }, + revive: function (b64) { + var buffer = decode(b64); + return buffer; + } + } +}; +// See also typed-arrays! + +var TSON = new typeson().register(structuredCloning); +var readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only. +var blobsToAwait = []; +var blobsToAwaitPos = 0; +// Need to patch encapsulateAsync as it does not work as of typeson 5.8.2 +// Also, current version of typespn-registry-1.0.0-alpha.21 does not +// encapsulate/revive Blobs correctly (fails one of the unit tests in +// this library (test 'export-format')) +TSON.register([ + arrayBuffer, + exportObj, { + blob2: { + test: function (x) { return typeson.toStringTag(x) === 'Blob'; }, + replace: function (b) { + if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob + throw new Error('The Blob is closed'); + } + if (readBlobsSynchronously) { + var data = readBlobSync(b, 'binary'); + var base64 = encode(data, 0, data.byteLength); + return { + type: b.type, + data: base64 + }; + } + else { + blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true. + var result = { + type: b.type, + data: { start: blobsToAwaitPos, end: blobsToAwaitPos + b.size } + }; + console.log("b.size: " + b.size); + blobsToAwaitPos += b.size; + return result; + } + }, + finalize: function (b, ba) { + b.data = encode(ba, 0, ba.byteLength); + }, + revive: function (_a) { + var type = _a.type, data = _a.data; + return new Blob([decode(data)], { type: type }); + } + } + } +]); +TSON.mustFinalize = function () { return blobsToAwait.length > 0; }; +TSON.finalize = function (items) { return __awaiter(void 0, void 0, void 0, function () { + var allChunks, _i, items_1, item, types, arrayType, keyPath, typeName, typeSpec, b; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, readBlobAsync(new Blob(blobsToAwait), 'binary')]; + case 1: + allChunks = _a.sent(); + if (items) { + for (_i = 0, items_1 = items; _i < items_1.length; _i++) { + item = items_1[_i]; + // Manually go through all "blob" types in the result + // and lookup the data slice they point at. + if (item.$types) { + types = item.$types; + arrayType = types.$; + if (arrayType) + types = types.$; + for (keyPath in types) { + typeName = types[keyPath]; + typeSpec = TSON.types[typeName]; + if (typeSpec && typeSpec.finalize) { + b = Dexie.getByKeyPath(item, arrayType ? "$." + keyPath : keyPath); + typeSpec.finalize(b, allChunks.slice(b.start, b.end)); + } + } + } + } + } + // Free up memory + blobsToAwait = []; + return [2 /*return*/]; + } + }); +}); }; + +var DEFAULT_ROWS_PER_CHUNK = 2000; +function exportDB(db, options) { + return __awaiter(this, void 0, void 0, function () { + function exportAll() { + return __awaiter(this, void 0, void 0, function () { + var tablesRowCounts, emptyExportJson, posEndDataArray, firstJsonSlice, filter, _loop_1, _i, tables_1, tableName; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all(db.tables.map(function (table) { return table.count(); }))]; + case 1: + tablesRowCounts = _a.sent(); + tablesRowCounts.forEach(function (rowCount, i) { return tables[i].rowCount = rowCount; }); + progress.totalRows = tablesRowCounts.reduce(function (p, c) { return p + c; }); + emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined); + posEndDataArray = emptyExportJson.lastIndexOf(']'); + firstJsonSlice = emptyExportJson.substring(0, posEndDataArray); + slices.push(firstJsonSlice); + filter = options.filter; + _loop_1 = function (tableName) { + var table, primKey, inbound, LIMIT, emptyTableExport, emptyTableExportJson, posEndRowsArray, lastKey, lastNumRows, mayHaveMoreRows, _loop_2, state_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + table = db.table(tableName); + primKey = table.schema.primKey; + inbound = !!primKey.keyPath; + LIMIT = options.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK; + emptyTableExport = inbound ? { + tableName: table.name, + inbound: true, + rows: [] + } : { + tableName: table.name, + inbound: false, + rows: [] + }; + emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined); + if (prettyJson) { + // Increase indentation according to this: + // { + // ... + // data: [ + // ... + // data: [ + // 123456<---- here + // ] + // ] + // } + emptyTableExportJson = emptyTableExportJson.split('\n').join('\n '); + } + posEndRowsArray = emptyTableExportJson.lastIndexOf(']'); + slices.push(emptyTableExportJson.substring(0, posEndRowsArray)); + lastKey = null; + lastNumRows = 0; + mayHaveMoreRows = true; + _loop_2 = function () { + var chunkedCollection, values, filteredValues, tsonValues, json, keys, keyvals, tsonTuples, json; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + chunkedCollection = lastKey == null ? + table.limit(LIMIT) : + table.where(':id').above(lastKey).limit(LIMIT); + return [4 /*yield*/, chunkedCollection.toArray()]; + case 1: + values = _a.sent(); + if (values.length === 0) + return [2 /*return*/, "break"]; + if (lastKey != null && lastNumRows > 0) { + // Not initial chunk. Must add a comma: + slices.push(","); + if (prettyJson) { + slices.push("\n "); + } + } + mayHaveMoreRows = values.length === LIMIT; + if (!inbound) return [3 /*break*/, 4]; + filteredValues = filter ? + values.filter(function (value) { return filter(tableName, value); }) : + values; + tsonValues = filteredValues.map(function (value) { return TSON.encapsulate(value); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 3]; + return [4 /*yield*/, Dexie.waitFor(TSON.finalize(tsonValues))]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = filteredValues.length; + lastKey = values.length > 0 ? + Dexie.getByKeyPath(values[values.length - 1], primKey.keyPath) : + null; + return [3 /*break*/, 8]; + case 4: return [4 /*yield*/, chunkedCollection.primaryKeys()]; + case 5: + keys = _a.sent(); + keyvals = keys.map(function (key, i) { return [key, values[i]]; }); + if (filter) + keyvals = keyvals.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }); + tsonTuples = keyvals.map(function (tuple) { return TSON.encapsulate(tuple); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 7]; + return [4 /*yield*/, Dexie.waitFor(TSON.finalize(tsonTuples))]; + case 6: + _a.sent(); + _a.label = 7; + case 7: + json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = keyvals.length; + lastKey = keys.length > 0 ? + keys[keys.length - 1] : + null; + _a.label = 8; + case 8: + progress.completedRows += values.length; + return [2 /*return*/]; + } + }); + }; + _a.label = 1; + case 1: + if (!mayHaveMoreRows) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_2()]; + case 2: + state_1 = _a.sent(); + if (state_1 === "break") + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + slices.push(emptyTableExportJson.substr(posEndRowsArray)); // "]}" + progress.completedTables += 1; + if (progress.completedTables < progress.totalTables) { + slices.push(","); + } + return [2 /*return*/]; + } + }); + }; + _i = 0, tables_1 = tables; + _a.label = 2; + case 2: + if (!(_i < tables_1.length)) return [3 /*break*/, 5]; + tableName = tables_1[_i].name; + return [5 /*yield**/, _loop_1(tableName)]; + case 3: + _a.sent(); + _a.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + slices.push(emptyExportJson.substr(posEndDataArray)); + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); + } + var slices, tables, prettyJson, emptyExport, progressCallback, progress; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; + slices = []; + tables = db.tables.map(function (table) { return ({ + name: table.name, + schema: getSchemaString(table), + rowCount: 0 + }); }); + prettyJson = options.prettyJson; + emptyExport = { + formatName: "dexie", + formatVersion: 1, + data: { + databaseName: db.name, + databaseVersion: db.verno, + tables: tables, + data: [] + } + }; + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: NaN, + totalTables: db.tables.length + }; + _a.label = 1; + case 1: + _a.trys.push([1, , 6, 7]); + if (!options.noTransaction) return [3 /*break*/, 3]; + return [4 /*yield*/, exportAll()]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, db.transaction('r', db.tables, exportAll)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: return [3 /*break*/, 7]; + case 6: + TSON.finalize(); // Free up mem if error has occurred + return [7 /*endfinally*/]; + case 7: + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/, new Blob(slices, { type: "text/json" })]; + } + }); + }); +} + +var VERSION = 1; + +var fakeStream = {Stream: function(){}}; + +var clarinet_1 = createCommonjsModule(function (module, exports) { +(function (clarinet) { + + // non node-js needs to set clarinet debug on root + var env =(typeof process === 'object' && process.env) + ? process.env + : self; + + clarinet.parser = function (opt) { return new CParser(opt);}; + clarinet.CParser = CParser; + clarinet.CStream = CStream; + clarinet.createStream = createStream; + clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024; + clarinet.DEBUG = (env.CDEBUG==='debug'); + clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info'); + clarinet.EVENTS = + [ "value" + , "string" + , "key" + , "openobject" + , "closeobject" + , "openarray" + , "closearray" + , "error" + , "end" + , "ready" + ]; + + var buffers = { + textNode: undefined, + numberNode: "" + } + , streamWraps = clarinet.EVENTS.filter(function (ev) { + return ev !== "error" && ev !== "end"; + }) + , S = 0 + , Stream + ; + + clarinet.STATE = + { BEGIN : S++ + , VALUE : S++ // general stuff + , OPEN_OBJECT : S++ // { + , CLOSE_OBJECT : S++ // } + , OPEN_ARRAY : S++ // [ + , CLOSE_ARRAY : S++ // ] + , TEXT_ESCAPE : S++ // \ stuff + , STRING : S++ // "" + , BACKSLASH : S++ + , END : S++ // No more stack + , OPEN_KEY : S++ // , "a" + , CLOSE_KEY : S++ // : + , TRUE : S++ // r + , TRUE2 : S++ // u + , TRUE3 : S++ // e + , FALSE : S++ // a + , FALSE2 : S++ // l + , FALSE3 : S++ // s + , FALSE4 : S++ // e + , NULL : S++ // u + , NULL2 : S++ // l + , NULL3 : S++ // l + , NUMBER_DECIMAL_POINT : S++ // . + , NUMBER_DIGIT : S++ // [0-9] + }; + + for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_; + + // switcharoo + S = clarinet.STATE; + + const Char = { + tab : 0x09, // \t + lineFeed : 0x0A, // \n + carriageReturn : 0x0D, // \r + space : 0x20, // " " + + doubleQuote : 0x22, // " + plus : 0x2B, // + + comma : 0x2C, // , + minus : 0x2D, // - + period : 0x2E, // . + + _0 : 0x30, // 0 + _9 : 0x39, // 9 + + colon : 0x3A, // : + + E : 0x45, // E + + openBracket : 0x5B, // [ + backslash : 0x5C, // \ + closeBracket : 0x5D, // ] + + a : 0x61, // a + b : 0x62, // b + e : 0x65, // e + f : 0x66, // f + l : 0x6C, // l + n : 0x6E, // n + r : 0x72, // r + s : 0x73, // s + t : 0x74, // t + u : 0x75, // u + + openBrace : 0x7B, // { + closeBrace : 0x7D, // } + }; + + if (!Object.create) { + Object.create = function (o) { + function f () { this["__proto__"] = o; } + f.prototype = o; + return new f; + }; + } + + if (!Object.getPrototypeOf) { + Object.getPrototypeOf = function (o) { + return o["__proto__"]; + }; + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = []; + for (var i in o) if (o.hasOwnProperty(i)) a.push(i); + return a; + }; + } + + function checkBufferLength (parser) { + var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10) + , maxActual = 0 + ; + for (var buffer in buffers) { + var len = parser[buffer] === undefined ? 0 : parser[buffer].length; + if (len > maxAllowed) { + switch (buffer) { + case "text": + closeText(parser); + break; + + default: + error(parser, "Max buffer length exceeded: "+ buffer); + } + } + maxActual = Math.max(maxActual, len); + } + parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual) + + parser.position; + } + + function clearBuffers (parser) { + for (var buffer in buffers) { + parser[buffer] = buffers[buffer]; + } + } + + var stringTokenPattern = /[\\"\n]/g; + + function CParser (opt) { + if (!(this instanceof CParser)) return new CParser (opt); + + var parser = this; + clearBuffers(parser); + parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH; + parser.q = parser.c = parser.p = ""; + parser.opt = opt || {}; + parser.closed = parser.closedRoot = parser.sawRoot = false; + parser.tag = parser.error = null; + parser.state = S.BEGIN; + parser.stack = new Array(); + // mostly just for error reporting + parser.position = parser.column = 0; + parser.line = 1; + parser.slashed = false; + parser.unicodeI = 0; + parser.unicodeS = null; + parser.depth = 0; + emit(parser, "onready"); + } + + CParser.prototype = + { end : function () { end(this); } + , write : write + , resume : function () { this.error = null; return this; } + , close : function () { return this.write(null); } + }; + + try { Stream = fakeStream.Stream; } + catch (ex) { Stream = function () {}; } + + function createStream (opt) { return new CStream(opt); } + + function CStream (opt) { + if (!(this instanceof CStream)) return new CStream(opt); + + this._parser = new CParser(opt); + this.writable = true; + this.readable = true; + + //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error + this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary + this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read + this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached + this.string = ''; + + var me = this; + Stream.apply(me); + + this._parser.onend = function () { me.emit("end"); }; + this._parser.onerror = function (er) { + me.emit("error", er); + me._parser.error = null; + }; + + streamWraps.forEach(function (ev) { + Object.defineProperty(me, "on" + ev, + { get : function () { return me._parser["on" + ev]; } + , set : function (h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on"+ev] = h; + return h; + } + me.on(ev, h); + } + , enumerable : true + , configurable : false + }); + }); + } + + CStream.prototype = Object.create(Stream.prototype, + { constructor: { value: CStream } }); + + CStream.prototype.write = function (data) { + data = new Buffer(data); + for (var i = 0; i < data.length; i++) { + var n = data[i]; + + // check for carry over of a multi byte char split between data chunks + // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration + if (this.bytes_remaining > 0) { + for (var j = 0; j < this.bytes_remaining; j++) { + this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j]; + } + this.string = this.temp_buffs[this.bytes_in_sequence].toString(); + this.bytes_in_sequence = this.bytes_remaining = 0; + + // move iterator forward by number of byte read during sequencing + i = i + j - 1; + + // pass data to parser and move forward to parse rest of data + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + + // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time + if (this.bytes_remaining === 0 && n >= 128) { + if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; + if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; + if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; + if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split + + for (var k = 0; k <= (data.length - 1 - i); k++) { + this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk + } + this.bytes_remaining = (i + this.bytes_in_sequence) - data.length; + + // immediately return as we need another chunk to sequence the character + return true; + } else { + this.string = data.slice(i, (i + this.bytes_in_sequence)).toString(); + i = i + this.bytes_in_sequence - 1; + + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + } + + // is there a range of characters that are immediately parsable? + for (var p = i; p < data.length; p++) { + if (data[p] >= 128) break; + } + this.string = data.slice(i, p).toString(); + this._parser.write(this.string); + this.emit("data", this.string); + i = p - 1; + + // handle any remaining characters using multibyte logic + continue; + } + }; + + CStream.prototype.end = function (chunk) { + if (chunk && chunk.length) this._parser.write(chunk.toString()); + this._parser.end(); + return true; + }; + + CStream.prototype.on = function (ev, handler) { + var me = this; + if (!me._parser["on"+ev] && streamWraps.indexOf(ev) !== -1) { + me._parser["on"+ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] + : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + } + return Stream.prototype.on.call(me, ev, handler); + }; + + CStream.prototype.destroy = function () { + clearBuffers(this._parser); + this.emit("close"); + }; + + function emit(parser, event, data) { + if(clarinet.INFO) console.log('-- emit', event, data); + if (parser[event]) parser[event](data); + } + + function emitNode(parser, event, data) { + closeValue(parser); + emit(parser, event, data); + } + + function closeValue(parser, event) { + parser.textNode = textopts(parser.opt, parser.textNode); + if (parser.textNode !== undefined) { + emit(parser, (event ? event : "onvalue"), parser.textNode); + } + parser.textNode = undefined; + } + + function closeNumber(parser) { + if (parser.numberNode) + emit(parser, "onvalue", parseFloat(parser.numberNode)); + parser.numberNode = ""; + } + + function textopts (opt, text) { + if (text === undefined) { + return text; + } + if (opt.trim) text = text.trim(); + if (opt.normalize) text = text.replace(/\s+/g, " "); + return text; + } + + function error (parser, er) { + closeValue(parser); + er += "\nLine: "+parser.line+ + "\nColumn: "+parser.column+ + "\nChar: "+parser.c; + er = new Error(er); + parser.error = er; + emit(parser, "onerror", er); + return parser; + } + + function end(parser) { + if (parser.state !== S.VALUE || parser.depth !== 0) + error(parser, "Unexpected end"); + + closeValue(parser); + parser.c = ""; + parser.closed = true; + emit(parser, "onend"); + CParser.call(parser, parser.opt); + return parser; + } + + function isWhitespace(c) { + return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab; + } + + function write (chunk) { + var parser = this; + if (this.error) throw this.error; + if (parser.closed) return error(parser, + "Cannot write after close. Assign an onready handler."); + if (chunk === null) return end(parser); + var i = 0, c = chunk.charCodeAt(0), p = parser.p; + if (clarinet.DEBUG) console.log('write -> [' + chunk + ']'); + while (c) { + p = c; + parser.c = c = chunk.charCodeAt(i++); + // if chunk doesnt have next, like streaming char by char + // this way we need to check if previous is really previous + // if not we need to reset to what the parser says is the previous + // from buffer + if(p !== c ) parser.p = p; + else p = parser.p; + + if(!c) break; + + if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]); + parser.position ++; + if (c === Char.lineFeed) { + parser.line ++; + parser.column = 0; + } else parser.column ++; + switch (parser.state) { + + case S.BEGIN: + if (c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if (!isWhitespace(c)) + error(parser, "Non-whitespace before {[."); + continue; + + case S.OPEN_KEY: + case S.OPEN_OBJECT: + if (isWhitespace(c)) continue; + if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY); + else { + if(c === Char.closeBrace) { + emit(parser, 'onopenobject'); + this.depth++; + emit(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else parser.stack.push(S.CLOSE_OBJECT); + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else error(parser, "Malformed object key should start with \""); + continue; + + case S.CLOSE_KEY: + case S.CLOSE_OBJECT: + if (isWhitespace(c)) continue; + var event = (parser.state === S.CLOSE_KEY) ? 'key' : 'object'; + if(c === Char.colon) { + if(parser.state === S.CLOSE_OBJECT) { + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser, 'onopenobject'); + this.depth++; + } else closeValue(parser, 'onkey'); + parser.state = S.VALUE; + } else if (c === Char.closeBrace) { + emitNode(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if(c === Char.comma) { + if(parser.state === S.CLOSE_OBJECT) + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser); + parser.state = S.OPEN_KEY; + } else error(parser, 'Bad object'); + continue; + + case S.OPEN_ARRAY: // after an array there always a value + case S.VALUE: + if (isWhitespace(c)) continue; + if(parser.state===S.OPEN_ARRAY) { + emit(parser, 'onopenarray'); + this.depth++; + parser.state = S.VALUE; + if(c === Char.closeBracket) { + emit(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else { + parser.stack.push(S.CLOSE_ARRAY); + } + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if(c === Char.t) parser.state = S.TRUE; + else if(c === Char.f) parser.state = S.FALSE; + else if(c === Char.n) parser.state = S.NULL; + else if(c === Char.minus) { // keep and continue + parser.numberNode += "-"; + } else if(Char._0 <= c && c <= Char._9) { + parser.numberNode += String.fromCharCode(c); + parser.state = S.NUMBER_DIGIT; + } else error(parser, "Bad value"); + continue; + + case S.CLOSE_ARRAY: + if(c === Char.comma) { + parser.stack.push(S.CLOSE_ARRAY); + closeValue(parser, 'onvalue'); + parser.state = S.VALUE; + } else if (c === Char.closeBracket) { + emitNode(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if (isWhitespace(c)) + continue; + else error(parser, 'Bad array'); + continue; + + case S.STRING: + if (parser.textNode === undefined) { + parser.textNode = ""; + } + + // thanks thejh, this is an about 50% performance improvement. + var starti = i-1 + , slashed = parser.slashed + , unicodeI = parser.unicodeI + ; + STRING_BIGLOOP: while (true) { + if (clarinet.DEBUG) + console.log(i,c,clarinet.STATE[parser.state] + ,slashed); + // zero means "no unicode active". 1-4 mean "parse some more". end after 4. + while (unicodeI > 0) { + parser.unicodeS += String.fromCharCode(c); + c = chunk.charCodeAt(i++); + parser.position++; + if (unicodeI === 4) { + // TODO this might be slow? well, probably not used too often anyway + parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16)); + unicodeI = 0; + starti = i-1; + } else { + unicodeI++; + } + // we can just break here: no stuff we skipped that still has to be sliced out or so + if (!c) break STRING_BIGLOOP; + } + if (c === Char.doubleQuote && !slashed) { + parser.state = parser.stack.pop() || S.VALUE; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + if (c === Char.backslash && !slashed) { + slashed = true; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + c = chunk.charCodeAt(i++); + parser.position++; + if (!c) break; + } + if (slashed) { + slashed = false; + if (c === Char.n) { parser.textNode += '\n'; } + else if (c === Char.r) { parser.textNode += '\r'; } + else if (c === Char.t) { parser.textNode += '\t'; } + else if (c === Char.f) { parser.textNode += '\f'; } + else if (c === Char.b) { parser.textNode += '\b'; } + else if (c === Char.u) { + // \uxxxx. meh! + unicodeI = 1; + parser.unicodeS = ''; + } else { + parser.textNode += String.fromCharCode(c); + } + c = chunk.charCodeAt(i++); + parser.position++; + starti = i-1; + if (!c) break; + else continue; + } + + stringTokenPattern.lastIndex = i; + var reResult = stringTokenPattern.exec(chunk); + if (reResult === null) { + i = chunk.length+1; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + i = reResult.index+1; + c = chunk.charCodeAt(reResult.index); + if (!c) { + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + } + parser.slashed = slashed; + parser.unicodeI = unicodeI; + continue; + + case S.TRUE: + if (c === Char.r) parser.state = S.TRUE2; + else error(parser, 'Invalid true started with t'+ c); + continue; + + case S.TRUE2: + if (c === Char.u) parser.state = S.TRUE3; + else error(parser, 'Invalid true started with tr'+ c); + continue; + + case S.TRUE3: + if(c === Char.e) { + emit(parser, "onvalue", true); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid true started with tru'+ c); + continue; + + case S.FALSE: + if (c === Char.a) parser.state = S.FALSE2; + else error(parser, 'Invalid false started with f'+ c); + continue; + + case S.FALSE2: + if (c === Char.l) parser.state = S.FALSE3; + else error(parser, 'Invalid false started with fa'+ c); + continue; + + case S.FALSE3: + if (c === Char.s) parser.state = S.FALSE4; + else error(parser, 'Invalid false started with fal'+ c); + continue; + + case S.FALSE4: + if (c === Char.e) { + emit(parser, "onvalue", false); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid false started with fals'+ c); + continue; + + case S.NULL: + if (c === Char.u) parser.state = S.NULL2; + else error(parser, 'Invalid null started with n'+ c); + continue; + + case S.NULL2: + if (c === Char.l) parser.state = S.NULL3; + else error(parser, 'Invalid null started with nu'+ c); + continue; + + case S.NULL3: + if(c === Char.l) { + emit(parser, "onvalue", null); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid null started with nul'+ c); + continue; + + case S.NUMBER_DECIMAL_POINT: + if(c === Char.period) { + parser.numberNode += "."; + parser.state = S.NUMBER_DIGIT; + } else error(parser, 'Leading zero not followed by .'); + continue; + + case S.NUMBER_DIGIT: + if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c); + else if (c === Char.period) { + if(parser.numberNode.indexOf('.')!==-1) + error(parser, 'Invalid number has two dots'); + parser.numberNode += "."; + } else if (c === Char.e || c === Char.E) { + if(parser.numberNode.indexOf('e')!==-1 || + parser.numberNode.indexOf('E')!==-1 ) + error(parser, 'Invalid number has two exponential'); + parser.numberNode += "e"; + } else if (c === Char.plus || c === Char.minus) { + if(!(p === Char.e || p === Char.E)) + error(parser, 'Invalid symbol in number'); + parser.numberNode += String.fromCharCode(c); + } else { + closeNumber(parser); + i--; // go back one + parser.state = parser.stack.pop() || S.VALUE; + } + continue; + + default: + error(parser, "Unknown state: " + parser.state); + } + } + if (parser.position >= parser.bufferCheckPosition) + checkBufferLength(parser); + return parser; + } + +})(exports); +}); + +function JsonStream(blob) { + var pos = 0; + var parser = JsonParser(true); + var rv = { + pullAsync: function (numBytes) { + return __awaiter(this, void 0, void 0, function () { + var slize, jsonPart, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + return [4 /*yield*/, readBlobAsync(slize, 'text')]; + case 1: + jsonPart = _a.sent(); + result = parser.write(jsonPart); + rv.result = result || {}; + return [2 /*return*/, result]; + } + }); + }); + }, + pullSync: function (numBytes) { + var slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + var jsonPart = readBlobSync(slize, 'text'); + var result = parser.write(jsonPart); + rv.result = result || {}; + return result; + }, + done: function () { + return parser.done(); + }, + eof: function () { + return pos >= blob.size; + }, + result: {} + }; + return rv; +} +function JsonParser(allowPartial) { + var parser = clarinet_1.parser(); + var level = 0; + var result; + var stack = []; + var obj; + var key; + var done = false; + var array = false; + parser.onopenobject = function (newKey) { + var newObj = {}; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + key = newKey; + array = false; + ++level; + }; + parser.onkey = function (newKey) { return key = newKey; }; + parser.onvalue = function (value) { return array ? obj.push(value) : obj[key] = value; }; + parser.oncloseobject = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + parser.onopenarray = function () { + var newObj = []; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + array = true; + key = null; + ++level; + }; + parser.onclosearray = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + return { + write: function (jsonPart) { + parser.write(jsonPart); + return result; + }, + done: function () { + return done; + } + }; +} + +var DEFAULT_KILOBYTES_PER_CHUNK = 1024; +function importDB(exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + var CHUNK_SIZE, stream, dbExport, db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + stream = _a.sent(); + dbExport = stream.result.data; + db = new Dexie(dbExport.databaseName); + db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport)); + return [4 /*yield*/, importInto(db, stream, options)]; + case 2: + _a.sent(); + return [2 /*return*/, db]; + } + }); + }); +} +function importInto(db, exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + function importAll() { + return __awaiter(this, void 0, void 0, function () { + var _loop_1, _i, _a, tableExport, state_1; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _loop_1 = function (tableExport) { + var tableName, table, tableSchemaStr, sourceRows, rows, i, obj, filter, filteredRows, _a, keys, values; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!tableExport.rows) + return [2 /*return*/, "break"]; // Need to pull more! + if (!tableExport.rows.incomplete && tableExport.rows.length === 0) + return [2 /*return*/, "continue"]; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + tableName = tableExport.tableName; + table = db.table(tableName); + tableSchemaStr = dbExport.tables.filter(function (t) { return t.name === tableName; })[0].schema; + if (!table) { + if (!options.acceptMissingTables) + throw new Error("Exported table " + tableExport.tableName + " is missing in installed database"); + else + return [2 /*return*/, "continue"]; + } + if (!options.acceptChangedPrimaryKey && + tableSchemaStr.split(',')[0] != table.schema.primKey.src) { + throw new Error("Primary key differs for table " + tableExport.tableName + ". "); + } + sourceRows = tableExport.rows; + rows = []; + for (i = 0; i < sourceRows.length; i++) { + obj = sourceRows[i]; + if (!obj.incomplete) { + rows.push(TSON.revive(obj)); + } + else { + break; + } + } + filter = options.filter; + filteredRows = filter ? + tableExport.inbound ? + rows.filter(function (value) { return filter(tableName, value); }) : + rows.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }) : + rows; + _a = tableExport.inbound ? + [undefined, filteredRows] : + [filteredRows.map(function (row) { return row[0]; }), rows.map(function (row) { return row[1]; })], keys = _a[0], values = _a[1]; + if (!options.clearTablesBeforeImport) return [3 /*break*/, 2]; + return [4 /*yield*/, table.clear()]; + case 1: + _b.sent(); + _b.label = 2; + case 2: + if (!options.overwriteValues) return [3 /*break*/, 4]; + return [4 /*yield*/, table.bulkPut(values, keys)]; + case 3: + _b.sent(); + return [3 /*break*/, 6]; + case 4: return [4 /*yield*/, table.bulkAdd(values, keys)]; + case 5: + _b.sent(); + _b.label = 6; + case 6: + progress.completedRows += rows.length; + if (!rows.incomplete) { + progress.completedTables += 1; + } + sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance. + return [2 /*return*/]; + } + }); + }; + _i = 0, _a = dbExport.data; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + tableExport = _a[_i]; + return [5 /*yield**/, _loop_1(tableExport)]; + case 2: + state_1 = _b.sent(); + if (state_1 === "break") + return [3 /*break*/, 4]; + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: + // Avoid unnescessary loops in "for (const tableExport of dbExport.data)" + while (dbExport.data.length > 0 && dbExport.data[0].rows && !dbExport.data[0].rows.incomplete) { + // We've already imported all rows from the first table. Delete its occurrence + dbExport.data.splice(0, 1); + } + if (!(!jsonStream.done() && !jsonStream.eof())) return [3 /*break*/, 8]; + if (!readBlobsSynchronously) return [3 /*break*/, 5]; + // If we can pull from blob synchronically, we don't have to + // keep transaction alive using Dexie.waitFor(). + // This will only be possible in workers. + jsonStream.pullSync(CHUNK_SIZE); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, Dexie.waitFor(jsonStream.pullAsync(CHUNK_SIZE))]; + case 6: + _b.sent(); + _b.label = 7; + case 7: return [3 /*break*/, 9]; + case 8: return [3 /*break*/, 10]; + case 9: + return [3 /*break*/, 0]; + _b.label = 10; + case 10: return [2 /*return*/]; + } + }); + }); + } + var CHUNK_SIZE, jsonStream, dbExportFile, readBlobsSynchronously, dbExport, progressCallback, progress; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + jsonStream = _a.sent(); + dbExportFile = jsonStream.result; + readBlobsSynchronously = 'FileReaderSync' in self; + dbExport = dbExportFile.data; + if (!options.acceptNameDiff && db.name !== dbExport.databaseName) + throw new Error("Name differs. Current database name is " + db.name + " but export is " + dbExport.databaseName); + if (!options.acceptVersionDiff && db.verno !== dbExport.databaseVersion) { + // Possible feature: Call upgraders in some isolated way if this happens... ? + throw new Error("Database version differs. Current database is in version " + db.verno + " but export is " + dbExport.databaseVersion); + } + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: dbExport.tables.reduce(function (p, c) { return p + c.rowCount; }, 0), + totalTables: dbExport.tables.length + }; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + if (!options.noTransaction) return [3 /*break*/, 3]; + return [4 /*yield*/, importAll()]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, db.transaction('rw', db.tables, importAll)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); +} +function loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE) { + return __awaiter(this, void 0, void 0, function () { + var stream, dbExportFile; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = ('slice' in exportedData ? + JsonStream(exportedData) : + exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(CHUNK_SIZE)]; + case 2: + _a.sent(); + if (stream.result.data && stream.result.data.data) + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + dbExportFile = stream.result; + if (!dbExportFile || dbExportFile.formatName != "dexie") + throw new Error("Given file is not a dexie export"); + if (dbExportFile.formatVersion > VERSION) { + throw new Error("Format version " + dbExportFile.formatVersion + " not supported"); + } + if (!dbExportFile.data) { + throw new Error("No data in export file"); + } + if (!dbExportFile.data.databaseName) { + throw new Error("Missing databaseName in export file"); + } + if (!dbExportFile.data.databaseVersion) { + throw new Error("Missing databaseVersion in export file"); + } + if (!dbExportFile.data.tables) { + throw new Error("Missing tables in export file"); + } + return [2 /*return*/, stream]; + } + }); + }); +} + +// +// Extend Dexie interface (runtime wise) +// +Dexie.prototype.export = function (options) { + return exportDB(this, options); +}; +Dexie.prototype.import = function (blob, options) { + return importInto(this, blob, options); +}; +Dexie.import = function (blob, options) { return importDB(blob, options); }; +var dexieExportImport = (function () { + throw new Error("This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options."); +}); + +export default dexieExportImport; +export { exportDB, importDB, importInto }; +//# sourceMappingURL=dexie-export-import.mjs.map diff --git a/addons/dexie-export-import/dist/dexie-export-import.mjs.map b/addons/dexie-export-import/dist/dexie-export-import.mjs.map new file mode 100644 index 000000000..bd3255b04 --- /dev/null +++ b/addons/dexie-export-import/dist/dexie-export-import.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-export-import.mjs","sources":["../node_modules/tslib/tslib.es6.js","../src/helpers.ts","../node_modules/typeson/dist/typeson.js","../node_modules/typeson-registry/node_modules/typeson/typeson.js","../node_modules/typeson-registry/node_modules/base64-arraybuffer-es6/src/base64-arraybuffer.js","../node_modules/typeson-registry/types/user-object.js","../node_modules/typeson-registry/presets/sparse-undefined.js","../node_modules/typeson-registry/types/undef.js","../node_modules/typeson-registry/types/primitive-objects.js","../node_modules/typeson-registry/types/nan.js","../node_modules/typeson-registry/types/infinity.js","../node_modules/typeson-registry/types/negative-infinity.js","../node_modules/typeson-registry/types/date.js","../node_modules/typeson-registry/types/regexp.js","../node_modules/typeson-registry/types/map.js","../node_modules/typeson-registry/types/set.js","../node_modules/typeson-registry/types/arraybuffer.js","../node_modules/typeson-registry/types/typed-arrays.js","../node_modules/typeson-registry/types/dataview.js","../node_modules/typeson-registry/types/intl-types.js","../node_modules/typeson-registry/utils/stringArrayBuffer.js","../node_modules/typeson-registry/types/file.js","../node_modules/typeson-registry/presets/structured-cloning.js","../node_modules/typeson-registry/types/imagedata.js","../node_modules/typeson-registry/types/imagebitmap.js","../node_modules/typeson-registry/types/filelist.js","../node_modules/typeson-registry/types/blob.js","../node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js","../src/tson-typed-array.ts","../src/tson-arraybuffer.ts","../src/tson.ts","../src/export.ts","../src/json-structure.ts","../tools/build-configs/fake-stream.js","../node_modules/clarinet/clarinet.js","../src/json-stream.ts","../src/import.ts","../src/dexie-export-import.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","import Dexie from 'dexie';\nimport { DexieExportedDatabase } from './json-structure';\n\nexport function getSchemaString(table: Dexie.Table) {\n const primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes);\n return primKeyAndIndexes.map(index => index.src).join(',');\n}\n\nexport function extractDbSchema(exportedDb: DexieExportedDatabase) {\n const schema: {\n [tableName: string]: string;\n } = {};\n for (const table of exportedDb.tables) {\n schema[table.name] = table.schema;\n }\n return schema;\n}\n\n\n// Missing FileReaderSync type in standard typescript libs:\ninterface FileReaderSync {\n readAsArrayBuffer(blob: Blob): ArrayBuffer;\n readAsBinaryString(blob: Blob): string;\n readAsDataURL(blob: Blob): string;\n readAsText(blob: Blob, encoding?: string): string;\n}\ndeclare var FileReaderSync: {\n prototype: FileReaderSync;\n new(): FileReaderSync;\n};\n// -----------------------------------------------\n\nexport interface TypeMapper {\n binary: ArrayBuffer;\n text: string;\n}\n\nexport function readBlobAsync(blob: Blob, type: T): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = ev => reject(new Error(\"file read aborted\"));\n reader.onerror = ev => reject((ev.target as any).error);\n reader.onload = ev => resolve((ev.target as any).result);\n if (type === 'binary')\n reader.readAsArrayBuffer(blob);\n else\n reader.readAsText(blob);\n });\n}\n\nexport function readBlobSync(blob: Blob, type: T): TypeMapper[T] {\n if (typeof FileReaderSync === 'undefined') {\n throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.');\n }\n const reader = new FileReaderSync(); // Requires worker environment\n const data = type === 'binary' ?\n reader.readAsArrayBuffer(blob) :\n reader.readAsText(blob);\n\n return data as TypeMapper[T];\n}\n","!function(e,n){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=n():\"function\"==typeof define&&define.amd?define(n):e.Typeson=n()}(this,function(){\"use strict\";var e=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&\"function\"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e},n=function(){return function(e,n){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function sliceIterator(e,n){var t=[],r=!0,i=!1,o=void 0;try{for(var s,c=e[Symbol.iterator]();!(r=(s=c.next()).done)&&(t.push(s.value),!n||t.length!==n);r=!0);}catch(e){i=!0,o=e}finally{try{!r&&c.return&&c.return()}finally{if(i)throw o}}return t}(e,n);throw new TypeError(\"Invalid attempt to destructure non-iterable instance\")}}(),t=function(e){if(Array.isArray(e)){for(var n=0,t=Array(e.length);n2&&void 0!==arguments[2]?arguments[2]:{};return t.returnTypeNames=!0,this.encapsulate(e,n,t)},this.rootTypeName=function(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.iterateNone=!0,this.encapsulate(e,n,t)};var l=this.encapsulate=function(y,p,f){var l=(f=Object.assign({sync:!0},o,f)).sync,h={},v=[],d=[],b=[],O=!(f&&\"cyclic\"in f)||f.cyclic,m=f.encapsulateObserver,T=_encapsulate(\"\",y,O,p||{},b);function finish(e){var n=Object.values(h);if(f.iterateNone)return n.length?n[0]:Typeson.getJSONType(e);if(n.length){if(f.returnTypeNames)return[].concat(t(new Set(n)));e&&isPlainObject(e)&&!e.hasOwnProperty(\"$types\")?e.$types=h:e={$:e,$types:{$:h}}}else isObject(e)&&e.hasOwnProperty(\"$types\")&&(e={$:e,$types:!0});return!f.returnTypeNames&&e}return b.length?l&&f.throwOnBadSyncType?function(){throw new TypeError(\"Sync method requested but async result obtained\")}():Promise.resolve(function checkPromises(e,t){return Promise.all(t.map(function(e){return e[1].p})).then(function(r){return Promise.all(r.map(function(r){var i=[],o=t.splice(0,1)[0],s=n(o,7),c=s[0],a=s[2],u=s[3],y=s[4],p=s[5],f=s[6],l=_encapsulate(c,r,a,u,i,!0,f),h=hasConstructorOf(l,TypesonPromise);return c&&h?l.p.then(function(n){return y[p]=n,checkPromises(e,i)}):(c?y[p]=l:e=h?l.p:l,checkPromises(e,i))}))}).then(function(){return e})}(T,b)).then(finish):!l&&f.throwOnBadSyncType?function(){throw new TypeError(\"Async method requested but sync result obtained\")}():f.stringification&&l?[finish(T)]:l?finish(T):Promise.resolve(finish(T));function _adaptBuiltinStateObjectProperties(e,n,t){Object.assign(e,n);var r=u.map(function(n){var t=e[n];return delete e[n],t});t(),u.forEach(function(n,t){e[n]=r[t]})}function _encapsulate(n,t,o,c,a,u,y){var p=void 0,l={},b=void 0===t?\"undefined\":e(t),O=m?function(e){var r=y||c.type||Typeson.getJSONType(t);m(Object.assign(e||l,{keypath:n,value:t,cyclic:o,stateObj:c,promisesData:a,resolvingTypesonPromise:u,awaitingTypesonPromise:hasConstructorOf(t,TypesonPromise)},void 0!==r?{type:r}:{}))}:null;if(b in{string:1,boolean:1,number:1,undefined:1})return void 0===t||\"number\"===b&&(isNaN(t)||t===-1/0||t===1/0)?(p=replace(n,t,c,a,!1,u,O))!==t&&(l={replaced:p}):p=t,O&&O(),p;if(null===t)return O&&O(),t;if(o&&!c.iterateIn&&!c.iterateUnsetNumeric){var T=v.indexOf(t);if(!(T<0))return h[n]=\"#\",O&&O({cyclicKeypath:d[T]}),\"#\"+d[T];!0===o&&(v.push(t),d.push(n))}var g=isPlainObject(t),P=i(t),j=(g||P)&&(!s.length||c.replaced)||c.iterateIn?t:replace(n,t,c,a,g||P,null,O),S=void 0;if(j!==t?(p=j,l={replaced:j}):P||\"array\"===c.iterateIn?(S=new Array(t.length),l={clone:S}):g||\"object\"===c.iterateIn?l={clone:S={}}:\"\"===n&&hasConstructorOf(t,TypesonPromise)?(a.push([n,t,o,c,void 0,void 0,c.type]),p=t):p=t,O&&O(),f.iterateNone)return S||p;if(!S)return p;if(c.iterateIn){var w=function _loop(e){var r={ownKeys:t.hasOwnProperty(e)};_adaptBuiltinStateObjectProperties(c,r,function(){var r=n+(n?\".\":\"\")+escapeKeyPathComponent(e),i=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(i,TypesonPromise)?a.push([r,i,!!o,c,S,e,c.type]):void 0!==i&&(S[e]=i)})};for(var A in t)w(A);O&&O({endIterateIn:!0,end:!0})}else r(t).forEach(function(e){var r=n+(n?\".\":\"\")+escapeKeyPathComponent(e);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},function(){var n=_encapsulate(r,t[e],!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n)})}),O&&O({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var C=t.length,N=function _loop2(e){if(!(e in t)){var r=n+(n?\".\":\"\")+e;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},function(){var n=_encapsulate(r,void 0,!!o,c,a,u);hasConstructorOf(n,TypesonPromise)?a.push([r,n,!!o,c,S,e,c.type]):void 0!==n&&(S[e]=n)})}},B=0;B-1){var r=e[unescapeKeyPathComponent(n.substr(0,t))];return void 0===r?void 0:getByKeyPath(r,n.substr(t+1))}return e[unescapeKeyPathComponent(n)]}function Undefined(){}function TypesonPromise(e){this.p=new Promise(e)}return TypesonPromise.prototype.then=function(e,n){var t=this;return new TypesonPromise(function(r,i){t.p.then(function(n){r(e?e(n):n)},function(e){t.p.catch(function(e){return n?n(e):Promise.reject(e)}).then(r,i)})})},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise(function(n){n(e)})},TypesonPromise.reject=function(e){return new TypesonPromise(function(n,t){t(e)})},[\"all\",\"race\"].map(function(e){TypesonPromise[e]=function(n){return new TypesonPromise(function(t,r){Promise[e](n.map(function(e){return e.p})).then(t,r)})}}),Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=function isUserObject(e){if(!e||\"Object\"!==toStringTag(e))return!1;var n=s(e);return!n||hasConstructorOf(e,Object)||isUserObject(n)},Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=function(n){return null===n?\"null\":i(n)?\"array\":void 0===n?\"undefined\":e(n)},Typeson.JSON_TYPES=[\"null\",\"boolean\",\"number\",\"string\",\"array\",\"object\"],Typeson});\n","const keys = Object.keys,\n isArray = Array.isArray,\n toString = ({}.toString),\n getProto = Object.getPrototypeOf,\n hasOwn = ({}.hasOwnProperty),\n fnToString = hasOwn.toString,\n internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric'];\n\nfunction isThenable (v, catchCheck) {\n return Typeson.isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v.catch === 'function');\n}\n\nfunction toStringTag (val) {\n return toString.call(val).slice(8, -1);\n}\n\n// This function is dependent on both constructors\n// being identical so any minimization is expected of both\nfunction hasConstructorOf (a, b) {\n if (!a || typeof a !== 'object') {\n return false;\n }\n const proto = getProto(a);\n if (!proto) {\n return false;\n }\n const Ctor = hasOwn.call(proto, 'constructor') && proto.constructor;\n if (typeof Ctor !== 'function') {\n return b === null;\n }\n return typeof Ctor === 'function' && b !== null && fnToString.call(Ctor) === fnToString.call(b);\n}\n\nfunction isPlainObject (val) { // Mirrors jQuery's\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n const proto = getProto(val);\n if (!proto) { // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object);\n}\n\nfunction isUserObject (val) {\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n const proto = getProto(val);\n if (!proto) { // `Object.create(null)`\n return true;\n }\n return hasConstructorOf(val, Object) || isUserObject(proto);\n}\n\nfunction isObject (v) {\n return v && typeof v === 'object';\n}\n\n/* Typeson - JSON with types\n * License: The MIT License (MIT)\n * Copyright (c) 2016 David Fahlander\n */\n\n/** An instance of this class can be used to call stringify() and parse().\n * Typeson resolves cyclic references by default. Can also be extended to\n * support custom types using the register() method.\n *\n * @constructor\n * @param {{cyclic: boolean}} [options] - if cyclic (default true), cyclic references will be handled gracefully.\n */\nfunction Typeson (options) {\n // Replacers signature: replace (value). Returns falsy if not replacing. Otherwise ['Date', value.getTime()]\n const plainObjectReplacers = [];\n const nonplainObjectReplacers = [];\n // Revivers: map {type => reviver}. Sample: {'Date': value => new Date(value)}\n const revivers = {};\n\n /** Types registered via register() */\n const regTypes = this.types = {};\n\n /** Serialize given object to Typeson.\n *\n * Arguments works identical to those of JSON.stringify().\n */\n const stringify = this.stringify = function (obj, replacer, space, opts) { // replacer here has nothing to do with our replacers.\n opts = Object.assign({}, options, opts, {stringification: true});\n const encapsulated = encapsulate(obj, null, opts);\n if (isArray(encapsulated)) {\n return JSON.stringify(encapsulated[0], replacer, space);\n }\n return encapsulated.then((res) => {\n return JSON.stringify(res, replacer, space);\n });\n };\n\n // Also sync but throws on non-sync result\n this.stringifySync = function (obj, replacer, space, opts) {\n return stringify(obj, replacer, space, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true}));\n };\n this.stringifyAsync = function (obj, replacer, space, opts) {\n return stringify(obj, replacer, space, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false}));\n };\n\n /** Parse Typeson back into an obejct.\n *\n * Arguments works identical to those of JSON.parse().\n */\n const parse = this.parse = function (text, reviver, opts) {\n opts = Object.assign({}, options, opts, {parse: true});\n return revive(JSON.parse(text, reviver), opts); // This reviver has nothing to do with our revivers.\n };\n\n // Also sync but throws on non-sync result\n this.parseSync = function (text, reviver, opts) {\n return parse(text, reviver, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true})); // This reviver has nothing to do with our revivers.\n };\n this.parseAsync = function (text, reviver, opts) {\n return parse(text, reviver, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false})); // This reviver has nothing to do with our revivers.\n };\n\n this.specialTypeNames = function (obj, stateObj, opts = {}) {\n opts.returnTypeNames = true;\n return this.encapsulate(obj, stateObj, opts);\n };\n this.rootTypeName = function (obj, stateObj, opts = {}) {\n opts.iterateNone = true;\n return this.encapsulate(obj, stateObj, opts);\n };\n\n /** Encapsulate a complex object into a plain Object by replacing registered types with\n * plain objects representing the types data.\n *\n * This method is used internally by Typeson.stringify().\n * @param {Object} obj - Object to encapsulate.\n */\n const encapsulate = this.encapsulate = function (obj, stateObj, opts) {\n opts = Object.assign({sync: true}, options, opts);\n const sync = opts.sync;\n const types = {},\n refObjs = [], // For checking cyclic references\n refKeys = [], // For checking cyclic references\n promisesDataRoot = [];\n // Clone the object deeply while at the same time replacing any special types or cyclic reference:\n const cyclic = opts && ('cyclic' in opts) ? opts.cyclic : true;\n const encapsulateObserver = opts.encapsulateObserver;\n const ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot);\n function finish (ret) {\n // Add $types to result only if we ever bumped into a special type (or special case where object has own `$types`)\n const typeNames = Object.values(types);\n if (opts.iterateNone) {\n if (typeNames.length) {\n return typeNames[0];\n }\n return Typeson.getJSONType(ret);\n }\n if (typeNames.length) {\n if (opts.returnTypeNames) {\n return [...new Set(typeNames)];\n }\n if (!ret || !isPlainObject(ret) || // Special if array (or a primitive) was serialized because JSON would ignore custom `$types` prop on it\n ret.hasOwnProperty('$types') // Also need to handle if this is an object with its own `$types` property (to avoid ambiguity)\n ) {\n ret = {$: ret, $types: {$: types}};\n } else {\n ret.$types = types;\n }\n } else if (isObject(ret) && ret.hasOwnProperty('$types')) { // No special types\n ret = {$: ret, $types: true};\n }\n if (opts.returnTypeNames) {\n return false;\n }\n return ret;\n }\n function checkPromises (ret, promisesData) {\n return Promise.all(\n promisesData.map((pd) => { return pd[1].p; })\n ).then(function (promResults) {\n return Promise.all(\n promResults.map(function (promResult) {\n const newPromisesData = [];\n const prData = promisesData.splice(0, 1)[0];\n const [keyPath, , cyclic, stateObj, parentObj, key, detectedType] = prData;\n\n const encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType);\n const isTypesonPromise = hasConstructorOf(encaps, TypesonPromise);\n if (keyPath && isTypesonPromise) { // Handle case where an embedded custom type itself returns a `Typeson.Promise`\n return encaps.p.then(function (encaps2) {\n parentObj[key] = encaps2;\n return checkPromises(ret, newPromisesData);\n });\n }\n if (keyPath) parentObj[key] = encaps;\n else if (isTypesonPromise) {\n ret = encaps.p;\n } else ret = encaps; // If this is itself a `Typeson.Promise` (because the original value supplied was a promise or because the supplied custom type value resolved to one), returning it below will be fine since a promise is expected anyways given current config (and if not a promise, it will be ready as the resolve value)\n return checkPromises(ret, newPromisesData);\n })\n );\n }).then(() => ret);\n };\n return promisesDataRoot.length\n ? sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Sync method requested but async result obtained');\n })()\n : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish)\n : !sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Async method requested but sync result obtained');\n })()\n : (opts.stringification && sync // If this is a synchronous request for stringification, yet a promise is the result, we don't want to resolve leading to an async result, so we return an array to avoid ambiguity\n ? [finish(ret)]\n : (sync\n ? finish(ret)\n : Promise.resolve(finish(ret))\n ));\n\n function _adaptBuiltinStateObjectProperties (stateObj, ownKeysObj, cb) {\n Object.assign(stateObj, ownKeysObj);\n const vals = internalStateObjPropsToIgnore.map((prop) => {\n const tmp = stateObj[prop];\n delete stateObj[prop];\n return tmp;\n });\n cb();\n internalStateObjPropsToIgnore.forEach((prop, i) => {\n stateObj[prop] = vals[i];\n });\n }\n function _encapsulate (keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) {\n let ret;\n let observerData = {};\n const $typeof = typeof value;\n const runObserver = encapsulateObserver ? function (obj) {\n const type = detectedType || stateObj.type || (\n Typeson.getJSONType(value)\n );\n encapsulateObserver(Object.assign(obj || observerData, {\n keypath,\n value,\n cyclic,\n stateObj,\n promisesData,\n resolvingTypesonPromise,\n awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise)\n }, type !== undefined ? {type} : {}));\n } : null;\n if ($typeof in {string: 1, boolean: 1, number: 1, undefined: 1}) {\n if (value === undefined || ($typeof === 'number' &&\n (isNaN(value) || value === -Infinity || value === Infinity))) {\n ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver);\n if (ret !== value) {\n observerData = {replaced: ret};\n }\n } else {\n ret = value;\n }\n if (runObserver) runObserver();\n return ret;\n }\n if (value === null) {\n if (runObserver) runObserver();\n return value;\n }\n if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric) {\n // Options set to detect cyclic references and be able to rewrite them.\n const refIndex = refObjs.indexOf(value);\n if (refIndex < 0) {\n if (cyclic === true) {\n refObjs.push(value);\n refKeys.push(keypath);\n }\n } else {\n types[keypath] = '#';\n if (runObserver) {\n runObserver({\n cyclicKeypath: refKeys[refIndex]\n });\n }\n return '#' + refKeys[refIndex];\n }\n }\n const isPlainObj = isPlainObject(value);\n const isArr = isArray(value);\n const replaced = (\n ((isPlainObj || isArr) && (!plainObjectReplacers.length || stateObj.replaced)) ||\n stateObj.iterateIn // Running replace will cause infinite loop as will test positive again\n )\n // Optimization: if plain object and no plain-object replacers, don't try finding a replacer\n ? value\n : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver);\n let clone;\n if (replaced !== value) {\n ret = replaced;\n observerData = {replaced: replaced};\n } else {\n if (isArr || stateObj.iterateIn === 'array') {\n clone = new Array(value.length);\n observerData = {clone: clone};\n } else if (isPlainObj || stateObj.iterateIn === 'object') {\n clone = {};\n observerData = {clone: clone};\n } else if (keypath === '' && hasConstructorOf(value, TypesonPromise)) {\n promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]);\n ret = value;\n } else {\n ret = value; // Only clone vanilla objects and arrays\n }\n }\n if (runObserver) runObserver();\n\n if (opts.iterateNone) {\n return clone || ret;\n }\n\n if (!clone) {\n return ret;\n }\n\n // Iterate object or array\n if (stateObj.iterateIn) {\n for (const key in value) {\n const ownKeysObj = {ownKeys: value.hasOwnProperty(key)};\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, () => {\n const kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n const val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise);\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) clone[key] = val;\n });\n }\n if (runObserver) runObserver({endIterateIn: true, end: true});\n } else { // Note: Non-indexes on arrays won't survive stringify so somewhat wasteful for arrays, but so too is iterating all numeric indexes on sparse arrays when not wanted or filtering own keys for positive integers\n keys(value).forEach(function (key) {\n const kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n const ownKeysObj = {ownKeys: true};\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, () => {\n const val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise);\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) clone[key] = val;\n });\n });\n if (runObserver) runObserver({endIterateOwn: true, end: true});\n }\n // Iterate array for non-own numeric properties (we can't replace the prior loop though as it iterates non-integer keys)\n if (stateObj.iterateUnsetNumeric) {\n const vl = value.length;\n for (let i = 0; i < vl; i++) {\n if (!(i in value)) {\n const kp = keypath + (keypath ? '.' : '') + i; // No need to escape numeric\n const ownKeysObj = {ownKeys: false};\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, () => {\n const val = _encapsulate(kp, undefined, !!cyclic, stateObj, promisesData, resolvingTypesonPromise);\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, !!cyclic, stateObj, clone, i, stateObj.type]);\n } else if (val !== undefined) clone[i] = val;\n });\n }\n }\n if (runObserver) runObserver({endIterateUnsetNumeric: true, end: true});\n }\n return clone;\n }\n\n function replace (keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) {\n // Encapsulate registered types\n const replacers = plainObject ? plainObjectReplacers : nonplainObjectReplacers;\n let i = replacers.length;\n while (i--) {\n const replacer = replacers[i];\n if (replacer.test(value, stateObj)) {\n const type = replacer.type;\n if (revivers[type]) {\n // Record the type only if a corresponding reviver exists.\n // This is to support specs where only replacement is done.\n // For example ensuring deep cloning of the object, or\n // replacing a type to its equivalent without the need to revive it.\n const existing = types[keypath];\n // type can comprise an array of types (see test shouldSupportIntermediateTypes)\n types[keypath] = existing ? [type].concat(existing) : type;\n }\n // Now, also traverse the result in case it contains its own types to replace\n Object.assign(stateObj, {type, replaced: true});\n if ((sync || !replacer.replaceAsync) && !replacer.replace) {\n if (runObserver) runObserver({typeDetected: true});\n return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n if (runObserver) runObserver({replacing: true});\n\n const replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync';\n return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n }\n return value;\n }\n };\n\n // Also sync but throws on non-sync result\n this.encapsulateSync = function (obj, stateObj, opts) {\n return encapsulate(obj, stateObj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true}));\n };\n this.encapsulateAsync = function (obj, stateObj, opts) {\n return encapsulate(obj, stateObj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false}));\n };\n\n /** Revive an encapsulated object.\n * This method is used internally by Typeson.parse().\n * @param {Object} obj - Object to revive. If it has $types member, the properties that are listed there\n * will be replaced with its true type instead of just plain objects.\n */\n const revive = this.revive = function (obj, opts) {\n opts = Object.assign({sync: true}, options, opts);\n const sync = opts.sync;\n let types = obj && obj.$types,\n ignore$Types = true;\n if (!types) return obj; // No type info added. Revival not needed.\n if (types === true) return obj.$; // Object happened to have own `$types` property but with no actual types, so we unescape and return that object\n if (types.$ && isPlainObject(types.$)) {\n // Special when root object is not a trivial Object, it will be encapsulated in $. It will also be encapsulated in $ if it has its own `$` property to avoid ambiguity\n obj = obj.$;\n types = types.$;\n ignore$Types = false;\n }\n const keyPathResolutions = [];\n const stateObj = {};\n let ret = _revive('', obj, null, opts);\n ret = hasConstructorOf(ret, Undefined) ? undefined : ret;\n return isThenable(ret)\n ? sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Sync method requested but async result obtained');\n })()\n : ret\n : !sync && opts.throwOnBadSyncType\n ? (() => {\n throw new TypeError('Async method requested but sync result obtained');\n })()\n : sync\n ? ret\n : Promise.resolve(ret);\n\n function _revive (keypath, value, target, opts, clone, key) {\n if (ignore$Types && keypath === '$types') return;\n const type = types[keypath];\n if (isArray(value) || isPlainObject(value)) {\n const clone = isArray(value) ? new Array(value.length) : {};\n // Iterate object or array\n keys(value).forEach((key) => {\n const val = _revive(\n keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key), value[key],\n target || clone,\n opts,\n clone,\n key\n );\n if (hasConstructorOf(val, Undefined)) clone[key] = undefined;\n else if (val !== undefined) clone[key] = val;\n });\n value = clone;\n while (keyPathResolutions.length) { // Try to resolve cyclic reference as soon as available\n const [[target, keyPath, clone, key]] = keyPathResolutions;\n const val = getByKeyPath(target, keyPath);\n if (hasConstructorOf(val, Undefined)) clone[key] = undefined;\n else if (val !== undefined) clone[key] = val;\n else break;\n keyPathResolutions.splice(0, 1);\n }\n }\n if (!type) return value;\n if (type === '#') {\n const ret = getByKeyPath(target, value.substr(1));\n if (ret === undefined) { // Cyclic reference not yet available\n keyPathResolutions.push([target, value.substr(1), clone, key]);\n }\n return ret;\n }\n const sync = opts.sync;\n return [].concat(type).reduce((val, type) => {\n const reviver = revivers[type];\n if (!reviver) throw new Error('Unregistered type: ' + type);\n return reviver[ // eslint-disable-line standard/computed-property-even-spacing\n sync && reviver.revive\n ? 'revive'\n : !sync && reviver.reviveAsync\n ? 'reviveAsync'\n : 'revive'\n ](val, stateObj);\n }, value);\n }\n };\n\n // Also sync but throws on non-sync result\n this.reviveSync = function (obj, opts) {\n return revive(obj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true}));\n };\n this.reviveAsync = function (obj, opts) {\n return revive(obj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false}));\n };\n\n /** Register types.\n * For examples how to use this method, see https://github.com/dfahlander/typeson-registry/tree/master/types\n * @param {Array.>} typeSpec - Types and their functions [test, encapsulate, revive];\n */\n this.register = function (typeSpecSets, opts) {\n opts = opts || {};\n [].concat(typeSpecSets).forEach(function R (typeSpec) {\n if (isArray(typeSpec)) return typeSpec.map(R); // Allow arrays of arrays of arrays...\n typeSpec && keys(typeSpec).forEach(function (typeId) {\n if (typeId === '#') {\n throw new TypeError('# cannot be used as a type name as it is reserved for cyclic objects');\n } else if (Typeson.JSON_TYPES.includes(typeId)) {\n throw new TypeError('Plain JSON object types are reserved as type names');\n }\n let spec = typeSpec[typeId];\n const replacers = spec.testPlainObjects ? plainObjectReplacers : nonplainObjectReplacers;\n const existingReplacer = replacers.filter(function (r) { return r.type === typeId; });\n if (existingReplacer.length) {\n // Remove existing spec and replace with this one.\n replacers.splice(replacers.indexOf(existingReplacer[0]), 1);\n delete revivers[typeId];\n delete regTypes[typeId];\n }\n if (spec) {\n if (typeof spec === 'function') {\n // Support registering just a class without replacer/reviver\n const Class = spec;\n spec = {\n test: (x) => x && x.constructor === Class,\n replace: (x) => assign({}, x),\n revive: (x) => assign(Object.create(Class.prototype), x)\n };\n } else if (isArray(spec)) {\n spec = {\n test: spec[0],\n replace: spec[1],\n revive: spec[2]\n };\n }\n const replacerObj = {\n type: typeId,\n test: spec.test.bind(spec)\n };\n if (spec.replace) {\n replacerObj.replace = spec.replace.bind(spec);\n }\n if (spec.replaceAsync) {\n replacerObj.replaceAsync = spec.replaceAsync.bind(spec);\n }\n const start = typeof opts.fallback === 'number' ? opts.fallback : (opts.fallback ? 0 : Infinity);\n if (spec.testPlainObjects) {\n plainObjectReplacers.splice(start, 0, replacerObj);\n } else {\n nonplainObjectReplacers.splice(start, 0, replacerObj);\n }\n // Todo: We might consider a testAsync type\n if (spec.revive || spec.reviveAsync) {\n const reviverObj = {};\n if (spec.revive) reviverObj.revive = spec.revive.bind(spec);\n if (spec.reviveAsync) reviverObj.reviveAsync = spec.reviveAsync.bind(spec);\n revivers[typeId] = reviverObj;\n }\n\n regTypes[typeId] = spec; // Record to be retrieved via public types property.\n }\n });\n });\n return this;\n };\n}\n\nfunction assign (t, s) {\n keys(s).map((k) => { t[k] = s[k]; });\n return t;\n}\n\n/** escapeKeyPathComponent() utility */\nfunction escapeKeyPathComponent (keyPathComponent) {\n return keyPathComponent.replace(/~/g, '~0').replace(/\\./g, '~1');\n}\n\n/** unescapeKeyPathComponent() utility */\nfunction unescapeKeyPathComponent (keyPathComponent) {\n return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~');\n}\n\n/** getByKeyPath() utility */\nfunction getByKeyPath (obj, keyPath) {\n if (keyPath === '') return obj;\n const period = keyPath.indexOf('.');\n if (period > -1) {\n const innerObj = obj[unescapeKeyPathComponent(keyPath.substr(0, period))];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return obj[unescapeKeyPathComponent(keyPath)];\n}\n\n// We keep these two functions minimized so if using two instances of this\n// library, where one is minimized and one is not, it will still work\nfunction Undefined(){} // eslint-disable-line space-before-function-paren, space-before-blocks\n// With ES6 classes, we may be able to simply use `class TypesonPromise extends Promise` and add a string tag for detection\nfunction TypesonPromise(f){this.p=new Promise(f)} // eslint-disable-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi\n\nTypesonPromise.prototype.then = function (onFulfilled, onRejected) {\n return new TypesonPromise((typesonResolve, typesonReject) => {\n this.p.then(function (res) {\n typesonResolve(onFulfilled ? onFulfilled(res) : res);\n }, (r) => {\n this.p['catch'](function (res) {\n return onRejected ? onRejected(res) : Promise.reject(res);\n }).then(typesonResolve, typesonReject);\n });\n });\n};\nTypesonPromise.prototype['catch'] = function (onRejected) {\n return this.then(null, onRejected);\n};\nTypesonPromise.resolve = function (v) {\n return new TypesonPromise((typesonResolve) => {\n typesonResolve(v);\n });\n};\nTypesonPromise.reject = function (v) {\n return new TypesonPromise((typesonResolve, typesonReject) => {\n typesonReject(v);\n });\n};\n['all', 'race'].map(function (meth) {\n TypesonPromise[meth] = function (promArr) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n Promise[meth](promArr.map((prom) => { return prom.p; })).then(typesonResolve, typesonReject);\n });\n };\n});\n\n// The following provide classes meant to avoid clashes with other values\nTypeson.Undefined = Undefined; // To insist `undefined` should be added\nTypeson.Promise = TypesonPromise; // To support async encapsulation/stringification\n\n// Some fundamental type-checking utilities\nTypeson.isThenable = isThenable;\nTypeson.toStringTag = toStringTag;\nTypeson.hasConstructorOf = hasConstructorOf;\nTypeson.isObject = isObject;\nTypeson.isPlainObject = isPlainObject;\nTypeson.isUserObject = isUserObject;\n\nTypeson.escapeKeyPathComponent = escapeKeyPathComponent;\nTypeson.unescapeKeyPathComponent = unescapeKeyPathComponent;\nTypeson.getByKeyPath = getByKeyPath;\nTypeson.getJSONType = (value) =>\n value === null ? 'null' : (\n isArray(value)\n ? 'array'\n : typeof value);\nTypeson.JSON_TYPES = [\n 'null', 'boolean', 'number', 'string', 'array', 'object'\n];\n\nexport default Typeson;\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n// Use a lookup table to find the index.\nconst lookup = new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n\nexport const encode = function (arraybuffer, byteOffset, length) {\n const bytes = new Uint8Array(arraybuffer, byteOffset, length),\n len = bytes.length;\n let base64 = '';\n\n for (let i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n\n if ((len % 3) === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n\n return base64;\n};\n\nexport const decode = function (base64) {\n const len = base64.length;\n\n let bufferLength = base64.length * 0.75;\n let p = 0;\n let encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n const arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (let i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n\n return arraybuffer;\n};\n","import Typeson from 'typeson';\n\nexport default {\n userObject: {\n test (x, stateObj) { return Typeson.isUserObject(x); },\n replace (n) { return Object.assign({}, n); },\n revive (s) { return s; }\n }\n};\n","export default [\n {\n sparseArrays: {\n testPlainObjects: true,\n test (x) { return Array.isArray(x); },\n replace (a, stateObj) {\n stateObj.iterateUnsetNumeric = true;\n return a;\n }\n }\n },\n {\n sparseUndefined: {\n test (x, stateObj) {\n return typeof x === 'undefined' && stateObj.ownKeys === false;\n },\n replace (n) { return null; },\n revive (s) { return undefined; } // Will avoid adding anything\n }\n }\n];\n","// This does not preserve `undefined` in sparse arrays; see the `undefined` or `sparse-undefined` preset\nimport Typeson from 'typeson';\n\nexport default {\n undef: {\n test (x, stateObj) {\n return typeof x === 'undefined' &&\n (stateObj.ownKeys || !('ownKeys' in stateObj));\n },\n replace (n) { return null; },\n revive (s) { return new Typeson.Undefined(); } // Will add `undefined` (returning `undefined` would instead avoid explicitly setting)\n }\n};\n","// This module is for objectified primitives (such as `new Number(3)` or\n// `new String(\"foo\")`)\n/* eslint-disable no-new-wrappers */\nimport Typeson from 'typeson';\nexport default {\n // String Object (not primitive string which need no type spec)\n StringObject: {\n test (x) { return Typeson.toStringTag(x) === 'String' && typeof x === 'object'; },\n replace (s) { return String(s); }, // convert to primitive string\n revive (s) { return new String(s); } // Revive to an objectified string\n },\n // Boolean Object (not primitive boolean which need no type spec)\n BooleanObject: {\n test (x) { return Typeson.toStringTag(x) === 'Boolean' && typeof x === 'object'; },\n replace (b) { return Boolean(b); }, // convert to primitive boolean\n revive (b) { return new Boolean(b); } // Revive to an objectified Boolean\n },\n // Number Object (not primitive number which need no type spec)\n NumberObject: {\n test (x) { return Typeson.toStringTag(x) === 'Number' && typeof x === 'object'; },\n replace (n) { return Number(n); }, // convert to primitive number\n revive (n) { return new Number(n); } // Revive to an objectified number\n }\n};\n/* eslint-enable no-new-wrappers */\n","export default {\n nan: {\n test (x) { return typeof x === 'number' && isNaN(x); },\n replace (n) { return 'NaN'; },\n revive (s) { return NaN; }\n }\n};\n","export default {\n infinity: {\n test (x) { return x === Infinity; },\n replace (n) { return 'Infinity'; },\n revive (s) { return Infinity; }\n }\n};\n","export default {\n negativeInfinity: {\n test (x) { return x === -Infinity; },\n replace (n) { return '-Infinity'; },\n revive (s) { return -Infinity; }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n date: {\n test (x) { return Typeson.toStringTag(x) === 'Date'; },\n replace (date) {\n const time = date.getTime();\n if (isNaN(time)) {\n return 'NaN';\n }\n return time;\n },\n revive (time) {\n if (time === 'NaN') {\n return new Date(NaN);\n }\n return new Date(time);\n }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n regexp: {\n test (x) { return Typeson.toStringTag(x) === 'RegExp'; },\n replace (rexp) {\n return {\n source: rexp.source,\n flags: (rexp.global ? 'g' : '') +\n (rexp.ignoreCase ? 'i' : '') +\n (rexp.multiline ? 'm' : '') +\n (rexp.sticky ? 'y' : '') +\n (rexp.unicode ? 'u' : '')\n };\n },\n revive ({source, flags}) { return new RegExp(source, flags); }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n map: {\n test (x) { return Typeson.toStringTag(x) === 'Map'; },\n replace (map) { return Array.from(map.entries()); },\n revive (entries) { return new Map(entries); }\n }\n};\n","import Typeson from 'typeson';\nexport default {\n set: {\n test (x) { return Typeson.toStringTag(x) === 'Set'; },\n replace (set) { return Array.from(set.values()); },\n revive (values) { return new Set(values); }\n }\n};\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nexport default {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(b);\n if (index > -1) {\n return {index};\n }\n stateObj.buffers.push(b);\n return encode(b);\n },\n revive (b64, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n if (typeof b64 === 'object') {\n return stateObj.buffers[b64.index];\n }\n const buffer = decode(b64);\n stateObj.buffers.push(buffer);\n return buffer;\n }\n }\n};\n\n// See also typed-arrays!\n","/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst exportObj = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n if (TypedArray) {\n exportObj[typeName.toLowerCase()] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, length};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n length\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, length, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new TypedArray(buffer, byteOffset, length);\n }\n };\n }\n});\n\nexport default exportObj;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\nexport default {\n dataview: {\n test (x) { return Typeson.toStringTag(x) === 'DataView'; },\n replace ({buffer, byteOffset, byteLength}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, byteLength};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n byteLength\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, byteLength, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new DataView(buffer, byteOffset, byteLength);\n }\n }\n};\n","import Typeson from 'typeson';\n\nconst IntlCollator = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.Collator); },\n replace (c) { return c.resolvedOptions(); },\n revive (options) { return new Intl.Collator(options.locale, options); }\n};\n\nconst IntlDateTimeFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.DateTimeFormat); },\n replace (dtf) { return dtf.resolvedOptions(); },\n revive (options) { return new Intl.DateTimeFormat(options.locale, options); }\n};\n\nconst IntlNumberFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.NumberFormat); },\n replace (nf) { return nf.resolvedOptions(); },\n revive (options) { return new Intl.NumberFormat(options.locale, options); }\n};\n\nexport default {\n IntlCollator,\n IntlDateTimeFormat,\n IntlNumberFormat\n};\n","function arraybuffer2string (buf) {\n return new Uint16Array(buf).reduce((s, byte) => s + String.fromCharCode(byte), '');\n}\n\nfunction string2arraybuffer (str) {\n /*\n // UTF-8 approaches\n const utf8 = unescape(encodeURIComponent(str));\n const arr = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n arr[i] = utf8.charCodeAt(i);\n }\n return arr.buffer;\n\n const utf8 = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 0x80) utf8.push(charcode);\n else if (charcode < 0x800) {\n utf8.push(0xc0 | (charcode >> 6),\n 0x80 | (charcode & 0x3f));\n } else if (charcode < 0xd800 || charcode >= 0xe000) {\n utf8.push(0xe0 | (charcode >> 12),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n // surrogate pair\n } else {\n i++;\n // UTF-16 encodes 0x10000-0x10FFFF by\n // subtracting 0x10000 and splitting the\n // 20 bits of 0x0-0xFFFFF into two halves\n charcode = 0x10000 + (((charcode & 0x3ff) << 10) |\n (str.charCodeAt(i) & 0x3ff));\n utf8.push(0xf0 | (charcode >> 18),\n 0x80 | ((charcode >> 12) & 0x3f),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n }\n }\n return utf8;\n */\n /*\n // Working UTF-16 options (equivalents)\n const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char\n const bufView = new Uint16Array(buf);\n for (let i = 0, strLen = str.length; i < strLen; i++) {\n bufView[i] = str.charCodeAt(i);\n }\n return buf;\n */\n\n const array = new Uint16Array(str.length);\n for (let i = 0; i < str.length; i++) {\n array[i] = str.charCodeAt(i);\n }\n return array.buffer;\n}\nexport {arraybuffer2string, string2arraybuffer};\n","import Typeson from 'typeson';\n\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nexport default {\n file: {\n test (x) { return Typeson.toStringTag(x) === 'File'; },\n replace (f) { // Sync\n const req = new XMLHttpRequest();\n req.open('GET', URL.createObjectURL(f), false); // Sync\n if (typeof TextEncoder !== 'undefined') { // Using TextDecoder/TextEncoder used too much space\n req.overrideMimeType('text/plain; charset=utf-16le');\n }\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad Blob access: ' + req.status);\n }\n req.send();\n return {\n type: f.type,\n stringContents: req.responseText,\n name: f.name,\n lastModified: f.lastModified\n };\n },\n revive ({name, type, stringContents, lastModified}) {\n // stringContents = new TextEncoder().encode(stringContents);\n const buffer = string2arraybuffer(stringContents);\n // stringContents = new TextDecoder('utf-16le').decode(buffer);\n return new File([buffer], name, {\n type,\n lastModified\n });\n },\n replaceAsync (f) {\n return new Typeson.Promise(function (resolve, reject) {\n if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The File is closed'));\n return;\n }\n const reader = new FileReader();\n reader.addEventListener('load', function () {\n resolve({\n type: f.type,\n stringContents: reader.result,\n name: f.name,\n lastModified: f.lastModified\n });\n });\n reader.addEventListener('error', function () {\n reject(reader.error);\n });\n reader.readAsText(f, 'UTF-16');\n });\n }\n }\n};\n","/* This preset includes types for the Structured Cloning Algorithm. */\n\nimport userObject from '../types/user-object.js';\nimport presetUndefined from '../presets/undef.js';\nimport primitiveObjects from '../types/primitive-objects.js';\nimport specialNumbers from '../presets/special-numbers.js';\nimport date from '../types/date.js';\nimport regexp from '../types/regexp.js';\nimport map from '../types/map.js';\nimport set from '../types/set.js';\nimport arraybuffer from '../types/arraybuffer.js';\nimport typedArrays from '../types/typed-arrays.js';\nimport dataview from '../types/dataview.js';\nimport intlTypes from '../types/intl-types.js';\n\nimport imagedata from '../types/imagedata.js';\nimport imagebitmap from '../types/imagebitmap.js'; // Async return\nimport file from '../types/file.js';\nimport filelist from '../types/filelist.js';\nimport blob from '../types/blob.js';\n\nconst expObj = [\n // Todo: Might also register synchronous `ImageBitmap` and `Blob`/`File`/`FileList`?\n // ES5\n userObject, // Processed last (non-builtin)\n\n presetUndefined, primitiveObjects, specialNumbers,\n date, regexp,\n\n // Non-built-ins\n imagedata,\n imagebitmap, // Async return\n file,\n filelist,\n blob\n].concat(\n // ES2015 (ES6)\n typeof Map === 'function' ? map : [],\n typeof Set === 'function' ? set : [],\n typeof ArrayBuffer === 'function' ? arraybuffer : [],\n typeof Uint8Array === 'function' ? typedArrays : [],\n typeof DataView === 'function' ? dataview : [],\n typeof Intl !== 'undefined' ? intlTypes : []\n);\nexport default expObj;\n","/** ImageData is browser / DOM specific (though `node-canvas` has it available on `Canvas`).\n*/\nimport Typeson from 'typeson';\nexport default {\n imagedata: {\n test (x) { return Typeson.toStringTag(x) === 'ImageData'; },\n replace (d) {\n return {\n array: Array.from(d.data), // Ensure `length` gets preserved for revival\n width: d.width,\n height: d.height\n };\n },\n revive (o) {\n return new ImageData(new Uint8ClampedArray(o.array), o.width, o.height);\n }\n }\n};\n","/** ImageBitmap is browser / DOM specific. It also can only work same-domain (or CORS)\n*/\nimport Typeson from 'typeson';\nexport default {\n imagebitmap: {\n test (x) {\n return Typeson.toStringTag(x) === 'ImageBitmap' ||\n // In Node, our polyfill sets the dataset on a canvas element as JSDom no longer allows overriding toStringTag\n (x && x.dataset && x.dataset.toStringTag === 'ImageBitmap');\n },\n replace (bm) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n ctx.drawImage(bm, 0, 0);\n // Although `width` and `height` are part of `ImageBitMap`, these will\n // be auto-created for us when reviving with the data URL (and they are\n // not settable even if they weren't)\n // return {width: bm.width, height: bm.height, dataURL: canvas.toDataURL()};\n return canvas.toDataURL();\n },\n revive (o) {\n /*\n var req = new XMLHttpRequest();\n req.open('GET', o, false); // Sync\n if (req.status !== 200 && req.status !== 0) throw new Error('Bad ImageBitmap access: ' + req.status);\n req.send();\n return req.responseText;\n */\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.onload = function () {\n ctx.drawImage(img, 0, 0);\n };\n img.src = o;\n return canvas; // Works in contexts allowing an ImageBitmap (We might use `OffscreenCanvas.transferToBitmap` when supported)\n },\n reviveAsync (o) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.onload = function () {\n ctx.drawImage(img, 0, 0);\n };\n img.src = o; // o.dataURL;\n return createImageBitmap(canvas); // Returns a promise\n }\n }\n};\n","import Typeson from 'typeson';\nimport file from './file.js';\nexport default {\n file: file.file,\n filelist: {\n test (x) { return Typeson.toStringTag(x) === 'FileList'; },\n replace (fl) {\n const arr = [];\n for (let i = 0; i < fl.length; i++) {\n arr[i] = fl.item(i);\n }\n return arr;\n },\n revive (o) {\n function FileList () {\n this._files = arguments[0];\n this.length = this._files.length;\n }\n FileList.prototype.item = function (index) {\n return this._files[index];\n };\n FileList.prototype[Symbol.toStringTag] = 'FileList';\n return new FileList(o);\n }\n }\n};\n","import Typeson from 'typeson';\n\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nexport default {\n blob: {\n test (x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace (b) { // Sync\n const req = new XMLHttpRequest();\n req.open('GET', URL.createObjectURL(b), false); // Sync\n if (typeof TextEncoder !== 'undefined') { // Using TextDecoder/TextEncoder used too much space\n req.overrideMimeType('text/plain; charset=utf-16le');\n }\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad Blob access: ' + req.status);\n }\n req.send();\n return {\n type: b.type,\n stringContents: req.responseText\n };\n },\n revive ({type, stringContents}) {\n return new Blob([string2arraybuffer(stringContents)], {type});\n },\n replaceAsync (b) {\n return new Typeson.Promise((resolve, reject) => {\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The Blob is closed'));\n return;\n }\n const reader = new FileReader();\n reader.addEventListener('load', () => {\n resolve({\n type: b.type,\n stringContents: reader.result\n });\n });\n reader.addEventListener('error', () => {\n reject(reader.error);\n });\n reader.readAsText(b, 'UTF-16');\n });\n }\n }\n};\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.\n\nvar lookup = new Uint8Array(256);\n\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n\nvar encode = function encode(arraybuffer, byteOffset, length) {\n if (length === null || length === undefined) {\n length = arraybuffer.byteLength; // Needed for Safari\n }\n\n var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari\n length);\n var len = bytes.length;\n var base64 = '';\n\n for (var _i = 0; _i < len; _i += 3) {\n base64 += chars[bytes[_i] >> 2];\n base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4];\n base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6];\n base64 += chars[bytes[_i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n\n return base64;\n};\nvar decode = function decode(base64) {\n var len = base64.length;\n var bufferLength = base64.length * 0.75;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (var _i2 = 0; _i2 < len; _i2 += 4) {\n encoded1 = lookup[base64.charCodeAt(_i2)];\n encoded2 = lookup[base64.charCodeAt(_i2 + 1)];\n encoded3 = lookup[base64.charCodeAt(_i2 + 2)];\n encoded4 = lookup[base64.charCodeAt(_i2 + 3)];\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n\n return arraybuffer;\n};\n\nexport { decode, encode };\n","declare var global;\n\n/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst exportObj = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n if (TypedArray) {\n exportObj[typeName.toLowerCase()+\"2\"] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length}) {\n return {\n buffer,\n byteOffset,\n length\n };\n },\n revive (b64Obj) {\n const {buffer, byteOffset, length} = b64Obj;\n return new TypedArray(buffer, byteOffset, length);\n }\n };\n }\n});\n\nexport default exportObj;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nexport default {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b) {\n return encode(b, 0, b.byteLength);\n },\n revive (b64) {\n const buffer = decode(b64);\n return buffer;\n }\n }\n};\n\n// See also typed-arrays!\n","import Typeson from 'typeson';\nimport StructuredCloning from 'typeson-registry/dist/presets/structured-cloning';\nimport { encode as encodeB64, decode as decodeB64 } from 'base64-arraybuffer-es6';\nimport Dexie from 'dexie';\nimport { readBlobSync, readBlobAsync } from './helpers';\nimport typedArray from './tson-typed-array';\nimport arrayBuffer from './tson-arraybuffer';\n\nexport const TSON = new Typeson().register(StructuredCloning);\n\nconst readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\nlet blobsToAwait: any[] = [];\nlet blobsToAwaitPos = 0;\n\n// Need to patch encapsulateAsync as it does not work as of typeson 5.8.2\n// Also, current version of typespn-registry-1.0.0-alpha.21 does not\n// encapsulate/revive Blobs correctly (fails one of the unit tests in\n// this library (test 'export-format'))\nTSON.register([\n arrayBuffer,\n typedArray, {\n blob2: {\n test(x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace(b) {\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n throw new Error('The Blob is closed');\n }\n if (readBlobsSynchronously) {\n const data = readBlobSync(b, 'binary');\n const base64 = encodeB64(data, 0, data.byteLength);\n return {\n type: b.type,\n data: base64\n }\n } else {\n blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true.\n const result = {\n type: b.type,\n data: {start: blobsToAwaitPos, end: blobsToAwaitPos + b.size}\n }\n console.log(\"b.size: \" + b.size);\n blobsToAwaitPos += b.size;\n return result;\n }\n },\n finalize(b, ba: ArrayBuffer) {\n b.data = encodeB64(ba, 0, ba.byteLength);\n },\n revive ({type, data}) {\n return new Blob([decodeB64(data)], {type});\n }\n }\n }\n]);\n\nTSON.mustFinalize = ()=>blobsToAwait.length > 0;\n\nTSON.finalize = async (items?: any[]) => {\n const allChunks = await readBlobAsync(new Blob(blobsToAwait), 'binary');\n if (items) {\n for (const item of items) {\n // Manually go through all \"blob\" types in the result\n // and lookup the data slice they point at.\n if (item.$types) {\n let types = item.$types;\n const arrayType = types.$;\n if (arrayType) types = types.$;\n for (let keyPath in types) {\n const typeName = types[keyPath];\n const typeSpec = TSON.types[typeName];\n if (typeSpec && typeSpec.finalize) {\n const b = Dexie.getByKeyPath(item, arrayType ? \"$.\" + keyPath : keyPath);\n typeSpec.finalize(b, allChunks.slice(b.start, b.end));\n }\n }\n }\n }\n }\n // Free up memory\n blobsToAwait = [];\n}\n","\nimport Dexie from 'dexie';\nimport { getSchemaString, extractDbSchema } from './helpers';\nimport { DexieExportedTable, DexieExportJsonStructure } from './json-structure';\nimport { TSON } from './tson';\n\nexport interface ExportOptions {\n noTransaction?: boolean;\n numRowsPerChunk?: number;\n prettyJson?: boolean;\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ExportProgress) => boolean;\n}\n\nexport interface ExportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nconst DEFAULT_ROWS_PER_CHUNK = 2000;\n\nexport async function exportDB(db: Dexie, options?: ExportOptions): Promise {\n options = options || {};\n const slices: (string | Blob)[] = [];\n const tables = db.tables.map(table => ({\n name: table.name,\n schema: getSchemaString(table),\n rowCount: 0\n }));\n const {prettyJson} = options!;\n const emptyExport: DexieExportJsonStructure = {\n formatName: \"dexie\",\n formatVersion: 1,\n data: {\n databaseName: db.name,\n databaseVersion: db.verno,\n tables: tables,\n data: []\n }\n };\n \n const {progressCallback} = options!;\n const progress: ExportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: NaN,\n totalTables: db.tables.length\n };\n\n try {\n if (options!.noTransaction) {\n await exportAll();\n } else {\n await db.transaction('r', db.tables, exportAll);\n }\n } finally {\n TSON.finalize(); // Free up mem if error has occurred\n }\n\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n return new Blob(slices,{type: \"text/json\"});\n\n async function exportAll() {\n // Count rows:\n const tablesRowCounts = await Promise.all(db.tables.map(table => table.count()));\n tablesRowCounts.forEach((rowCount, i) => tables[i].rowCount = rowCount);\n progress.totalRows = tablesRowCounts.reduce((p,c)=>p+c);\n\n // Write first JSON slice\n const emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined);\n const posEndDataArray = emptyExportJson.lastIndexOf(']');\n const firstJsonSlice = emptyExportJson.substring(0, posEndDataArray);\n slices.push(firstJsonSlice);\n\n const filter = options!.filter;\n\n for (const {name: tableName} of tables) {\n const table = db.table(tableName);\n const {primKey} = table.schema;\n const inbound = !!primKey.keyPath;\n const LIMIT = options!.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK;\n const emptyTableExport: DexieExportedTable = inbound ? {\n tableName: table.name,\n inbound: true,\n rows: []\n } : {\n tableName: table.name,\n inbound: false,\n rows: []\n };\n let emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) {\n // Increase indentation according to this:\n // {\n // ...\n // data: [\n // ...\n // data: [\n // 123456<---- here\n // ] \n // ]\n // }\n emptyTableExportJson = emptyTableExportJson.split('\\n').join('\\n ');\n }\n const posEndRowsArray = emptyTableExportJson.lastIndexOf(']');\n slices.push(emptyTableExportJson.substring(0, posEndRowsArray));\n let lastKey: any = null;\n let lastNumRows = 0;\n let mayHaveMoreRows = true;\n while (mayHaveMoreRows) {\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const chunkedCollection = lastKey == null ?\n table.limit(LIMIT) :\n table.where(':id').above(lastKey).limit(LIMIT);\n\n const values = await chunkedCollection.toArray();\n\n if (values.length === 0) break;\n\n if (lastKey != null && lastNumRows > 0) {\n // Not initial chunk. Must add a comma:\n slices.push(\",\");\n if (prettyJson) {\n slices.push(\"\\n \");\n }\n }\n\n mayHaveMoreRows = values.length === LIMIT;\n \n if (inbound) {\n const filteredValues = filter ?\n values.filter(value => filter(tableName, value)) :\n values;\n\n const tsonValues = filteredValues.map(value => TSON.encapsulate(value));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonValues));\n }\n\n let json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = filteredValues.length;\n lastKey = values.length > 0 ?\n Dexie.getByKeyPath(values[values.length -1], primKey.keyPath as string) :\n null;\n } else {\n const keys = await chunkedCollection.primaryKeys();\n let keyvals = keys.map((key, i) => [key, values[i]]);\n if (filter) keyvals = keyvals.filter(([key, value]) => filter(tableName, value, key));\n\n const tsonTuples = keyvals.map(tuple => TSON.encapsulate(tuple));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonTuples));\n }\n\n let json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = keyvals.length;\n lastKey = keys.length > 0 ?\n keys[keys.length - 1] :\n null;\n }\n progress.completedRows += values.length;\n }\n slices.push(emptyTableExportJson.substr(posEndRowsArray)); // \"]}\"\n progress.completedTables += 1;\n if (progress.completedTables < progress.totalTables) {\n slices.push(\",\");\n }\n }\n slices.push(emptyExportJson.substr(posEndDataArray));\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n }\n}\n","export const VERSION = 1;\n\nexport interface DexieExportJsonStructure {\n formatName: 'dexie';\n formatVersion: typeof VERSION;\n data: {\n databaseName: string;\n databaseVersion: number;\n tables: Array<{\n name: string;\n schema: string;\n rowCount: number;\n }>;\n data: Array<{\n tableName: string;\n inbound: boolean;\n rows: any[];\n }>;\n }\n}\n\nexport type DexieExportedDatabase = DexieExportJsonStructure[\"data\"];\nexport type DexieExportedTable = DexieExportedDatabase[\"data\"][number];\n","module.exports = {Stream: function(){}};\n\n",";(function (clarinet) {\n \"use strict\";\n\n // non node-js needs to set clarinet debug on root\n var env =(typeof process === 'object' && process.env)\n ? process.env\n : self;\n\n clarinet.parser = function (opt) { return new CParser(opt);};\n clarinet.CParser = CParser;\n clarinet.CStream = CStream;\n clarinet.createStream = createStream;\n clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024;\n clarinet.DEBUG = (env.CDEBUG==='debug');\n clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info');\n clarinet.EVENTS =\n [ \"value\"\n , \"string\"\n , \"key\"\n , \"openobject\"\n , \"closeobject\"\n , \"openarray\"\n , \"closearray\"\n , \"error\"\n , \"end\"\n , \"ready\"\n ];\n\n var buffers = {\n textNode: undefined,\n numberNode: \"\"\n }\n , streamWraps = clarinet.EVENTS.filter(function (ev) {\n return ev !== \"error\" && ev !== \"end\";\n })\n , S = 0\n , Stream\n ;\n\n clarinet.STATE =\n { BEGIN : S++\n , VALUE : S++ // general stuff\n , OPEN_OBJECT : S++ // {\n , CLOSE_OBJECT : S++ // }\n , OPEN_ARRAY : S++ // [\n , CLOSE_ARRAY : S++ // ]\n , TEXT_ESCAPE : S++ // \\ stuff\n , STRING : S++ // \"\"\n , BACKSLASH : S++\n , END : S++ // No more stack\n , OPEN_KEY : S++ // , \"a\"\n , CLOSE_KEY : S++ // :\n , TRUE : S++ // r\n , TRUE2 : S++ // u\n , TRUE3 : S++ // e\n , FALSE : S++ // a\n , FALSE2 : S++ // l\n , FALSE3 : S++ // s\n , FALSE4 : S++ // e\n , NULL : S++ // u\n , NULL2 : S++ // l\n , NULL3 : S++ // l\n , NUMBER_DECIMAL_POINT : S++ // .\n , NUMBER_DIGIT : S++ // [0-9]\n };\n\n for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_;\n\n // switcharoo\n S = clarinet.STATE;\n\n const Char = {\n tab : 0x09, // \\t\n lineFeed : 0x0A, // \\n\n carriageReturn : 0x0D, // \\r\n space : 0x20, // \" \"\n\n doubleQuote : 0x22, // \"\n plus : 0x2B, // +\n comma : 0x2C, // ,\n minus : 0x2D, // -\n period : 0x2E, // .\n\n _0 : 0x30, // 0\n _9 : 0x39, // 9\n\n colon : 0x3A, // :\n\n E : 0x45, // E\n\n openBracket : 0x5B, // [\n backslash : 0x5C, // \\\n closeBracket : 0x5D, // ]\n\n a : 0x61, // a\n b : 0x62, // b\n e : 0x65, // e \n f : 0x66, // f\n l : 0x6C, // l\n n : 0x6E, // n\n r : 0x72, // r\n s : 0x73, // s\n t : 0x74, // t\n u : 0x75, // u\n\n openBrace : 0x7B, // {\n closeBrace : 0x7D, // }\n }\n\n if (!Object.create) {\n Object.create = function (o) {\n function f () { this[\"__proto__\"] = o; }\n f.prototype = o;\n return new f;\n };\n }\n\n if (!Object.getPrototypeOf) {\n Object.getPrototypeOf = function (o) {\n return o[\"__proto__\"];\n };\n }\n\n if (!Object.keys) {\n Object.keys = function (o) {\n var a = [];\n for (var i in o) if (o.hasOwnProperty(i)) a.push(i);\n return a;\n };\n }\n\n function checkBufferLength (parser) {\n var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10)\n , maxActual = 0\n ;\n for (var buffer in buffers) {\n var len = parser[buffer] === undefined ? 0 : parser[buffer].length;\n if (len > maxAllowed) {\n switch (buffer) {\n case \"text\":\n closeText(parser);\n break;\n\n default:\n error(parser, \"Max buffer length exceeded: \"+ buffer);\n }\n }\n maxActual = Math.max(maxActual, len);\n }\n parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual)\n + parser.position;\n }\n\n function clearBuffers (parser) {\n for (var buffer in buffers) {\n parser[buffer] = buffers[buffer];\n }\n }\n\n var stringTokenPattern = /[\\\\\"\\n]/g;\n\n function CParser (opt) {\n if (!(this instanceof CParser)) return new CParser (opt);\n\n var parser = this;\n clearBuffers(parser);\n parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH;\n parser.q = parser.c = parser.p = \"\";\n parser.opt = opt || {};\n parser.closed = parser.closedRoot = parser.sawRoot = false;\n parser.tag = parser.error = null;\n parser.state = S.BEGIN;\n parser.stack = new Array();\n // mostly just for error reporting\n parser.position = parser.column = 0;\n parser.line = 1;\n parser.slashed = false;\n parser.unicodeI = 0;\n parser.unicodeS = null;\n parser.depth = 0;\n emit(parser, \"onready\");\n }\n\n CParser.prototype =\n { end : function () { end(this); }\n , write : write\n , resume : function () { this.error = null; return this; }\n , close : function () { return this.write(null); }\n };\n\n try { Stream = require(\"stream\").Stream; }\n catch (ex) { Stream = function () {}; }\n\n function createStream (opt) { return new CStream(opt); }\n\n function CStream (opt) {\n if (!(this instanceof CStream)) return new CStream(opt);\n\n this._parser = new CParser(opt);\n this.writable = true;\n this.readable = true;\n\n //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error\n this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary\n this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read\n this.temp_buffs = { \"2\": new Buffer(2), \"3\": new Buffer(3), \"4\": new Buffer(4) }; // for rebuilding chars split before boundary is reached\n this.string = '';\n\n var me = this;\n Stream.apply(me);\n\n this._parser.onend = function () { me.emit(\"end\"); };\n this._parser.onerror = function (er) {\n me.emit(\"error\", er);\n me._parser.error = null;\n };\n\n streamWraps.forEach(function (ev) {\n Object.defineProperty(me, \"on\" + ev,\n { get : function () { return me._parser[\"on\" + ev]; }\n , set : function (h) {\n if (!h) {\n me.removeAllListeners(ev);\n me._parser[\"on\"+ev] = h;\n return h;\n }\n me.on(ev, h);\n }\n , enumerable : true\n , configurable : false\n });\n });\n }\n\n CStream.prototype = Object.create(Stream.prototype,\n { constructor: { value: CStream } });\n\n CStream.prototype.write = function (data) {\n data = new Buffer(data);\n for (var i = 0; i < data.length; i++) {\n var n = data[i];\n\n // check for carry over of a multi byte char split between data chunks\n // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration\n if (this.bytes_remaining > 0) {\n for (var j = 0; j < this.bytes_remaining; j++) {\n this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j];\n }\n this.string = this.temp_buffs[this.bytes_in_sequence].toString();\n this.bytes_in_sequence = this.bytes_remaining = 0;\n\n // move iterator forward by number of byte read during sequencing\n i = i + j - 1;\n\n // pass data to parser and move forward to parse rest of data\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n\n // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time\n if (this.bytes_remaining === 0 && n >= 128) {\n if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;\n if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;\n if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;\n if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split\n\n for (var k = 0; k <= (data.length - 1 - i); k++) {\n this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk\n }\n this.bytes_remaining = (i + this.bytes_in_sequence) - data.length;\n\n // immediately return as we need another chunk to sequence the character\n return true;\n } else {\n this.string = data.slice(i, (i + this.bytes_in_sequence)).toString();\n i = i + this.bytes_in_sequence - 1;\n\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n }\n\n // is there a range of characters that are immediately parsable?\n for (var p = i; p < data.length; p++) {\n if (data[p] >= 128) break;\n }\n this.string = data.slice(i, p).toString();\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n i = p - 1;\n\n // handle any remaining characters using multibyte logic\n continue;\n }\n };\n\n CStream.prototype.end = function (chunk) {\n if (chunk && chunk.length) this._parser.write(chunk.toString());\n this._parser.end();\n return true;\n };\n\n CStream.prototype.on = function (ev, handler) {\n var me = this;\n if (!me._parser[\"on\"+ev] && streamWraps.indexOf(ev) !== -1) {\n me._parser[\"on\"+ev] = function () {\n var args = arguments.length === 1 ? [arguments[0]]\n : Array.apply(null, arguments);\n args.splice(0, 0, ev);\n me.emit.apply(me, args);\n };\n }\n return Stream.prototype.on.call(me, ev, handler);\n };\n\n CStream.prototype.destroy = function () {\n clearBuffers(this._parser);\n this.emit(\"close\");\n };\n\n function emit(parser, event, data) {\n if(clarinet.INFO) console.log('-- emit', event, data);\n if (parser[event]) parser[event](data);\n }\n\n function emitNode(parser, event, data) {\n closeValue(parser);\n emit(parser, event, data);\n }\n\n function closeValue(parser, event) {\n parser.textNode = textopts(parser.opt, parser.textNode);\n if (parser.textNode !== undefined) {\n emit(parser, (event ? event : \"onvalue\"), parser.textNode);\n }\n parser.textNode = undefined;\n }\n\n function closeNumber(parser) {\n if (parser.numberNode)\n emit(parser, \"onvalue\", parseFloat(parser.numberNode));\n parser.numberNode = \"\";\n }\n\n function textopts (opt, text) {\n if (text === undefined) {\n return text;\n }\n if (opt.trim) text = text.trim();\n if (opt.normalize) text = text.replace(/\\s+/g, \" \");\n return text;\n }\n\n function error (parser, er) {\n closeValue(parser);\n er += \"\\nLine: \"+parser.line+\n \"\\nColumn: \"+parser.column+\n \"\\nChar: \"+parser.c;\n er = new Error(er);\n parser.error = er;\n emit(parser, \"onerror\", er);\n return parser;\n }\n\n function end(parser) {\n if (parser.state !== S.VALUE || parser.depth !== 0)\n error(parser, \"Unexpected end\");\n\n closeValue(parser);\n parser.c = \"\";\n parser.closed = true;\n emit(parser, \"onend\");\n CParser.call(parser, parser.opt);\n return parser;\n }\n\n function isWhitespace(c) {\n return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab;\n }\n\n function write (chunk) {\n var parser = this;\n if (this.error) throw this.error;\n if (parser.closed) return error(parser,\n \"Cannot write after close. Assign an onready handler.\");\n if (chunk === null) return end(parser);\n var i = 0, c = chunk.charCodeAt(0), p = parser.p;\n if (clarinet.DEBUG) console.log('write -> [' + chunk + ']');\n while (c) {\n p = c;\n parser.c = c = chunk.charCodeAt(i++);\n // if chunk doesnt have next, like streaming char by char\n // this way we need to check if previous is really previous\n // if not we need to reset to what the parser says is the previous\n // from buffer\n if(p !== c ) parser.p = p;\n else p = parser.p;\n\n if(!c) break;\n\n if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]);\n parser.position ++;\n if (c === Char.lineFeed) {\n parser.line ++;\n parser.column = 0;\n } else parser.column ++;\n switch (parser.state) {\n\n case S.BEGIN:\n if (c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if (!isWhitespace(c))\n error(parser, \"Non-whitespace before {[.\");\n continue;\n\n case S.OPEN_KEY:\n case S.OPEN_OBJECT:\n if (isWhitespace(c)) continue;\n if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY);\n else {\n if(c === Char.closeBrace) {\n emit(parser, 'onopenobject');\n this.depth++;\n emit(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else parser.stack.push(S.CLOSE_OBJECT);\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else error(parser, \"Malformed object key should start with \\\"\");\n continue;\n\n case S.CLOSE_KEY:\n case S.CLOSE_OBJECT:\n if (isWhitespace(c)) continue;\n var event = (parser.state === S.CLOSE_KEY) ? 'key' : 'object';\n if(c === Char.colon) {\n if(parser.state === S.CLOSE_OBJECT) {\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser, 'onopenobject');\n this.depth++;\n } else closeValue(parser, 'onkey');\n parser.state = S.VALUE;\n } else if (c === Char.closeBrace) {\n emitNode(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if(c === Char.comma) {\n if(parser.state === S.CLOSE_OBJECT)\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser);\n parser.state = S.OPEN_KEY;\n } else error(parser, 'Bad object');\n continue;\n\n case S.OPEN_ARRAY: // after an array there always a value\n case S.VALUE:\n if (isWhitespace(c)) continue;\n if(parser.state===S.OPEN_ARRAY) {\n emit(parser, 'onopenarray');\n this.depth++;\n parser.state = S.VALUE;\n if(c === Char.closeBracket) {\n emit(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else {\n parser.stack.push(S.CLOSE_ARRAY);\n }\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if(c === Char.t) parser.state = S.TRUE;\n else if(c === Char.f) parser.state = S.FALSE;\n else if(c === Char.n) parser.state = S.NULL;\n else if(c === Char.minus) { // keep and continue\n parser.numberNode += \"-\";\n } else if(Char._0 <= c && c <= Char._9) {\n parser.numberNode += String.fromCharCode(c);\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, \"Bad value\");\n continue;\n\n case S.CLOSE_ARRAY:\n if(c === Char.comma) {\n parser.stack.push(S.CLOSE_ARRAY);\n closeValue(parser, 'onvalue');\n parser.state = S.VALUE;\n } else if (c === Char.closeBracket) {\n emitNode(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if (isWhitespace(c))\n continue;\n else error(parser, 'Bad array');\n continue;\n\n case S.STRING:\n if (parser.textNode === undefined) {\n parser.textNode = \"\";\n }\n\n // thanks thejh, this is an about 50% performance improvement.\n var starti = i-1\n , slashed = parser.slashed\n , unicodeI = parser.unicodeI\n ;\n STRING_BIGLOOP: while (true) {\n if (clarinet.DEBUG)\n console.log(i,c,clarinet.STATE[parser.state]\n ,slashed);\n // zero means \"no unicode active\". 1-4 mean \"parse some more\". end after 4.\n while (unicodeI > 0) {\n parser.unicodeS += String.fromCharCode(c);\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (unicodeI === 4) {\n // TODO this might be slow? well, probably not used too often anyway\n parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16));\n unicodeI = 0;\n starti = i-1;\n } else {\n unicodeI++;\n }\n // we can just break here: no stuff we skipped that still has to be sliced out or so\n if (!c) break STRING_BIGLOOP;\n }\n if (c === Char.doubleQuote && !slashed) {\n parser.state = parser.stack.pop() || S.VALUE;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n if (c === Char.backslash && !slashed) {\n slashed = true;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (!c) break;\n }\n if (slashed) {\n slashed = false;\n if (c === Char.n) { parser.textNode += '\\n'; }\n else if (c === Char.r) { parser.textNode += '\\r'; }\n else if (c === Char.t) { parser.textNode += '\\t'; }\n else if (c === Char.f) { parser.textNode += '\\f'; }\n else if (c === Char.b) { parser.textNode += '\\b'; }\n else if (c === Char.u) {\n // \\uxxxx. meh!\n unicodeI = 1;\n parser.unicodeS = '';\n } else {\n parser.textNode += String.fromCharCode(c);\n }\n c = chunk.charCodeAt(i++);\n parser.position++;\n starti = i-1;\n if (!c) break;\n else continue;\n }\n\n stringTokenPattern.lastIndex = i;\n var reResult = stringTokenPattern.exec(chunk);\n if (reResult === null) {\n i = chunk.length+1;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n i = reResult.index+1;\n c = chunk.charCodeAt(reResult.index);\n if (!c) {\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n }\n parser.slashed = slashed;\n parser.unicodeI = unicodeI;\n continue;\n\n case S.TRUE:\n if (c === Char.r) parser.state = S.TRUE2;\n else error(parser, 'Invalid true started with t'+ c);\n continue;\n\n case S.TRUE2:\n if (c === Char.u) parser.state = S.TRUE3;\n else error(parser, 'Invalid true started with tr'+ c);\n continue;\n\n case S.TRUE3:\n if(c === Char.e) {\n emit(parser, \"onvalue\", true);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid true started with tru'+ c);\n continue;\n\n case S.FALSE:\n if (c === Char.a) parser.state = S.FALSE2;\n else error(parser, 'Invalid false started with f'+ c);\n continue;\n\n case S.FALSE2:\n if (c === Char.l) parser.state = S.FALSE3;\n else error(parser, 'Invalid false started with fa'+ c);\n continue;\n\n case S.FALSE3:\n if (c === Char.s) parser.state = S.FALSE4;\n else error(parser, 'Invalid false started with fal'+ c);\n continue;\n\n case S.FALSE4:\n if (c === Char.e) {\n emit(parser, \"onvalue\", false);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid false started with fals'+ c);\n continue;\n\n case S.NULL:\n if (c === Char.u) parser.state = S.NULL2;\n else error(parser, 'Invalid null started with n'+ c);\n continue;\n\n case S.NULL2:\n if (c === Char.l) parser.state = S.NULL3;\n else error(parser, 'Invalid null started with nu'+ c);\n continue;\n\n case S.NULL3:\n if(c === Char.l) {\n emit(parser, \"onvalue\", null);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid null started with nul'+ c);\n continue;\n\n case S.NUMBER_DECIMAL_POINT:\n if(c === Char.period) {\n parser.numberNode += \".\";\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, 'Leading zero not followed by .');\n continue;\n\n case S.NUMBER_DIGIT:\n if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c);\n else if (c === Char.period) {\n if(parser.numberNode.indexOf('.')!==-1)\n error(parser, 'Invalid number has two dots');\n parser.numberNode += \".\";\n } else if (c === Char.e || c === Char.E) {\n if(parser.numberNode.indexOf('e')!==-1 ||\n parser.numberNode.indexOf('E')!==-1 )\n error(parser, 'Invalid number has two exponential');\n parser.numberNode += \"e\";\n } else if (c === Char.plus || c === Char.minus) {\n if(!(p === Char.e || p === Char.E))\n error(parser, 'Invalid symbol in number');\n parser.numberNode += String.fromCharCode(c);\n } else {\n closeNumber(parser);\n i--; // go back one\n parser.state = parser.stack.pop() || S.VALUE;\n }\n continue;\n\n default:\n error(parser, \"Unknown state: \" + parser.state);\n }\n }\n if (parser.position >= parser.bufferCheckPosition)\n checkBufferLength(parser);\n return parser;\n }\n\n})(typeof exports === \"undefined\" ? clarinet = {} : exports);\n","import clarinet from 'clarinet';\nimport { readBlobAsync, readBlobSync } from './helpers';\n\nexport interface JsonStream {\n pullAsync(numBytes: number): Promise>;\n pullSync(numBytes: number): Partial;\n done(): boolean;\n eof(): boolean;\n result: Partial;\n}\n\nexport function JsonStream(blob: Blob): JsonStream {\n let pos = 0;\n const parser = JsonParser(true);\n\n const rv = {\n async pullAsync(numBytes: number): Promise> {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = await readBlobAsync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n pullSync(numBytes: number): Partial {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = readBlobSync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n done() {\n return parser.done();\n },\n eof() {\n return pos >= blob.size;\n },\n result: {}\n }\n\n return rv;\n}\n\n\nexport function JsonParser (allowPartial: boolean) {\n const parser = (clarinet as any).parser();\n let level = 0;\n let result: any;\n const stack: any[][] = [];\n let obj: any;\n let key: string | null;\n let done = false;\n let array = false;\n\n parser.onopenobject = newKey => {\n const newObj = {};\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n key = newKey;\n array = false;\n ++level;\n }\n parser.onkey = newKey => key = newKey;\n parser.onvalue = value => array ? obj.push(value) : obj[key!] = value;\n parser.oncloseobject = ()=>{\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n parser.onopenarray = () => {\n const newObj = [];\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n array = true;\n key = null;\n ++level;\n }\n parser.onclosearray = () => {\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n\n return {\n write(jsonPart: string) {\n parser.write(jsonPart);\n return result;\n },\n done() {\n return done;\n }\n }\n}\n","import Dexie from 'dexie';\nimport { extractDbSchema } from './helpers';\nimport { DexieExportJsonStructure, VERSION } from './json-structure';\nimport { TSON } from './tson';\nimport { JsonStream } from './json-stream';\n\nexport interface StaticImportOptions {\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nexport interface ImportOptions extends StaticImportOptions {\n acceptMissingTables?: boolean;\n acceptVersionDiff?: boolean;\n acceptNameDiff?: boolean;\n acceptChangedPrimaryKey?: boolean;\n overwriteValues?: boolean;\n clearTablesBeforeImport?: boolean;\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nconst DEFAULT_KILOBYTES_PER_CHUNK = 1024;\n\nexport interface ImportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nexport async function importDB(exportedData: Blob | JsonStream, options?: StaticImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const stream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n const dbExport = stream.result.data!;\n const db = new Dexie(dbExport.databaseName);\n db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport));\n await importInto(db, stream, options);\n return db;\n}\n\nexport async function importInto(db: Dexie, exportedData: Blob | JsonStream, options?: ImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const jsonStream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n let dbExportFile = jsonStream.result;\n const readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\n const dbExport = dbExportFile.data!;\n\n if (!options!.acceptNameDiff && db.name !== dbExport.databaseName)\n throw new Error(`Name differs. Current database name is ${db.name} but export is ${dbExport.databaseName}`);\n if (!options!.acceptVersionDiff && db.verno !== dbExport.databaseVersion) {\n // Possible feature: Call upgraders in some isolated way if this happens... ?\n throw new Error(`Database version differs. Current database is in version ${db.verno} but export is ${dbExport.databaseVersion}`);\n }\n \n const { progressCallback } = options;\n const progress: ImportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: dbExport.tables.reduce((p, c) => p + c.rowCount, 0),\n totalTables: dbExport.tables.length\n };\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n\n if (options.noTransaction) {\n await importAll();\n } else {\n await db.transaction('rw', db.tables, importAll);\n } \n\n async function importAll () {\n do {\n for (const tableExport of dbExport.data) {\n if (!tableExport.rows) break; // Need to pull more!\n if (!(tableExport.rows as any).incomplete && tableExport.rows.length === 0)\n continue;\n\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const tableName = tableExport.tableName;\n const table = db.table(tableName);\n const tableSchemaStr = dbExport.tables.filter(t => t.name === tableName)[0].schema;\n if (!table) {\n if (!options!.acceptMissingTables)\n throw new Error(`Exported table ${tableExport.tableName} is missing in installed database`);\n else\n continue;\n }\n if (!options!.acceptChangedPrimaryKey &&\n tableSchemaStr.split(',')[0] != table.schema.primKey.src) {\n throw new Error(`Primary key differs for table ${tableExport.tableName}. `);\n }\n\n const sourceRows = tableExport.rows\n \n // Our rows may be partial, so we need to ensure each one is completed before using it\n const rows: any[] = [];\n for(let i = 0; i < sourceRows.length; i++) {\n const obj = sourceRows[i];\n if (!obj.incomplete) {\n rows.push(TSON.revive(obj));\n } else {\n break;\n }\n }\n\n const filter = options!.filter;\n const filteredRows = filter ?\n tableExport.inbound ?\n rows.filter(value => filter(tableName, value)) :\n rows.filter(([key, value]) => filter(tableName, value, key)) :\n rows;\n const [keys, values] = tableExport.inbound ?\n [undefined, filteredRows] :\n [filteredRows.map(row=>row[0]), rows.map(row=>row[1])];\n\n if (options!.clearTablesBeforeImport) {\n await table.clear();\n }\n if (options!.overwriteValues)\n await table.bulkPut(values, keys);\n else\n await table.bulkAdd(values, keys);\n \n progress.completedRows += rows.length;\n if (!(rows as any).incomplete) {\n progress.completedTables += 1;\n }\n sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance.\n }\n\n // Avoid unnescessary loops in \"for (const tableExport of dbExport.data)\" \n while (dbExport.data.length > 0 && dbExport.data[0].rows && !(dbExport.data[0].rows as any).incomplete) {\n // We've already imported all rows from the first table. Delete its occurrence\n dbExport.data.splice(0, 1); \n }\n if (!jsonStream.done() && !jsonStream.eof()) {\n // Pull some more (keeping transaction alive)\n if (readBlobsSynchronously) {\n // If we can pull from blob synchronically, we don't have to\n // keep transaction alive using Dexie.waitFor().\n // This will only be possible in workers.\n jsonStream.pullSync(CHUNK_SIZE);\n } else {\n await Dexie.waitFor(jsonStream.pullAsync(CHUNK_SIZE));\n }\n } else break;\n } while (true)\n }\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n}\n\nasync function loadUntilWeGotEnoughData(exportedData: Blob | JsonStream, CHUNK_SIZE: number): Promise> {\n const stream = ('slice' in exportedData ?\n JsonStream(exportedData) :\n exportedData);\n\n while (!stream.eof()) {\n await stream.pullAsync(CHUNK_SIZE);\n\n if (stream.result.data && stream.result.data!.data)\n break;\n }\n const dbExportFile = stream.result;\n if (!dbExportFile || dbExportFile.formatName != \"dexie\")\n throw new Error(`Given file is not a dexie export`);\n if (dbExportFile.formatVersion! > VERSION) {\n throw new Error(`Format version ${dbExportFile.formatVersion} not supported`);\n }\n if (!dbExportFile.data!) {\n throw new Error(`No data in export file`);\n }\n if (!dbExportFile.data!.databaseName) {\n throw new Error(`Missing databaseName in export file`);\n }\n if (!dbExportFile.data!.databaseVersion) {\n throw new Error(`Missing databaseVersion in export file`);\n }\n if (!dbExportFile.data!.tables) {\n throw new Error(`Missing tables in export file`);\n }\n return stream; \n}\n","import Dexie from 'dexie';\nimport { ExportOptions, exportDB } from './export';\nimport { importDB, ImportOptions, importInto, StaticImportOptions } from './import';\n\nexport { exportDB, ExportOptions};\nexport { importDB, importInto, ImportOptions};\n\n//\n// Extend Dexie interface (typescript-wise)\n//\ndeclare module 'dexie' {\n // Extend methods on db\n interface Dexie {\n export(options?: ExportOptions): Promise;\n import(blob: Blob, options?: ImportOptions): Promise;\n }\n interface DexieConstructor {\n import(blob: Blob, options?: StaticImportOptions): Promise;\n }\n}\n\n//\n// Extend Dexie interface (runtime wise)\n//\n\nDexie.prototype.export = function (this: Dexie, options?: ExportOptions) {\n return exportDB(this, options);\n};\nDexie.prototype.import = function (this: Dexie, blob: Blob, options?: ImportOptions) {\n return importInto(this, blob, options);\n};\nDexie.import = (blob: Blob, options?: StaticImportOptions) => importDB(blob, options);\n\nexport default ()=>{\n throw new Error(\"This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options.\")\n};\n"],"names":["this","keys","Object","isArray","Array","toString","getProto","getPrototypeOf","hasOwn","hasOwnProperty","fnToString","internalStateObjPropsToIgnore","isThenable","v","catchCheck","Typeson","isObject","then","catch","toStringTag","val","call","slice","hasConstructorOf","a","b","proto","Ctor","constructor","isPlainObject","options","plainObjectReplacers","nonplainObjectReplacers","revivers","regTypes","types","stringify","obj","replacer","space","opts","assign","stringification","encapsulated","encapsulate","JSON","res","stringifySync","throwOnBadSyncType","sync","stringifyAsync","parse","text","reviver","revive","parseSync","parseAsync","specialTypeNames","stateObj","returnTypeNames","rootTypeName","iterateNone","refObjs","cyclic","encapsulateObserver","ret","_encapsulate","promisesDataRoot","finish","typeNames","values","length","getJSONType","Set","$types","$","TypeError","Promise","resolve","checkPromises","promisesData","all","map","pd","p","promResults","promResult","newPromisesData","prData","splice","keyPath","parentObj","key","detectedType","encaps","isTypesonPromise","TypesonPromise","encaps2","_adaptBuiltinStateObjectProperties","ownKeysObj","cb","vals","prop","tmp","forEach","i","keypath","value","resolvingTypesonPromise","observerData","$typeof","runObserver","type","undefined","string","boolean","number","isNaN","Infinity","replace","replaced","iterateIn","iterateUnsetNumeric","refIndex","indexOf","refKeys","push","isPlainObj","isArr","clone","ownKeys","kp","escapeKeyPathComponent","endIterateIn","end","endIterateOwn","vl","endIterateUnsetNumeric","plainObject","replacers","test","existing","concat","replaceAsync","replacing","typeDetected","encapsulateSync","encapsulateAsync","ignore$Types","keyPathResolutions","_revive","target","Undefined","getByKeyPath","substr","reduce","Error","reviveAsync","reviveSync","register","typeSpecSets","R","typeSpec","typeId","JSON_TYPES","includes","spec","testPlainObjects","existingReplacer","filter","r","Class","x","create","prototype","replacerObj","bind","start","fallback","reviverObj","t","s","k","keyPathComponent","unescapeKeyPathComponent","period","innerObj","f","onFulfilled","onRejected","typesonResolve","typesonReject","reject","meth","promArr","prom","isUserObject","n","String","Boolean","Number","NaN","date","time","getTime","Date","rexp","source","global","ignoreCase","multiline","sticky","unicode","flags","RegExp","from","entries","Map","set","chars","lookup","Uint8Array","charCodeAt","encode","arraybuffer","byteOffset","bytes","len","base64","substring","decode","bufferLength","encoded1","encoded2","encoded3","encoded4","ArrayBuffer","buffers","index","b64","buffer","_global","self","exportObj","typeName","arrType","TypedArray","toLowerCase","b64Obj","encoded","byteLength","DataView","Intl","Collator","c","resolvedOptions","locale","DateTimeFormat","dtf","NumberFormat","nf","string2arraybuffer","str","array","Uint16Array","req","XMLHttpRequest","open","URL","createObjectURL","TextEncoder","overrideMimeType","status","send","responseText","name","lastModified","stringContents","File","isClosed","reader","FileReader","addEventListener","result","error","readAsText","userObject","presetUndefined","primitiveObjects","specialNumbers","regexp","d","data","width","height","o","ImageData","Uint8ClampedArray","dataset","bm","canvas","document","createElement","getContext","drawImage","toDataURL","ctx","img","onload","src","createImageBitmap","file","fl","arr","item","FileList","_files","arguments","Symbol","Blob","typedArrays","dataview","intlTypes","StructuredCloning","typedArray","encodeB64","decodeB64","require$$0","clarinet"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;AAcA,AAoDA;AACA,AAAO,SAAS,SAAS,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE;IACzD,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,EAAE,UAAU,OAAO,EAAE,MAAM,EAAE;QACvD,SAAS,SAAS,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE;QAC3F,SAAS,QAAQ,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE;QAC9F,SAAS,IAAI,CAAC,MAAM,EAAE,EAAE,MAAM,CAAC,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,UAAU,OAAO,EAAE,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,EAAE;QAC/I,IAAI,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC,KAAK,CAAC,OAAO,EAAE,UAAU,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,C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Ae;IACb,MAAM,IAAI,KAAK,CAAC,kHAAkH,CAAC,CAAA;CACpI,EAAC;;;;;"} \ 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..9185420c2 --- /dev/null +++ b/dist/dexie.d.ts @@ -0,0 +1,749 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 3.0.2, Fri Jul 31 2020 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + export interface IndexSpec { + name: string; + keyPath: string | Array | undefined; + unique: boolean | undefined; + multi: boolean | undefined; + auto: boolean | undefined; + compound: boolean | undefined; + src: string; +} +export interface TableSchema { + name: string; + primKey: IndexSpec; + indexes: IndexSpec[]; + mappedClass: Function; + idxByName: {[name: string]: IndexSpec}; + readHook?: (x:any) => any +} +export type IndexableTypePart = +string | number | Date | ArrayBuffer | ArrayBufferView | DataView | Array>; +export type IndexableTypeArray = Array; +export type IndexableTypeArrayReadonly = ReadonlyArray; +export type IndexableType = IndexableTypePart | IndexableTypeArrayReadonly; +export interface DexieEvent { + subscribers: Function[]; + fire(...args:any[]): any; + subscribe(fn: (...args:any[]) => any): void; + unsubscribe(fn: (...args:any[]) => any): void; +} +export interface DexieEventSet { + (eventName: string): DexieEvent; // To be able to unsubscribe. + + addEventType ( + eventName: string, + chainFunction?: (f1:Function,f2:Function)=>Function, + defaultFunction?: Function): DexieEvent; + addEventType ( + events: {[eventName:string]: ('asap' | [(f1:Function,f2:Function)=>Function, Function])}) + : DexieEvent; +} +export type TransactionMode = 'readonly' | 'readwrite' | 'r' | 'r!' | 'r?' | 'rw' | 'rw!' | 'rw?'; +export interface PromiseExtendedConstructor extends PromiseConstructor { + readonly prototype: PromiseExtended; + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): PromiseExtended; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): PromiseExtended<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): PromiseExtended<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): PromiseExtended<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): PromiseExtended<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): PromiseExtended<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): PromiseExtended<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): PromiseExtended<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): PromiseExtended<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): PromiseExtended<[T1, T2]>; + all(values: (T | PromiseLike)[]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): PromiseExtended; + race(values: [T1 | PromiseLike, T2 | PromiseLike]): PromiseExtended; + race(values: (T | PromiseLike)[]): PromiseExtended; + reject(reason: any): PromiseExtended; + reject(reason: any): PromiseExtended; + resolve(value: T | PromiseLike): PromiseExtended; + resolve(): PromiseExtended; +} +/** The interface of Dexie.Promise, which basically extends standard Promise with methods: + * + * finally() - also subject for standardization + * timeout() - set a completion timeout + * catch(ErrorClass, handler) - java style error catching + * catch(errorName, handler) - cross-domain safe type error catching (checking error.name instead of instanceof) + * + */ +export interface PromiseExtended extends Promise { + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseExtended; + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseExtended; + catch(ErrorConstructor: Function, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseExtended; + catch(errorName: string, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseExtended; + finally(onFinally?: () => U | PromiseLike): PromiseExtended; + timeout (ms: number, msg?: string): PromiseExtended; +} +export type ThenShortcut = (value: T) => TResult | PromiseLike; +export interface Collection { + //db: Database; + and(filter: (x: T) => boolean): Collection; + clone(props?: Object): Collection; + count(): PromiseExtended; + count(thenShortcut: ThenShortcut): PromiseExtended; + distinct(): Collection; + each(callback: (obj: T, cursor: {key: IndexableType, primaryKey: TKey}) => any): PromiseExtended; + eachKey(callback: (key: IndexableType, cursor: {key: IndexableType, primaryKey: TKey}) => any): PromiseExtended; + eachPrimaryKey(callback: (key: TKey, cursor: {key: IndexableType, primaryKey: TKey}) => any): PromiseExtended; + eachUniqueKey(callback: (key: IndexableType, cursor: {key: IndexableType, primaryKey: TKey}) => any): PromiseExtended; + filter(filter: (x: T) => boolean): Collection; + first(): PromiseExtended; + first(thenShortcut: ThenShortcut): PromiseExtended; + keys(): PromiseExtended; + keys(thenShortcut: ThenShortcut): PromiseExtended; + primaryKeys(): PromiseExtended; + primaryKeys(thenShortcut: ThenShortcut): PromiseExtended; + last(): PromiseExtended; + last(thenShortcut: ThenShortcut): PromiseExtended; + limit(n: number): Collection; + offset(n: number): Collection; + or(indexOrPrimayKey: string): WhereClause; + raw(): Collection; + reverse(): Collection; + sortBy(keyPath: string): PromiseExtended; + sortBy(keyPath: string, thenShortcut: ThenShortcut) : PromiseExtended; + toArray(): PromiseExtended>; + toArray(thenShortcut: ThenShortcut) : PromiseExtended; + uniqueKeys(): PromiseExtended; + uniqueKeys(thenShortcut: ThenShortcut): PromiseExtended; + until(filter: (value: T) => boolean, includeStopEntry?: boolean): Collection; + // Mutating methods + delete(): PromiseExtended; + modify(changeCallback: (obj: T, ctx:{value: T}) => void | boolean): PromiseExtended; + modify(changes: { [keyPath: string]: any } ): PromiseExtended; +} +export interface WhereClause { + above(key: any): Collection; + aboveOrEqual(key: any): Collection; + anyOf(keys: ReadonlyArray): Collection; + anyOf(...keys: Array): Collection; + anyOfIgnoreCase(keys: string[]): Collection; + anyOfIgnoreCase(...keys: string[]): Collection; + below(key: any): Collection; + belowOrEqual(key: any): Collection; + between(lower: any, upper: any, includeLower?: boolean, includeUpper?: boolean): Collection; + equals(key: IndexableType): Collection; + equalsIgnoreCase(key: string): Collection; + inAnyRange(ranges: ReadonlyArray<{0: any, 1: any}>, options?: { includeLowers?: boolean, includeUppers?: boolean }): 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: ReadonlyArray): Collection; + notEqual(key: IndexableType): Collection; +} +export interface Database { + readonly name: string; + readonly tables: Table[]; + + table(tableName: string): Table; + + transaction(mode: TransactionMode, table: Table, scope: () => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, scope: () => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, table3: Table, scope: () => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, table3: Table, table4: Table, scope: () => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, table3: Table, table4: Table, table5: Table, scope: () => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, tables: Table[], scope: () => PromiseLike | U): PromiseExtended; +} +export interface TransactionEvents extends DexieEventSet { + (eventName: 'complete', subscriber: () => any): void; + (eventName: 'abort', subscriber: () => any): void; + (eventName: 'error', subscriber: (error:any) => any): void; + complete: DexieEvent; + abort: DexieEvent; + error: DexieEvent; +} +export interface Transaction { + db: Database; + active: boolean; + mode: IDBTransactionMode; + //tables: { [type: string]: Table }; Deprecated since 2.0. Obsolete from v3.0. + storeNames: Array; + parent?: Transaction; + on: TransactionEvents; + abort(): void; + table(tableName: string): Table; + table(tableName: string): Table; + table(tableName: string): Table; +} +export interface CreatingHookContext { + onsuccess?: (primKey: Key) => void; + onerror?: (err: any) => void; +} +export interface UpdatingHookContext { + onsuccess?: (updatedObj: T) => void; + onerror?: (err: any) => void; +} +export interface DeletingHookContext { + onsuccess?: () => void; + onerror?: (err: any) => void; +} +export interface TableHooks extends DexieEventSet { + (eventName: 'creating', subscriber: (this: CreatingHookContext, primKey:TKey, obj:T, transaction:Transaction) => any): void; + (eventName: 'reading', subscriber: (obj:T) => T | any): void; + (eventName: 'updating', subscriber: (this: UpdatingHookContext, modifications:Object, primKey:TKey, obj:T, transaction:Transaction) => any): void; + (eventName: 'deleting', subscriber: (this: DeletingHookContext, primKey:TKey, obj:T, transaction:Transaction) => any): void; + creating: DexieEvent; + reading: DexieEvent; + updating: DexieEvent; + deleting: DexieEvent; +} +export const enum DBCoreRangeType { + Equal = 1, + Range = 2, + Any = 3, + Never = 4 +} +export interface DBCoreKeyRange { + readonly type: DBCoreRangeType; + readonly lower: any; + readonly lowerOpen?: boolean; + readonly upper: any; + readonly upperOpen?: boolean; + //includes (key: Key) : boolean; Despite IDBKeyRange api - it's no good to have this as a method. Benefit from using a more functional approach. +} +export interface DBCoreTransaction { + abort(): void; +} +export interface DBCoreTransactionRequest { + tables: string[]; + mode: 'readonly' | 'readwrite'; +} +export type DBCoreMutateRequest = DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest | DBCoreDeleteRangeRequest; +export interface DBCoreMutateResponse { + numFailures: number, + failures: {[operationNumber: number]: Error}; + lastResult: any; + results?: any[]; // Present on AddRequest and PutRequest if request.wantResults is truthy. +} +export interface DBCoreAddRequest { + type: 'add'; + trans: DBCoreTransaction; + values: any[]; + keys?: any[]; + wantResults?: boolean; +} +export interface DBCorePutRequest { + type: 'put'; + trans: DBCoreTransaction; + values: any[]; + keys?: any[]; + wantResults?: boolean; +} +export interface DBCoreDeleteRequest { + type: 'delete'; + trans: DBCoreTransaction; + keys: any[]; +} +export interface DBCoreDeleteRangeRequest { + type: 'deleteRange'; + trans: DBCoreTransaction; + range: DBCoreKeyRange; +} +export interface DBCoreGetManyRequest { + trans: DBCoreTransaction; + keys: any[]; +} +export interface DBCoreGetRequest { + trans: DBCoreTransaction; + key: any; +} +export interface DBCoreQuery { + index: DBCoreIndex;//keyPath: null | string | string[]; // null represents primary key. string a property, string[] several properties. + range: DBCoreKeyRange; +} +export interface DBCoreQueryRequest { + trans: DBCoreTransaction; + values?: boolean; + limit?: number; + query: DBCoreQuery; +} +export interface DBCoreQueryResponse { + result: any[]; +} +export interface DBCoreOpenCursorRequest { + trans: DBCoreTransaction; + values?: boolean; + unique?: boolean; + reverse?: boolean; + query: DBCoreQuery; +} +export interface DBCoreCountRequest { + trans: DBCoreTransaction; + query: DBCoreQuery; +} +export interface DBCoreCursor { + readonly trans: DBCoreTransaction; + readonly key: any; + readonly primaryKey: any; + readonly value?: any; + readonly done?: boolean; + continue(key?: any): void; + continuePrimaryKey(key: any, primaryKey: any): void; + advance(count: number): void; + start(onNext: ()=>void): Promise + stop(value?: any | Promise): void; + next(): Promise; + fail(error: Error): void; +} +export interface DBCoreSchema { + name: string; + tables: DBCoreTableSchema[]; +} +export interface DBCoreTableSchema { + readonly name: string; + readonly primaryKey: DBCoreIndex; + readonly indexes: DBCoreIndex[]; + readonly getIndexByKeyPath: (keyPath: null | string | string[]) => DBCoreIndex | undefined; +} +export interface DBCoreIndex { + /** Name of the index, or null for primary key */ + readonly name: string | null; + /** True if this index represents the primary key */ + readonly isPrimaryKey?: boolean; + /** True if this index represents the primary key and is not inbound (http://dexie.org/docs/inbound) */ + readonly outbound?: boolean; + /** True if and only if keyPath is an array (http://dexie.org/docs/Compound-Index) */ + readonly compound?: boolean; + /** keyPath, null for primary key, string for single-property indexes, Array for compound indexes */ + readonly keyPath: null | string | string[]; + /** Auto-generated primary key (does not apply to secondary indexes) */ + readonly autoIncrement?: boolean; + /** Whether index is unique. Also true if index is primary key. */ + readonly unique?: boolean; + /** Whether index is multiEntry. */ + readonly multiEntry?: boolean; + /** Extract (using keyPath) a key from given value (object) */ + readonly extractKey: (value: any) => any; +} +export interface DBCore { + stack: "dbcore"; + // Transaction and Object Store + transaction(req: DBCoreTransactionRequest): DBCoreTransaction; + + // Utility methods + cmp(a: any, b: any) : number; + readonly MIN_KEY: any; + readonly MAX_KEY: any; + readonly schema: DBCoreSchema; + table(name: string): DBCoreTable; +} +export interface DBCoreTable { + readonly name: string; + readonly schema: DBCoreTableSchema; + + mutate(req: DBCoreMutateRequest): Promise; + get(req: DBCoreGetRequest): Promise; + getMany(req: DBCoreGetManyRequest): Promise; + query(req: DBCoreQueryRequest): Promise; + openCursor(req: DBCoreOpenCursorRequest): Promise; + count(req: DBCoreCountRequest): Promise; +} +export interface Table { + db: Database; + name: string; + schema: TableSchema; + hook: TableHooks; + core: DBCoreTable; + + get(key: TKey): PromiseExtended; + get(key: TKey, thenShortcut: ThenShortcut): PromiseExtended; + get(equalityCriterias: {[key:string]:any}): PromiseExtended; + get(equalityCriterias: {[key:string]:any}, thenShortcut: ThenShortcut): PromiseExtended; + where(index: string | string[]): WhereClause; + where(equalityCriterias: {[key:string]:any}): Collection; + + filter(fn: (obj: T) => boolean): Collection; + + count(): PromiseExtended; + count(thenShortcut: ThenShortcut): PromiseExtended; + + offset(n: number): Collection; + + limit(n: number): Collection; + + each(callback: (obj: T, cursor: {key: any, primaryKey: TKey}) => any): PromiseExtended; + + toArray(): PromiseExtended>; + toArray(thenShortcut: ThenShortcut): PromiseExtended; + + toCollection(): Collection; + orderBy(index: string | string[]): Collection; + reverse(): Collection; + mapToClass(constructor: Function): Function; + add(item: T, key?: TKey): PromiseExtended; + update(key: TKey | T, changes: { [keyPath: string]: any }): PromiseExtended; + put(item: T, key?: TKey): PromiseExtended; + delete(key: TKey): PromiseExtended; + clear(): PromiseExtended; + bulkGet(keys: TKey[]): PromiseExtended; + + bulkAdd(items: T[], keys: IndexableTypeArrayReadonly, options: { allKeys: B }): PromiseExtended; + bulkAdd(items: T[], options: { allKeys: B }): PromiseExtended; + bulkAdd(items: T[], keys?: IndexableTypeArrayReadonly, options?: { allKeys: boolean }): PromiseExtended; + + bulkPut(items: T[], keys: IndexableTypeArrayReadonly, options: { allKeys: B }): PromiseExtended; + bulkPut(items: T[], options: { allKeys: B }): PromiseExtended; + bulkPut(items: T[], keys?: IndexableTypeArrayReadonly, options?: { allKeys: boolean }): PromiseExtended; + + bulkDelete(keys: IndexableTypeArrayReadonly): PromiseExtended; +} +export interface Version { + stores(schema: { [tableName: string]: string | null }): Version; + upgrade(fn: (trans: Transaction) => void): Version; +} +export interface DexieOnReadyEvent { + subscribe(fn: () => any, bSticky: boolean): void; + unsubscribe(fn: () => any): void; + fire(): any; +} +export interface DexieVersionChangeEvent { + subscribe(fn: (event: IDBVersionChangeEvent) => any): void; + unsubscribe(fn: (event: IDBVersionChangeEvent) => any): void; + fire(event: IDBVersionChangeEvent): any; +} +export interface DexiePopulateEvent { + subscribe(fn: (trans: Transaction) => any): void; + unsubscribe(fn: (trans: Transaction) => any): void; + fire(trans: Transaction): any; +} +export interface DbEvents extends DexieEventSet { + (eventName: 'ready', subscriber: () => any, bSticky?: boolean): void; + (eventName: 'populate', subscriber: (trans: Transaction) => any): void; + (eventName: 'blocked', subscriber: (event: IDBVersionChangeEvent) => any): void; + (eventName: 'versionchange', subscriber: (event: IDBVersionChangeEvent) => any): void; + ready: DexieOnReadyEvent; + populate: DexiePopulateEvent; + blocked: DexieEvent; + versionchange: DexieVersionChangeEvent; +} +export type DbSchema = {[tableName: string]: TableSchema}; +export interface Middleware { + stack: TStack["stack"], + create: (down: TStack) => Partial; + level?: number; + name?: string; +} +export interface DexieStacks { + dbcore: DBCore; +} +export interface Dexie extends Database { + readonly name: string; + readonly tables: Table[]; + readonly verno: number; + + readonly _allTables: {[name: string]: Table}; + + readonly core: DBCore; + + _createTransaction: ( + this: Dexie, + mode: IDBTransactionMode, + storeNames: ArrayLike, + dbschema: DbSchema, + parentTransaction?: Transaction | null) => Transaction; + + _dbSchema: DbSchema; + + version(versionNumber: number): Version; + + on: DbEvents; + + open(): PromiseExtended; + + table(tableName: string): Table; + + transaction(mode: TransactionMode, table: Table, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string, table2: string, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, table3: Table, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string, table2: string, table3: string, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, table3: Table, table4: Table, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string, table2: string, table3: string, table4: string, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, table: Table, table2: Table, table3: Table, table4: Table, table5: Table, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string, table2: string, table3: string, table4: string, table5: string, scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + + transaction(mode: TransactionMode, tables: Table[], scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, tables: string[], scope: (trans: Transaction) => PromiseLike | U): PromiseExtended; + + close(): void; + + delete(): PromiseExtended; + + isOpen(): boolean; + + hasBeenClosed(): boolean; + + hasFailed(): boolean; + + dynamicallyOpened(): boolean; + + backendDB(): IDBDatabase; + + use(middleware: Middleware): this; + // Add more supported stacks here... : use(middleware: Middleware): this; + unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this; + unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this; + + // 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 : {prototype: Table}; + WhereClause: {prototype: WhereClause}; + Version: {prototype: Version}; + Transaction: {prototype: Transaction}; + Collection: {prototype: Collection}; +} +/** DexieError + * + * Common base class for all errors originating from Dexie.js except TypeError, + * SyntaxError and RangeError. + * + * http://dexie.org/docs/DexieErrors/DexieError + * + */ +export interface DexieError extends Error { + name: string; + message: string; + stack: string; + inner: any; + toString(): string; +} +/** + * List of the names of auto-generated error classes that extends DexieError + * and shares the interface of DexieError. + * + * Each error should be documented at http://dexie.org/docs/DexieErrors/Dexie. + * + * The generic type DexieExceptionClasses is a map of full error name to + * error constructor. The DexieExceptionClasses is mixed in into Dexie, + * so that it is always possible to throw or catch certain errors via + * Dexie.ErrorName. Example: + * + * try { + * throw new Dexie.InvalidTableError("Invalid table foo", innerError?); + * } catch (err) { + * if (err instanceof Dexie.InvalidTableError) { + * // Could also have check for err.name === "InvalidTableError", or + * // err.name === Dexie.errnames.InvalidTableError. + * console.log("Seems to be an invalid table here..."); + * } else { + * throw err; + * } + * } + */ +export type DexieErrors = { + // http://dexie.org/docs/DexieErrors/Dexie.OpenFailedError + OpenFailed: 'OpenFailedError', + + // http://dexie.org/docs/DexieErrors/Dexie.VersionChangeError + VersionChange: 'VersionChangeError', + + // http://dexie.org/docs/DexieErrors/Dexie.SchemaError + Schema: 'SchemaError', + + // http://dexie.org/docs/DexieErrors/Dexie.UpgradeError + Upgrade: 'UpgradeError', + + // http://dexie.org/docs/DexieErrors/Dexie.InvalidTableError + InvalidTable: 'InvalidTableError', + + // http://dexie.org/docs/DexieErrors/Dexie.MissingAPIError + MissingAPI: 'MissingAPIError', + + // http://dexie.org/docs/DexieErrors/Dexie.NoSuchDatabaseError + NoSuchDatabase: 'NoSuchDatabaseError', + + // http://dexie.org/docs/DexieErrors/Dexie.InvalidArgumentError + InvalidArgument: 'InvalidArgumentError', + + // http://dexie.org/docs/DexieErrors/Dexie.SubTransactionError + SubTransaction: 'SubTransactionError', + + // http://dexie.org/docs/DexieErrors/Dexie.UnsupportedError + Unsupported: 'UnsupportedError', + + // http://dexie.org/docs/DexieErrors/Dexie.InternalError + Internal: 'InternalError', + + // http://dexie.org/docs/DexieErrors/Dexie.DatabaseClosedError + DatabaseClosed: 'DatabaseClosedError', + + // http://dexie.org/docs/DexieErrors/Dexie.PrematureCommitError + PrematureCommit: 'PrematureCommitError', + + // http://dexie.org/docs/DexieErrors/Dexie.ForeignAwaitError + ForeignAwait: 'ForeignAwaitError', + + // http://dexie.org/docs/DexieErrors/Dexie.UnknownError + Unknown: 'UnknownError', + + // http://dexie.org/docs/DexieErrors/Dexie.ConstraintError + Constraint: 'ConstraintError', + + // http://dexie.org/docs/DexieErrors/Dexie.DataError + Data: 'DataError', + + // http://dexie.org/docs/DexieErrors/Dexie.TransactionInactiveError + TransactionInactive: 'TransactionInactiveError', + + // http://dexie.org/docs/DexieErrors/Dexie.ReadOnlyError + ReadOnly: 'ReadOnlyError', + + // http://dexie.org/docs/DexieErrors/Dexie.VersionError + Version: 'VersionError', + + // http://dexie.org/docs/DexieErrors/Dexie.NotFoundError + NotFound: 'NotFoundError', + + // http://dexie.org/docs/DexieErrors/Dexie.InvalidStateError + InvalidState: 'InvalidStateError', + + // http://dexie.org/docs/DexieErrors/Dexie.InvalidAccessError + InvalidAccess: 'InvalidAccessError', + + // http://dexie.org/docs/DexieErrors/Dexie.AbortError + Abort: 'AbortError', + + // http://dexie.org/docs/DexieErrors/Dexie.TimeoutError + Timeout: 'TimeoutError', + + // http://dexie.org/docs/DexieErrors/Dexie.QuotaExceededError + QuotaExceeded: 'QuotaExceededError', + + // http://dexie.org/docs/DexieErrors/Dexie.DataCloneError + DataClone: 'DataCloneError' +} +/** ModifyError + * + * http://dexie.org/docs/DexieErrors/Dexie.ModifyError + */ +export interface ModifyError extends DexieError { + failures: Array; + failedKeys: IndexableTypeArrayReadonly; + successCount: number; +} +/** BulkError + * + * http://dexie.org/docs/DexieErrors/Dexie.BulkError + */ +export interface BulkError extends DexieError { + failures: {[operationNumber: number]: Error}; +} +export interface DexieErrorConstructor { + new(msg?: string, inner?: Object) : DexieError; + new(inner: Object): DexieError; + prototype: DexieError; +} +export interface ModifyErrorConstructor { + new ( + msg?:string, + failures?: any[], + successCount?: number, + failedKeys?: IndexableTypeArrayReadonly) : ModifyError; + prototype: ModifyError; +} +export interface BulkErrorConstructor { + new (msg?:string, failures?: {[operationNumber: number]: Error}) : BulkError; + prototype: BulkError; +} +export type ExceptionSet = {[P in DexieErrors[keyof DexieErrors]]: DexieErrorConstructor}; +export type DexieExceptionClasses = ExceptionSet & { + DexieError: DexieErrorConstructor, + ModifyError: ModifyErrorConstructor; + BulkError: BulkErrorConstructor; +} +export interface DexieDOMDependencies { + indexedDB: IDBFactory; + IDBKeyRange: typeof IDBKeyRange; +} +export interface DexieOptions { + addons?: Array<(db: Dexie) => void>, + autoOpen?: boolean, + indexedDB?: {open: Function}, + IDBKeyRange?: {bound: Function, lowerBound: Function, upperBound: Function}, + allowEmptyDB?: boolean; +} +export interface DexieConstructor extends DexieExceptionClasses { + new(databaseName: string, options?: DexieOptions) : Dexie; + prototype: Dexie; + + addons: Array<(db: Dexie) => void>; + version: number; + semVer: string; + currentTransaction: Transaction; + waitFor (promise: PromiseLike | T, timeoutMilliseconds?: number) : Promise; + + getDatabaseNames(): Promise; + getDatabaseNames(thenShortcut: ThenShortcut): Promise; + + vip(scopeFunction: () => U): U; + ignoreTransaction(fn: ()=> U) : U; + override (origFunc:F, overridedFactory: (fn:any)=>any) : F; // ? + getByKeyPath(obj: Object, keyPath: string): any; + setByKeyPath(obj: Object, keyPath: string, value: any): void; + delByKeyPath(obj: Object, keyPath: string): void; + shallowClone (obj: T): T; + deepClone(obj: T): T; + asap(fn: Function) : void; //? + maxKey: Array> | string; + minKey: number; + exists(dbName: string) : Promise; + delete(dbName: string): Promise; + dependencies: DexieDOMDependencies; + default: Dexie; // Work-around for different build tools handling default imports differently. + + Promise: PromiseExtendedConstructor; + //TableSchema: {}; // Deprecate! + //IndexSpec: {new():IndexSpec}; //? Deprecate + Events: (ctx?: any)=>DexieEventSet; + + errnames: {[P in keyof DexieExceptionClasses]: P}; +} +export declare var Dexie: DexieConstructor; +export interface _Table extends Table {} +export interface _Collection extends Collection {} +export declare module Dexie { + // The "Dexie.Promise" type. + type Promise = PromiseExtended // Because many samples have been Dexie.Promise. + // The "Dexie.Table" interface. Same as named exported interface Table. + interface Table extends _Table {} // Because all samples have been Dexie.Table<...> + // The "Dexie.Collection" interface. Same as named exported interface Collection. + interface Collection extends _Collection {} // Because app-code may declare it. +} +/** Exporting 'Dexie' as the default export. + **/ +export default Dexie; + +export as namespace Dexie; diff --git a/dist/dexie.js b/dist/dexie.js new file mode 100644 index 000000000..b1b3e8af4 --- /dev/null +++ b/dist/dexie.js @@ -0,0 +1,4380 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 3.0.2, Fri Jul 31 2020 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + +(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'; + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + + + + + + + + + + +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +var keys = Object.keys; +var isArray = Array.isArray; +var _global = typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; +if (typeof Promise !== 'undefined' && !_global.Promise) { + _global.Promise = Promise; +} +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]); + }); +} +var defineProperty = Object.defineProperty; +function setProp(obj, prop, functionOrGetSet, options) { + 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); + var 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 assert(b) { + if (!b) + throw new Error("Assertion Failed"); +} +function asap(fn) { + if (_global.setImmediate) + setImmediate(fn); + else + setTimeout(fn, 0); +} + +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 tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } + catch (ex) { + onerror && onerror(ex); + } +} +function getByKeyPath(obj, keyPath) { + if (hasOwn(obj, keyPath)) + return obj[keyPath]; + 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) { + if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) + obj.splice(currentKeyPath, 1); + else + 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) { + if (isArray(obj) && !isNaN(parseInt(keyPath))) + obj.splice(keyPath, 1); + else + 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; +} +var concat = [].concat; +function flatten(a) { + return concat.apply([], a); +} +var intrinsicTypeNames = "Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set" + .split(',').concat(flatten([8, 16, 32, 64].map(function (num) { return ["Int", "Uint", "Float"].map(function (t) { return t + num + "Array"; }); }))).filter(function (t) { return _global[t]; }); +var intrinsicTypes = intrinsicTypeNames.map(function (t) { return _global[t]; }); +var intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, function (x) { return [x, true]; }); +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 (intrinsicTypes.indexOf(any.constructor) >= 0) { + rv = any; + } + 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; +} +var toString = {}.toString; +function toStringTag(o) { + return toString.call(o).slice(8, -1); +} +var getValueOf = function (val, type) { + return type === "Array" ? '' + val.map(function (v) { return getValueOf(v, toStringTag(v)); }) : + type === "ArrayBuffer" ? '' + new Uint8Array(val) : + type === "Date" ? val.getTime() : + ArrayBuffer.isView(val) ? '' + new Uint8Array(val.buffer) : + val; +}; +function getObjectDiff(a, b, rv, prfx) { + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(function (prop) { + if (!hasOwn(b, prop)) + rv[prfx + prop] = undefined; + else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) { + var apTypeName = toStringTag(ap); + var bpTypeName = toStringTag(bp); + if (apTypeName === bpTypeName) { + if (intrinsicTypeNameSet[apTypeName]) { + if (getValueOf(ap, apTypeName) !== getValueOf(bp, bpTypeName)) { + rv[prfx + prop] = b[prop]; + } + } + else { + getObjectDiff(ap, bp, rv, prfx + prop + "."); + } + } + else { + rv[prfx + prop] = b[prop]; + } + } + else if (ap !== bp) + rv[prfx + prop] = b[prop]; + } + }); + keys(b).forEach(function (prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; + } + }); + return rv; +} +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 = {}; +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 isAsyncFunction = typeof Symbol !== 'undefined' + ? function (fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; } + : function () { return false; }; + +var debug = typeof location !== 'undefined' && + /^(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() { + if (NEEDS_THROW_FOR_STACK) + try { + throw new Error(); + } + 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(''); +} + +var dexieErrorNames = [ + 'Modify', + 'Bulk', + 'OpenFailed', + 'VersionChange', + 'Schema', + 'Upgrade', + 'InvalidTable', + 'MissingAPI', + 'NoSuchDatabase', + 'InvalidArgument', + 'SubTransaction', + 'Unsupported', + 'Internal', + 'DatabaseClosed', + 'PrematureCommit', + 'ForeignAwait' +]; +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" +}; +function DexieError(name, msg) { + 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: " + Object.keys(failures) + .map(function (key) { return failures[key].toString(); }) + .filter(function (v, i, s) { return s.indexOf(v) === i; }) + .join('\n'); +} +function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; + this.message = getMultiErrorMessage(msg, failures); +} +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); +var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); +var BaseException = DexieError; +var exceptions = errorList.reduce(function (obj, name) { + 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 + (!inner ? '' : '\n ' + inner); + 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; +}, {}); +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) { + 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 nop() { } +function mirror(val) { return val; } +function pureFunctionChain(f1, f2) { + 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) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) + arguments[0] = res; + var onsuccess = this.onsuccess, + onerror = 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, + onerror = 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); + var onsuccess = this.onsuccess, + onerror = 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); + }; +} + +var INTERNAL = {}; +var LONG_STACKS_CLIP_LIMIT = 100; +var MAX_LONG_STACKS = 20; +var ZONE_ECHO_LIMIT = 100; +var _a = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, globalP.__proto__, globalP]; + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + nativeP.__proto__, + globalP + ]; + })(); +var resolvedNativePromise = _a[0]; +var nativePromiseProto = _a[1]; +var resolvedGlobalPromise = _a[2]; +var nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; +var patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +var schedulePhysicalTick = resolvedGlobalPromise ? + function () { resolvedGlobalPromise.then(physicalTick); } + : + _global.setImmediate ? + setImmediate.bind(null, physicalTick) : + _global.MutationObserver ? + function () { + var hiddenDiv = document.createElement("div"); + (new MutationObserver(function () { + physicalTick(); + hiddenDiv = null; + })).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); + } : + function () { setTimeout(physicalTick, 0); }; +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; +var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + pgp: false, + env: {}, + finalize: function () { + this.unhandleds.forEach(function (uh) { + try { + globalError(uh[0], uh[1]); + } + catch (e) { } + }); + } +}; +var PSD = globalPSD; +var microtickQueue = []; +var numScheduledCalls = 0; +var tickFinalizers = []; +function DexiePromise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this.onuncatched = nop; + this._lib = false; + var psd = (this._PSD = PSD); + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) + throw new TypeError('Not a function'); + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); + return; + } + this._state = null; + this._value = null; + ++psd.ref; + executePromiseTask(this, fn); +} +var thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + if (possibleAwait) + decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; + return then; + }, + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : + { + get: function () { + return value; + }, + set: thenProp.set + }); + } +}; +props(DexiePromise.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + var type = arguments[0], handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + return err instanceof type ? handler(err) : PromiseReject(err); + }) + : this.then(null, function (err) { + return 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); + }); + }, + 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; + return stack; + } + finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? + new DexiePromise(function (resolve, reject) { + var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms); + _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } +}); +if (typeof Symbol !== 'undefined' && Symbol.toStringTag) + setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); +globalPSD.env = snapShot(); +function Listener(onFulfilled, onRejected, resolve, reject, zone) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = zone; +} +props(DexiePromise, { + all: function () { + var values = getArrayOf.apply(null, arguments) + .map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + values.map(function (value) { return DexiePromise.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; } + }, + follow: function (fn, zoneProps) { + return new DexiePromise(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; + psd.onunhandled = reject; + psd.finalize = callBoth(function () { + var _this = this; + run_at_end_of_this_or_next_physical_tick(function () { + _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } +}); +if (NativePromise) { + if (NativePromise.allSettled) + setProp(DexiePromise, "allSettled", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve) { + if (possiblePromises.length === 0) + resolve([]); + var remaining = possiblePromises.length; + var results = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) + .then(function () { return --remaining || resolve(results); }); }); + }); + }); + if (NativePromise.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + var remaining = possiblePromises.length; + var failures = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + }); }); + }); + }); +} +function executePromiseTask(promise, fn) { + 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 DexiePromise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } + else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); + } + 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; + } + }); + }); + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); +} +function propagateAllListeners(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 (numScheduledCalls === 0) { + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } +} +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap$1(callListener, [cb, promise, listener]); +} +function callListener(cb, promise, listener) { + try { + currentFulfiller = promise; + var ret, value = promise._value; + if (promise._state) { + ret = cb(value); + } + else { + if (rejectingErrors.length) + rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); + } + listener.resolve(ret); + } + catch (e) { + listener.reject(e); + } + finally { + currentFulfiller = null; + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + --listener.psd.ref || listener.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; + 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) { + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } +} +function physicalTick() { + beginMicroTickScope() && endMicroTickScope(); +} +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} +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); + 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) { + if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) + unhandledErrors.push(promise); +} +function markErrorAsHandled(promise) { + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + unhandledErrors.splice(i, 1); + return; + } +} +function PromiseReject(reason) { + return new DexiePromise(INTERNAL, false, reason); +} +function wrap(fn, errorCatcher) { + var psd = PSD; + return function () { + var wasRootExec = beginMicroTickScope(), outerScope = PSD; + try { + switchToZone(psd, true); + return fn.apply(this, arguments); + } + catch (e) { + errorCatcher && errorCatcher(e); + } + finally { + switchToZone(outerScope, false); + if (wasRootExec) + endMicroTickScope(); + } + }; +} +var task = { awaits: 0, echoes: 0, id: 0 }; +var taskCounter = 0; +var zoneStack = []; +var zoneEchoes = 0; +var totalEchoes = 0; +var zone_id_counter = 0; +function newScope(fn, props$$1, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: DexiePromise, + PromiseProp: { value: DexiePromise, configurable: true, writable: true }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) + } : {}; + if (props$$1) + extend(psd, props$$1); + ++parent.ref; + psd.finalize = function () { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD(psd, fn, a1, a2); + if (psd.ref === 0) + psd.finalize(); + return rv; +} +function incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; +} +function decrementExpectedAwaits(sourceTaskId) { + if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) + return; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; +} +if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + incrementExpectedAwaits = decrementExpectedAwaits = nop; +} +function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { + incrementExpectedAwaits(); + return possiblePromise.then(function (x) { + decrementExpectedAwaits(); + return x; + }, function (e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; +} +function zoneEnterEcho(targetZone) { + ++totalEchoes; + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.id = 0; + } + zoneStack.push(PSD); + switchToZone(targetZone, true); +} +function zoneLeaveEcho() { + var zone = zoneStack[zoneStack.length - 1]; + zoneStack.pop(); + switchToZone(zone, false); +} +function switchToZone(targetZone, bEnteringZone) { + var currentZone = PSD; + if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { + enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + var GlobalPromise_1 = globalPSD.env.Promise; + var targetEnv = targetZone.env; + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise_1.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + GlobalPromise_1.all = targetEnv.all; + GlobalPromise_1.race = targetEnv.race; + GlobalPromise_1.resolve = targetEnv.resolve; + GlobalPromise_1.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise_1.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise_1.any = targetEnv.any; + } + } +} +function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + resolve: GlobalPromise.resolve, + reject: GlobalPromise.reject, + nthen: nativePromiseProto.then, + gthen: GlobalPromise.prototype.then + } : {}; +} +function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + switchToZone(psd, true); + return fn(a1, a2, a3); + } + finally { + switchToZone(outerScope, false); + } +} +function enqueueNativeMicroTask(job) { + nativePromiseThen.call(resolvedNativePromise, job); +} +function nativeAwaitCompatibleWrap(fn, zone, possibleAwait) { + return typeof fn !== 'function' ? fn : function () { + var outerZone = PSD; + if (possibleAwait) + incrementExpectedAwaits(); + switchToZone(zone, true); + try { + return fn.apply(this, arguments); + } + finally { + switchToZone(outerZone, false); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone, false), nativeAwaitCompatibleWrap(onRejected, zone, false)); + }; +} +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) + try { + _global.onunhandledrejection(event); + } + catch (_) { } + } + if (debug && event && !event.defaultPrevented) { + console.warn("Unhandled rejection: " + (err.stack || err)); + } + } + catch (e) { } +} +var rejection = DexiePromise.reject; + +function tempTransaction(db, mode, storeNames, fn) { + if (!db._state.openComplete && (!PSD.letThrough)) { + if (!db._state.isBeingOpened) { + if (!db._options.autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); + } + return db._state.dbReadyPromise.then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + else { + var trans = db._createTransaction(mode, storeNames, db._dbSchema); + try { + trans.create(); + } + catch (ex) { + return rejection(ex); + } + return trans._promise(mode, function (resolve, reject) { + return newScope(function () { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(function (result) { + return trans._completion.then(function () { return result; }); + }); + } +} + +var DEXIE_VERSION = '3.0.2'; +var maxString = String.fromCharCode(65535); +var minKey = -Infinity; +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); }; +var DBNAMES_DB = '__dbnames'; +var READONLY = 'readonly'; +var READWRITE = 'readwrite'; + +function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; +} + +var AnyRange = { + type: 3 , + lower: -Infinity, + lowerOpen: false, + upper: [[]], + upperOpen: false +}; + +var Table = (function () { + function Table() { + } + Table.prototype._trans = function (mode, fn, writeLocked) { + var trans = this._tx || PSD.trans; + var tableName = this.name; + function checkTableInTransaction(resolve, reject, trans) { + if (!trans.schema[tableName]) + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + return fn(trans.idbtrans, trans); + } + var wasRootExec = beginMicroTickScope(); + try { + return trans && trans.db === this.db ? + trans === PSD.trans ? + trans._promise(mode, checkTableInTransaction, writeLocked) : + newScope(function () { return trans._promise(mode, checkTableInTransaction, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(this.db, mode, [this.name], checkTableInTransaction); + } + finally { + if (wasRootExec) + endMicroTickScope(); + } + }; + Table.prototype.get = function (keyOrCrit, cb) { + var _this = this; + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + return this._trans('readonly', function (trans) { + return _this.core.get({ trans: trans, key: keyOrCrit }) + .then(function (res) { return _this.hook.reading.fire(res); }); + }).then(cb); + }; + Table.prototype.where = function (indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new this.db.WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new this.db.WhereClause(this, "[" + indexOrCrit.join('+') + "]"); + var keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { + return ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; }) && + ix.keyPath.every(function (keyPath) { return keyPaths.indexOf(keyPath) >= 0; }); + })[0]; + if (compoundIndex && this.db._maxKey !== maxString) + return this + .where(compoundIndex.name) + .equals(compoundIndex.keyPath.map(function (kp) { return indexOrCrit[kp]; })); + if (!compoundIndex && debug) + console.warn("The query " + JSON.stringify(indexOrCrit) + " on " + this.name + " would benefit of a " + + ("compound index [" + keyPaths.join('+') + "]")); + var idxByName = this.schema.idxByName; + var idb = this.db._deps.indexedDB; + function equals(a, b) { + try { + return idb.cmp(a, b) === 0; + } + catch (e) { + return false; + } + } + var _a = keyPaths.reduce(function (_a, keyPath) { + var prevIndex = _a[0], prevFilterFn = _a[1]; + var index = idxByName[keyPath]; + var value = indexOrCrit[keyPath]; + return [ + prevIndex || index, + prevIndex || !index ? + combine(prevFilterFn, index && index.multi ? + function (x) { + var prop = getByKeyPath(x, keyPath); + return isArray(prop) && prop.some(function (item) { return equals(value, item); }); + } : function (x) { return equals(value, getByKeyPath(x, keyPath)); }) + : prevFilterFn + ]; + }, [null, null]), idx = _a[0], filterFunction = _a[1]; + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(filterFunction) : + compoundIndex ? + this.filter(filterFunction) : + this.where(keyPaths).equals(''); + }; + Table.prototype.filter = function (filterFunction) { + return this.toCollection().and(filterFunction); + }; + Table.prototype.count = function (thenShortcut) { + return this.toCollection().count(thenShortcut); + }; + Table.prototype.offset = function (offset) { + return this.toCollection().offset(offset); + }; + Table.prototype.limit = function (numRows) { + return this.toCollection().limit(numRows); + }; + Table.prototype.each = function (callback) { + return this.toCollection().each(callback); + }; + Table.prototype.toArray = function (thenShortcut) { + return this.toCollection().toArray(thenShortcut); + }; + Table.prototype.toCollection = function () { + return new this.db.Collection(new this.db.WhereClause(this)); + }; + Table.prototype.orderBy = function (index) { + return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? + "[" + index.join('+') + "]" : + index)); + }; + Table.prototype.reverse = function () { + return this.toCollection().reverse(); + }; + Table.prototype.mapToClass = function (constructor) { + this.schema.mappedClass = constructor; + var readHook = function (obj) { + if (!obj) + return obj; + var res = Object.create(constructor.prototype); + 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; + }; + Table.prototype.defineClass = function () { + function Class(content) { + extend(this, content); + } + + return this.mapToClass(Class); + }; + Table.prototype.add = function (obj, key) { + var _this = this; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [obj] }); + }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (!_this.core.schema.primaryKey.outbound) { + try { + setByKeyPath(obj, _this.core.schema.primaryKey.keyPath, lastResult); + } + catch (_) { } + + } + return lastResult; + }); + }; + Table.prototype.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)) { + 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")); + return this.where(":id").equals(key).modify(modifications); + } + else { + return this.where(":id").equals(keyOrObject).modify(modifications); + } + }; + Table.prototype.put = function (obj, key) { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [obj], keys: key != null ? [key] : null }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (!_this.core.schema.primaryKey.outbound) { + try { + setByKeyPath(obj, _this.core.schema.primaryKey.keyPath, lastResult); + } + catch (_) { } + + } + return lastResult; + }); + }; + Table.prototype.delete = function (key) { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.clear = function () { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.bulkGet = function (keys$$1) { + var _this = this; + return this._trans('readonly', function (trans) { + return _this.core.getMany({ + keys: keys$$1, + trans: trans + }).then(function (result) { return result.map(function (res) { return _this.hook.reading.fire(res); }); }); + }); + }; + Table.prototype.bulkAdd = function (objects, keysOrOptions, options) { + var _this = this; + var keys$$1 = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys$$1 ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var outbound = _this.core.schema.primaryKey.outbound; + if (!outbound && 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"); + var numObjects = objects.length; + return _this.core.mutate({ trans: trans, type: 'add', keys: keys$$1, values: objects, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(_this.name + ".bulkAdd(): " + numFailures + " of " + numObjects + " operations failed", Object.keys(failures).map(function (pos) { return failures[pos]; })); + }); + }); + }; + Table.prototype.bulkPut = function (objects, keysOrOptions, options) { + var _this = this; + var keys$$1 = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys$$1 ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var outbound = _this.core.schema.primaryKey.outbound; + if (!outbound && 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"); + var numObjects = objects.length; + return _this.core.mutate({ trans: trans, type: 'put', keys: keys$$1, values: objects, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(_this.name + ".bulkPut(): " + numFailures + " of " + numObjects + " operations failed", Object.keys(failures).map(function (pos) { return failures[pos]; })); + }); + }); + }; + Table.prototype.bulkDelete = function (keys$$1) { + var _this = this; + var numKeys = keys$$1.length; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'delete', keys: keys$$1 }); + }).then(function (_a) { + var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures; + if (numFailures === 0) + return lastResult; + throw new BulkError(_this.name + ".bulkDelete(): " + numFailures + " of " + numKeys + " operations failed", failures); + }); + }; + return Table; +}()); + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + 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 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) { + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } + else if (args === 'asap') { + var context = add(eventName, mirror, function fire() { + var i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + context.subscribers.forEach(function (fn) { + asap(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +function makeClassConstructor(prototype, constructor) { + derive(constructor).from({ prototype: prototype }); + return constructor; +} + +function createTableConstructor(db) { + return makeClassConstructor(Table.prototype, function Table$$1(name, tableSchema, trans) { + this.db = db; + this._tx = trans; + this.name = name; + this.schema = tableSchema; + this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + }); +} + +function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); +} +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); +} +function getIndexOrStore(ctx, coreSchema) { + if (ctx.isPrimKey) + return coreSchema.primaryKey; + var index = coreSchema.getIndexByKeyPath(ctx.index); + if (!index) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); + return index; +} +function openCursor(ctx, coreTable, trans) { + var index = getIndexOrStore(ctx, coreTable.schema); + return coreTable.openCursor({ + trans: trans, + values: !ctx.keysOnly, + reverse: ctx.dir === 'prev', + unique: !!ctx.unique, + query: { + index: index, + range: ctx.range + } + }); +} +function iter(ctx, fn, coreTrans, coreTable) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); + } + else { + var set_1 = {}; + var union = function (item, cursor, advance) { + if (!filter || filter(cursor, advance, function (result) { return cursor.stop(result); }, function (err) { return cursor.fail(err); })) { + var primaryKey = cursor.primaryKey; + var key = '' + primaryKey; + if (key === '[object ArrayBuffer]') + key = '' + new Uint8Array(primaryKey); + if (!hasOwn(set_1, key)) { + set_1[key] = true; + fn(item, cursor, advance); + } + } + }; + return Promise.all([ + ctx.or._iterate(union, coreTrans), + iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) + ]); + } +} +function iterate(cursorPromise, filter, fn, valueMapper) { + var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; + var wrappedFn = wrap(mappedFn); + return cursorPromise.then(function (cursor) { + if (cursor) { + return cursor.start(function () { + var c = function () { return cursor.continue(); }; + if (!filter || filter(cursor, function (advancer) { return c = advancer; }, function (val) { cursor.stop(val); c = nop; }, function (e) { cursor.fail(e); c = nop; })) + wrappedFn(cursor.value, cursor, function (advancer) { return c = advancer; }); + c(); + }); + } + }); +} + +var Collection = (function () { + function Collection() { + } + Collection.prototype._read = function (fn, cb) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readonly', fn).then(cb); + }; + Collection.prototype._write = function (fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readwrite', fn, "locked"); + }; + Collection.prototype._addAlgorithm = function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }; + Collection.prototype._iterate = function (fn, coreTrans) { + return iter(this._ctx, fn, coreTrans, this._ctx.table.core); + }; + Collection.prototype.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; + }; + Collection.prototype.raw = function () { + this._ctx.valueMapper = null; + return this; + }; + Collection.prototype.each = function (fn) { + var ctx = this._ctx; + return this._read(function (trans) { return iter(ctx, fn, trans, ctx.table.core); }); + }; + Collection.prototype.count = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + var coreTable = ctx.table.core; + if (isPlainKeyRange(ctx, true)) { + return coreTable.count({ + trans: trans, + query: { + index: getIndexOrStore(ctx, coreTable.schema), + range: ctx.range + } + }).then(function (count) { return Math.min(count, ctx.limit); }); + } + else { + var count = 0; + return iter(ctx, function () { ++count; return false; }, trans, coreTable) + .then(function () { return count; }); + } + }).then(cb); + }; + Collection.prototype.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); + }; + Collection.prototype.toArray = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + var valueMapper_1 = ctx.valueMapper; + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + limit: ctx.limit, + values: true, + query: { + index: index, + range: ctx.range + } + }).then(function (_a) { + var result = _a.result; + return valueMapper_1 ? result.map(valueMapper_1) : result; + }); + } + else { + var a_1 = []; + return iter(ctx, function (item) { return a_1.push(item); }, trans, ctx.table.core).then(function () { return a_1; }); + } + }, cb); + }; + Collection.prototype.offset = function (offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; + 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; + }; + Collection.prototype.limit = function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); + addReplayFilter(this._ctx, function () { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); + return rowsLeft >= 0; + }; + }, true); + return this; + }; + Collection.prototype.until = function (filterFunction, bIncludeStopEntry) { + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + }; + Collection.prototype.first = function (cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.last = function (cb) { + return this.reverse().first(cb); + }; + Collection.prototype.filter = function (filterFunction) { + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + addMatchFilter(this._ctx, filterFunction); + return this; + }; + Collection.prototype.and = function (filter) { + return this.filter(filter); + }; + Collection.prototype.or = function (indexName) { + return new this.db.WhereClause(this._ctx.table, indexName, this); + }; + Collection.prototype.reverse = function () { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + }; + Collection.prototype.desc = function () { + return this.reverse(); + }; + Collection.prototype.eachKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + }; + Collection.prototype.eachUniqueKey = function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }; + Collection.prototype.eachPrimaryKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + }; + Collection.prototype.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); + }; + Collection.prototype.primaryKeys = function (cb) { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + return this._read(function (trans) { + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + values: false, + limit: ctx.limit, + query: { + index: index, + range: ctx.range + } + }); + }).then(function (_a) { + var result = _a.result; + return result; + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }; + Collection.prototype.uniqueKeys = function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }; + Collection.prototype.firstKey = function (cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.lastKey = function (cb) { + return this.reverse().firstKey(cb); + }; + Collection.prototype.distinct = function () { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + }; + Collection.prototype.modify = function (changes) { + var _this = this; + var ctx = this._ctx; + return this._write(function (trans) { + var modifyer; + if (typeof changes === 'function') { + modifyer = changes; + } + else { + 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); + anythingModified = true; + } + } + return anythingModified; + }; + } + var coreTable = ctx.table.core; + var _a = coreTable.schema.primaryKey, outbound = _a.outbound, extractKey = _a.extractKey; + var limit = 'testmode' in Dexie ? 1 : 2000; + var cmp = _this.db.core.cmp; + var totalFailures = []; + var successCount = 0; + var failedKeys = []; + var applyMutateResult = function (expectedCount, res) { + var failures = res.failures, numFailures = res.numFailures; + successCount += expectedCount - numFailures; + for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) { + var pos = _a[_i]; + totalFailures.push(failures[pos]); + } + }; + return _this.clone().primaryKeys().then(function (keys$$1) { + var nextChunk = function (offset) { + var count = Math.min(limit, keys$$1.length - offset); + return coreTable.getMany({ trans: trans, keys: keys$$1.slice(offset, offset + count) }).then(function (values) { + var addValues = []; + var putValues = []; + var putKeys = outbound ? [] : null; + var deleteKeys = []; + for (var i = 0; i < count; ++i) { + var origValue = values[i]; + var ctx_1 = { + value: deepClone(origValue), + primKey: keys$$1[offset + i] + }; + if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { + if (ctx_1.value == null) { + deleteKeys.push(keys$$1[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { + deleteKeys.push(keys$$1[offset + i]); + addValues.push(ctx_1.value); + } + else { + putValues.push(ctx_1.value); + if (outbound) + putKeys.push(keys$$1[offset + i]); + } + } + } + return Promise.resolve(addValues.length > 0 && + coreTable.mutate({ trans: trans, type: 'add', values: addValues }) + .then(function (res) { + for (var pos in res.failures) { + deleteKeys.splice(parseInt(pos), 1); + } + applyMutateResult(addValues.length, res); + })).then(function (res) { return putValues.length > 0 && + coreTable.mutate({ trans: trans, type: 'put', keys: putKeys, values: putValues }) + .then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return deleteKeys.length > 0 && + coreTable.mutate({ trans: trans, type: 'delete', keys: deleteKeys }) + .then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { + return keys$$1.length > offset + count && nextChunk(offset + limit); + }); + }); + }; + return nextChunk(0).then(function () { + if (totalFailures.length > 0) + throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); + return keys$$1.length; + }); + }); + }); + }; + Collection.prototype.delete = function () { + var ctx = this._ctx, range = ctx.range; + if (isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 )) + { + return this._write(function (trans) { + var primaryKey = ctx.table.core.schema.primaryKey; + var coreRange = range; + return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) { + return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange }) + .then(function (_a) { + var failures = _a.failures, lastResult = _a.lastResult, results = _a.results, numFailures = _a.numFailures; + if (numFailures) + throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures); + return count - numFailures; + }); + }); + }); + } + return this.modify(function (value, ctx) { return ctx.value = null; }); + }; + return Collection; +}()); + +function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection$$1(whereClause, keyRangeGenerator) { + this.db = db; + var keyRange = AnyRange, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + var whereCtx = whereClause._ctx; + var table = whereCtx.table; + var readingHook = table.hook.reading.fire; + 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, + isMatch: null, + offset: 0, + limit: Infinity, + error: error, + or: whereCtx.or, + valueMapper: readingHook !== mirror ? readingHook : null + }; + }); +} + +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 fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new collectionOrWhereClause.Collection(collectionOrWhereClause) : + collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; +} +function emptyCollection(whereClause) { + return new whereClause.Collection(whereClause, function () { return rangeEqual(""); }).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.Collection(whereClause, function () { return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); + c._ondirectionchange = function (direction) { + 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; +} +function createRange(lower, upper, lowerOpen, upperOpen) { + return { + type: 2 , + lower: lower, + upper: upper, + lowerOpen: lowerOpen, + upperOpen: upperOpen + }; +} +function rangeEqual(value) { + return { + type: 1 , + lower: value, + upper: value + }; +} + +var WhereClause = (function () { + function WhereClause() { + } + Object.defineProperty(WhereClause.prototype, "Collection", { + get: function () { + return this._ctx.table.db.Collection; + }, + enumerable: true, + configurable: true + }); + WhereClause.prototype.between = function (lower, upper, includeLower, includeUpper) { + includeLower = includeLower !== false; + includeUpper = includeUpper === true; + try { + if ((this._cmp(lower, upper) > 0) || + (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); + return new this.Collection(this, function () { return createRange(lower, upper, !includeLower, !includeUpper); }); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }; + WhereClause.prototype.equals = function (value) { + return new this.Collection(this, function () { return rangeEqual(value); }); + }; + WhereClause.prototype.above = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, true); }); + }; + WhereClause.prototype.aboveOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, false); }); + }; + WhereClause.prototype.below = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value, false, true); }); + }; + WhereClause.prototype.belowOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value); }); + }; + WhereClause.prototype.startsWith = function (str) { + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }; + WhereClause.prototype.startsWithIgnoreCase = function (str) { + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); + }; + WhereClause.prototype.equalsIgnoreCase = function (str) { + return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); + }; + WhereClause.prototype.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, ""); + }; + WhereClause.prototype.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); + }; + WhereClause.prototype.anyOf = function () { + var _this = this; + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = this._cmp; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + var c = new this.Collection(this, function () { return createRange(set[0], set[set.length - 1]); }); + c._ondirectionchange = function (direction) { + compare = (direction === "next" ? + _this._ascending : + _this._descending); + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + ++i; + if (i === set.length) { + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + return true; + } + else { + advance(function () { cursor.continue(set[i]); }); + return false; + } + }); + return c; + }; + WhereClause.prototype.notEqual = function (value) { + return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.noneOf = function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new this.Collection(this); + try { + set.sort(this._ascending); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var ranges = set.reduce(function (res, val) { return res ? + res.concat([[res[res.length - 1][1], val]]) : + [[minKey, val]]; }, null); + ranges.push([set[set.length - 1], this.db._maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.inAnyRange = function (ranges, options) { + var _this = this; + var cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; + 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; + var includeUppers = options && options.includeUppers === true; + function addRange(ranges, newRange) { + var i = 0, l = ranges.length; + for (; 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]); } + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var rangePos = 0; + var keyIsBeyondCurrentEntry = includeUppers ? + function (key) { return ascending(key, set[rangePos][1]) > 0; } : + function (key) { return ascending(key, set[rangePos][1]) >= 0; }; + var keyIsBeforeCurrentEntry = includeLowers ? + function (key) { return descending(key, set[rangePos][0]) > 0; } : + function (key) { return descending(key, set[rangePos][0]) >= 0; }; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + var checkKey = keyIsBeyondCurrentEntry; + var c = new this.Collection(this, function () { return createRange(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)) { + ++rangePos; + if (rangePos === set.length) { + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + return true; + } + else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { + return false; + } + else { + advance(function () { + if (sortDirection === ascending) + cursor.continue(set[rangePos][0]); + else + cursor.continue(set[rangePos][1]); + }); + return false; + } + }); + return c; + }; + WhereClause.prototype.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]; })); + }; + return WhereClause; +}()); + +function createWhereClauseConstructor(db) { + return makeClassConstructor(WhereClause.prototype, function WhereClause$$1(table, index, orCollection) { + this.db = db; + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + var indexedDB = db._deps.indexedDB; + if (!indexedDB) + throw new exceptions.MissingAPI("indexedDB API missing"); + this._cmp = this._ascending = indexedDB.cmp.bind(indexedDB); + this._descending = function (a, b) { return indexedDB.cmp(b, a); }; + this._max = function (a, b) { return indexedDB.cmp(a, b) > 0 ? a : b; }; + this._min = function (a, b) { return indexedDB.cmp(a, b) < 0 ? a : b; }; + this._IDBKeyRange = db._deps.IDBKeyRange; + }); +} + +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} + +function getMaxKey(IdbKeyRange) { + try { + IdbKeyRange.only([[]]); + return [[]]; + } + catch (e) { + return maxString; + } +} + +function eventRejectHandler(reject) { + return wrap(function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }); +} + + + +function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); +} + +var Transaction = (function () { + function Transaction() { + } + Transaction.prototype._lock = function () { + assert(!PSD.global); + ++this._reculock; + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + }; + Transaction.prototype._unlock = function () { + assert(!PSD.global); + if (--this._reculock === 0) { + if (!PSD.global) + PSD.lockOwnerFor = null; + while (this._blockedFuncs.length > 0 && !this._locked()) { + var fnAndPSD = this._blockedFuncs.shift(); + try { + usePSD(fnAndPSD[1], fnAndPSD[0]); + } + catch (e) { } + } + } + return this; + }; + Transaction.prototype._locked = function () { + return this._reculock && PSD.lockOwnerFor !== this; + }; + Transaction.prototype.create = function (idbtrans) { + var _this = this; + if (!this.mode) + return this; + var idbdb = this.db.idbdb; + var dbOpenError = this.db._state.dbOpenError; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + 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); + _this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(function (ev) { + preventDefault(ev); + _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); + _this.active = false; + _this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(function () { + _this.active = false; + _this._resolve(); + }); + return this; + }; + Transaction.prototype._promise = function (mode, fn, bWriteLock) { + var _this = this; + if (mode === 'readwrite' && this.mode !== 'readwrite') + return rejection(new exceptions.ReadOnly("Transaction is readonly")); + if (!this.active) + return rejection(new exceptions.TransactionInactive()); + if (this._locked()) { + return new DexiePromise(function (resolve, reject) { + _this._blockedFuncs.push([function () { + _this._promise(mode, fn, bWriteLock).then(resolve, reject); + }, PSD]); + }); + } + else if (bWriteLock) { + return newScope(function () { + var p = new DexiePromise(function (resolve, reject) { + _this._lock(); + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p.finally(function () { return _this._unlock(); }); + p._lib = true; + return p; + }); + } + else { + var p = new DexiePromise(function (resolve, reject) { + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + }; + Transaction.prototype._root = function () { + return this.parent ? this.parent._root() : this; + }; + Transaction.prototype.waitFor = function (promiseLike) { + var root = this._root(); + var promise = DexiePromise.resolve(promiseLike); + if (root._waitingFor) { + root._waitingFor = root._waitingFor.then(function () { return promise; }); + } + else { + root._waitingFor = promise; + root._waitingQueue = []; + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; + while (root._waitingQueue.length) + (root._waitingQueue.shift())(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + }()); + } + var currentWaitPromise = root._waitingFor; + return new DexiePromise(function (resolve, reject) { + promise.then(function (res) { return root._waitingQueue.push(wrap(resolve.bind(null, res))); }, function (err) { return root._waitingQueue.push(wrap(reject.bind(null, err))); }).finally(function () { + if (root._waitingFor === currentWaitPromise) { + root._waitingFor = null; + } + }); + }); + }; + Transaction.prototype.abort = function () { + this.active && this._reject(new exceptions.Abort()); + this.active = false; + }; + Transaction.prototype.table = function (tableName) { + var memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); + if (hasOwn(memoizedTables, tableName)) + return memoizedTables[tableName]; + var tableSchema = this.schema[tableName]; + if (!tableSchema) { + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + } + var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); + transactionBoundTable.core = this.db.core.table(tableName); + memoizedTables[tableName] = transactionBoundTable; + return transactionBoundTable; + }; + return Transaction; +}()); + +function createTransactionConstructor(db) { + return makeClassConstructor(Transaction.prototype, function Transaction$$1(mode, storeNames, dbschema, parent) { + var _this = this; + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.idbtrans = null; + this.on = Events(this, "complete", "error", "abort"); + this.parent = parent || null; + this.active = true; + this._reculock = 0; + this._blockedFuncs = []; + this._resolve = null; + this._reject = null; + this._waitingFor = null; + this._waitingQueue = null; + this._spinCount = 0; + this._completion = new DexiePromise(function (resolve, reject) { + _this._resolve = resolve; + _this._reject = reject; + }); + this._completion.then(function () { + _this.active = false; + _this.on.complete.fire(); + }, function (e) { + var wasActive = _this.active; + _this.active = false; + _this.on.error.fire(e); + _this.parent ? + _this.parent._reject(e) : + wasActive && _this.idbtrans && _this.idbtrans.abort(); + return rejection(e); + }); + }); +} + +function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) { + return { + name: name, + keyPath: keyPath, + unique: unique, + multi: multi, + auto: auto, + compound: compound, + src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath) + }; +} +function nameFromKeyPath(keyPath) { + return typeof keyPath === 'string' ? + keyPath : + keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; +} + +function createTableSchema(name, primKey, indexes) { + return { + name: name, + primKey: primKey, + indexes: indexes, + mappedClass: null, + idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }) + }; +} + +function getKeyExtractor(keyPath) { + if (keyPath == null) { + return function () { return undefined; }; + } + else if (typeof keyPath === 'string') { + return getSinglePathKeyExtractor(keyPath); + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } +} +function getSinglePathKeyExtractor(keyPath) { + var split = keyPath.split('.'); + if (split.length === 1) { + return function (obj) { return obj[keyPath]; }; + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } +} + +function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); +} +function getExistingValues(table, req, effectiveKeys) { + return req.type === 'add' ? Promise.resolve(new Array(req.values.length)) : + table.getMany({ trans: req.trans, keys: effectiveKeys }); +} + +function arrayify(arrayLike) { + return [].slice.call(arrayLike); +} + +var _id_counter = 0; +function getKeyPathAlias(keyPath) { + return keyPath == null ? + ":id" : + typeof keyPath === 'string' ? + keyPath : + "[" + keyPath.join('+') + "]"; +} +function createDBCore(db, indexedDB, IdbKeyRange, tmpTrans) { + var cmp = indexedDB.cmp.bind(indexedDB); + function extractSchema(db, trans) { + var tables = arrayify(db.objectStoreNames); + return { + schema: { + name: db.name, + tables: tables.map(function (table) { return trans.objectStore(table); }).map(function (store) { + var keyPath = store.keyPath, autoIncrement = store.autoIncrement; + var compound = isArray(keyPath); + var outbound = keyPath == null; + var indexByKeyPath = {}; + var result = { + name: store.name, + primaryKey: { + name: null, + isPrimaryKey: true, + outbound: outbound, + compound: compound, + keyPath: keyPath, + autoIncrement: autoIncrement, + unique: true, + extractKey: getKeyExtractor(keyPath) + }, + indexes: arrayify(store.indexNames).map(function (indexName) { return store.index(indexName); }) + .map(function (index) { + var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath = index.keyPath; + var compound = isArray(keyPath); + var result = { + name: name, + compound: compound, + keyPath: keyPath, + unique: unique, + multiEntry: multiEntry, + extractKey: getKeyExtractor(keyPath) + }; + indexByKeyPath[getKeyPathAlias(keyPath)] = result; + return result; + }), + getIndexByKeyPath: function (keyPath) { return indexByKeyPath[getKeyPathAlias(keyPath)]; } + }; + indexByKeyPath[":id"] = result.primaryKey; + if (keyPath != null) { + indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; + } + return result; + }) + }, + hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) && + !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) + }; + } + function makeIDBKeyRange(range) { + if (range.type === 3 ) + return null; + if (range.type === 4 ) + throw new Error("Cannot convert never type to IDBKeyRange"); + var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; + var idbRange = lower === undefined ? + upper === undefined ? + null : + IdbKeyRange.upperBound(upper, !!upperOpen) : + upper === undefined ? + IdbKeyRange.lowerBound(lower, !!lowerOpen) : + IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); + return idbRange; + } + function createDbCoreTable(tableSchema) { + var tableName = tableSchema.name; + function mutate(_a) { + var trans = _a.trans, type = _a.type, keys$$1 = _a.keys, values = _a.values, range = _a.range, wantResults = _a.wantResults; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var outbound = store.keyPath == null; + var isAddOrPut = type === "put" || type === "add"; + if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') + throw new Error("Invalid operation type: " + type); + var length = (keys$$1 || values || { length: 1 }).length; + if (keys$$1 && values && keys$$1.length !== values.length) { + throw new Error("Given keys array must have same length as given values array."); + } + if (length === 0) + return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined }); + var results = wantResults && __spreadArrays((keys$$1 ? + keys$$1 : + getEffectiveKeys(tableSchema.primaryKey, { type: type, keys: keys$$1, values: values }))); + var req; + var failures = []; + var numFailures = 0; + var errorHandler = function (event) { + ++numFailures; + preventDefault(event); + if (results) + results[event.target._reqno] = undefined; + failures[event.target._reqno] = event.target.error; + }; + var setResult = function (_a) { + var target = _a.target; + results[target._reqno] = target.result; + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures: numFailures, failures: failures, results: results, lastResult: undefined }); + if (range.type === 3 ) + req = store.clear(); + else + req = store.delete(makeIDBKeyRange(range)); + } + else { + var _a = isAddOrPut ? + outbound ? + [values, keys$$1] : + [values, null] : + [keys$$1, null], args1 = _a[0], args2 = _a[1]; + if (isAddOrPut) { + for (var i = 0; i < length; ++i) { + req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i])); + req._reqno = i; + if (results && results[i] === undefined) { + req.onsuccess = setResult; + } + req.onerror = errorHandler; + } + } + else { + for (var i = 0; i < length; ++i) { + req = store[type](args1[i]); + req._reqno = i; + req.onerror = errorHandler; + } + } + } + var done = function (event) { + var lastResult = event.target.result; + if (results) + results[length - 1] = lastResult; + resolve({ + numFailures: numFailures, + failures: failures, + results: results, + lastResult: lastResult + }); + }; + req.onerror = function (event) { + errorHandler(event); + done(event); + }; + req.onsuccess = done; + }); + } + function openCursor(_a) { + var trans = _a.trans, values = _a.values, query = _a.query, reverse = _a.reverse, unique = _a.unique; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? + store : + store.index(index.name); + var direction = reverse ? + unique ? + "prevunique" : + "prev" : + unique ? + "nextunique" : + "next"; + var req = values || !('openKeyCursor' in source) ? + source.openCursor(makeIDBKeyRange(range), direction) : + source.openKeyCursor(makeIDBKeyRange(range), direction); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function (ev) { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + cursor.___id = ++_id_counter; + cursor.done = false; + var _cursorContinue = cursor.continue.bind(cursor); + var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; + if (_cursorContinuePrimaryKey) + _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); + var _cursorAdvance = cursor.advance.bind(cursor); + var doThrowCursorIsNotStarted = function () { throw new Error("Cursor not started"); }; + var doThrowCursorIsStopped = function () { throw new Error("Cursor not stopped"); }; + cursor.trans = trans; + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; + cursor.fail = wrap(reject); + cursor.next = function () { + var _this = this; + var gotOne = 1; + return this.start(function () { return gotOne-- ? _this.continue() : _this.stop(); }).then(function () { return _this; }); + }; + cursor.start = function (callback) { + var iterationPromise = new Promise(function (resolveIteration, rejectIteration) { + resolveIteration = wrap(resolveIteration); + req.onerror = eventRejectHandler(rejectIteration); + cursor.fail = rejectIteration; + cursor.stop = function (value) { + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; + resolveIteration(value); + }; + }); + var guardedCallback = function () { + if (req.result) { + try { + callback(); + } + catch (err) { + cursor.fail(err); + } + } + else { + cursor.done = true; + cursor.start = function () { throw new Error("Cursor behind last entry"); }; + cursor.stop(); + } + }; + req.onsuccess = wrap(function (ev) { + req.onsuccess = guardedCallback; + guardedCallback(); + }); + cursor.continue = _cursorContinue; + cursor.continuePrimaryKey = _cursorContinuePrimaryKey; + cursor.advance = _cursorAdvance; + guardedCallback(); + return iterationPromise; + }; + resolve(cursor); + }, reject); + }); + } + function query(hasGetAll) { + return function (request) { + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var trans = request.trans, values = request.values, limit = request.limit, query = request.query; + var nonInfinitLimit = limit === Infinity ? undefined : limit; + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + if (limit === 0) + return resolve({ result: [] }); + if (hasGetAll) { + var req = values ? + source.getAll(idbKeyRange, nonInfinitLimit) : + source.getAllKeys(idbKeyRange, nonInfinitLimit); + req.onsuccess = function (event) { return resolve({ result: event.target.result }); }; + req.onerror = eventRejectHandler(reject); + } + else { + var count_1 = 0; + var req_1 = values || !('openKeyCursor' in source) ? + source.openCursor(idbKeyRange) : + source.openKeyCursor(idbKeyRange); + var result_1 = []; + req_1.onsuccess = function (event) { + var cursor = req_1.result; + if (!cursor) + return resolve({ result: result_1 }); + result_1.push(values ? cursor.value : cursor.primaryKey); + if (++count_1 === limit) + return resolve({ result: result_1 }); + cursor.continue(); + }; + req_1.onerror = eventRejectHandler(reject); + } + }); + }; + } + return { + name: tableName, + schema: tableSchema, + mutate: mutate, + getMany: function (_a) { + var trans = _a.trans, keys$$1 = _a.keys; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var length = keys$$1.length; + var result = new Array(length); + var keyCount = 0; + var callbackCount = 0; + var valueCount = 0; + var req; + var successHandler = function (event) { + var req = event.target; + if ((result[req._pos] = req.result) != null) + ++valueCount; + if (++callbackCount === keyCount) + resolve(result); + }; + var errorHandler = eventRejectHandler(reject); + for (var i = 0; i < length; ++i) { + var key = keys$$1[i]; + if (key != null) { + req = store.get(keys$$1[i]); + req._pos = i; + req.onsuccess = successHandler; + req.onerror = errorHandler; + ++keyCount; + } + } + if (keyCount === 0) + resolve(result); + }); + }, + get: function (_a) { + var trans = _a.trans, key = _a.key; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var req = store.get(key); + req.onsuccess = function (event) { return resolve(event.target.result); }; + req.onerror = eventRejectHandler(reject); + }); + }, + query: query(hasGetAll), + openCursor: openCursor, + count: function (_a) { + var query = _a.query, trans = _a.trans; + var index = query.index, range = query.range; + return new Promise(function (resolve, reject) { + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); + req.onsuccess = wrap(function (ev) { return resolve(ev.target.result); }); + req.onerror = eventRejectHandler(reject); + }); + } + }; + } + var _a = extractSchema(db, tmpTrans), schema = _a.schema, hasGetAll = _a.hasGetAll; + var tables = schema.tables.map(function (tableSchema) { return createDbCoreTable(tableSchema); }); + var tableMap = {}; + tables.forEach(function (table) { return tableMap[table.name] = table; }); + return { + stack: "dbcore", + transaction: db.transaction.bind(db), + table: function (name) { + var result = tableMap[name]; + if (!result) + throw new Error("Table '" + name + "' not found"); + return tableMap[name]; + }, + cmp: cmp, + MIN_KEY: -Infinity, + MAX_KEY: getMaxKey(IdbKeyRange), + schema: schema + }; +} + +function createMiddlewareStack(stackImpl, middlewares) { + return middlewares.reduce(function (down, _a) { + var create = _a.create; + return (__assign(__assign({}, down), create(down))); + }, stackImpl); +} +function createMiddlewareStacks(middlewares, idbdb, _a, tmpTrans) { + var IDBKeyRange = _a.IDBKeyRange, indexedDB = _a.indexedDB; + var dbcore = createMiddlewareStack(createDBCore(idbdb, indexedDB, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore: dbcore + }; +} +function generateMiddlewareStacks(db, tmpTrans) { + var idbdb = tmpTrans.db; + var stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); + db.core = stacks.dbcore; + db.tables.forEach(function (table) { + var tableName = table.name; + if (db.core.schema.tables.some(function (tbl) { return tbl.name === tableName; })) { + table.core = db.core.table(tableName); + if (db[tableName] instanceof db.Table) { + db[tableName].core = table.core; + } + } + }); +} + +function setApiOnPlace(db, objs, tableNames, dbschema) { + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + if (!(tableName in obj)) { + if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { + setProp(obj, tableName, { + get: function () { return this.table(tableName); }, + set: function (value) { + defineProperty(this, tableName, { value: value, writable: true, configurable: true, enumerable: true }); + } + }); + } + else { + obj[tableName] = new db.Table(tableName, schema); + } + } + }); + }); +} +function removeTablesApi(db, objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof db.Table) + delete obj[key]; + } + }); +} +function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; +} +function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) { + var globalSchema = db._dbSchema; + var trans = db._createTransaction('readwrite', db._storeNames, globalSchema); + trans.create(idbUpgradeTrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + var transless = PSD.transless || PSD; + newScope(function () { + PSD.trans = trans; + PSD.transless = transless; + if (oldVersion === 0) { + keys(globalSchema).forEach(function (tableName) { + createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + generateMiddlewareStacks(db, idbUpgradeTrans); + DexiePromise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); + } + else + updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction); + }); +} +function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) { + var queue = []; + var versions = db._versions; + var globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); + 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(db, oldSchema, idbUpgradeTrans); + adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + diff.add.forEach(function (tuple) { + createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + var store_1 = idbUpgradeTrans.objectStore(change.name); + change.add.forEach(function (idx) { return addIndex(store_1, idx); }); + change.change.forEach(function (idx) { + store_1.deleteIndex(idx.name); + addIndex(store_1, idx); + }); + change.del.forEach(function (idxName) { return store_1.deleteIndex(idxName); }); + } + }); + var contentUpgrade = version._cfg.contentUpgrade; + if (contentUpgrade && version._cfg.version > oldVersion) { + generateMiddlewareStacks(db, idbUpgradeTrans); + anyContentUpgraderHasRun = true; + var upgradeSchema_1 = shallowClone(newSchema); + diff.del.forEach(function (table) { + upgradeSchema_1[table] = oldSchema[table]; + }); + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); + trans.schema = upgradeSchema_1; + var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); + if (contentUpgradeIsAsync_1) { + incrementExpectedAwaits(); + } + var returnValue_1; + var promiseFollowed = DexiePromise.follow(function () { + returnValue_1 = contentUpgrade(trans); + if (returnValue_1) { + if (contentUpgradeIsAsync_1) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue_1.then(decrementor, decrementor); + } + } + }); + return (returnValue_1 && typeof returnValue_1.then === 'function' ? + DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function () { return returnValue_1; })); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + var newSchema = version._cfg.dbschema; + deleteRemovedTables(newSchema, idbtrans); + } + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema); + trans.schema = db._dbSchema; + }); + }); + function runQueue() { + return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + DexiePromise.resolve(); + } + return runQueue().then(function () { + createMissingTables(globalSchema, idbUpgradeTrans); + }); +} +function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], + add: [], + change: [] + }; + var table; + for (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 && + !isIEOrEdge + ) { + change.recreate = true; + diff.change.push(change); + } + else { + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + var idxName = void 0; + for (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) { return 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 buildGlobalSchema(db, idbdb, tmpTrans) { + var globalSchema = {}; + var dbStoreNames = slice(idbdb.objectStoreNames, 0); + dbStoreNames.forEach(function (storeName) { + var store = tmpTrans.objectStore(storeName); + var keyPath = store.keyPath; + var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); + indexes.push(index); + } + globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); + }); + return globalSchema; +} +function readGlobalSchema(db, idbdb, tmpTrans) { + db.verno = idbdb.version / 10; + var globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); + db._storeNames = slice(idbdb.objectStoreNames, 0); + setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); +} +function adjustToExistingIndexNames(db, schema, idbtrans) { + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + db._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; + delete schema[storeName].idxByName[dexieName]; + schema[storeName].idxByName[indexName] = indexSpec; + } + } + } + } + if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + db._hasGetAll = false; + } +} +function parseIndexSyntax(primKeyAndIndexes) { + return primKeyAndIndexes.split(',').map(function (index, indexNum) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); + }); +} + +var Version = (function () { + function Version() { + } + Version.prototype._parseStoresSpec = function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multi-valued"); + 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"); + }); + outSchema[tableName] = createTableSchema(tableName, primKey, indexes); + } + }); + }; + Version.prototype.stores = function (stores) { + var db = this.db; + this._cfg.storesSource = this._cfg.storesSource ? + extend(this._cfg.storesSource, stores) : + stores; + var versions = db._versions; + var storesSpec = {}; + var dbschema = {}; + versions.forEach(function (version) { + extend(storesSpec, version._cfg.storesSource); + dbschema = (version._cfg.dbschema = {}); + version._parseStoresSpec(storesSpec, dbschema); + }); + db._dbSchema = dbschema; + removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]); + setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + db._storeNames = keys(dbschema); + return this; + }; + Version.prototype.upgrade = function (upgradeFunction) { + this._cfg.contentUpgrade = upgradeFunction; + return this; + }; + return Version; +}()); + +function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version$$1(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); +} + +var databaseEnumerator; +function DatabaseEnumerator(indexedDB) { + var hasDatabasesNative = indexedDB && typeof indexedDB.databases === 'function'; + var dbNamesTable; + if (!hasDatabasesNative) { + var db = new Dexie(DBNAMES_DB, { addons: [] }); + db.version(1).stores({ dbnames: 'name' }); + dbNamesTable = db.table('dbnames'); + } + return { + getDatabaseNames: function () { + return hasDatabasesNative + ? + DexiePromise.resolve(indexedDB.databases()).then(function (infos) { return infos + .map(function (info) { return info.name; }) + .filter(function (name) { return name !== DBNAMES_DB; }); }) + : + dbNamesTable.toCollection().primaryKeys(); + }, + add: function (name) { + return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.put({ name: name }).catch(nop); + }, + remove: function (name) { + return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.delete(name).catch(nop); + } + }; +} +function initDatabaseEnumerator(indexedDB) { + try { + databaseEnumerator = DatabaseEnumerator(indexedDB); + } + catch (e) { } +} + +function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); +} + +function dexieOpen(db) { + var state = db._state; + var indexedDB = db._deps.indexedDB; + if (state.isBeingOpened || db.idbdb) + return state.dbReadyPromise.then(function () { return state.dbOpenError ? + rejection(state.dbOpenError) : + db; }); + debug && (state.openCanceller._stackHolder = getErrorWithStack()); + state.isBeingOpened = true; + state.dbOpenError = null; + state.openComplete = false; + var resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null; + return DexiePromise.race([state.openCanceller, new DexiePromise(function (resolve, reject) { + 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 dbName = db.name; + var req = state.autoSchema ? + indexedDB.open(dbName) : + indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI("IndexedDB API not available"); + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(db._fireOnBlocked); + req.onupgradeneeded = wrap(function (e) { + upgradeTransaction = req.transaction; + if (state.autoSchema && !db._options.allowEmptyDB) { + req.onerror = preventDefault; + upgradeTransaction.abort(); + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); + delreq.onsuccess = delreq.onerror = wrap(function () { + reject(new exceptions.NoSuchDatabase("Database " + dbName + " doesnt exist")); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; + db.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(function () { + upgradeTransaction = null; + var idbdb = db.idbdb = req.result; + var objectStoreNames = slice(idbdb.objectStoreNames); + if (objectStoreNames.length > 0) + try { + var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); + if (state.autoSchema) + readGlobalSchema(db, idbdb, tmpTrans); + else + adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(function (ev) { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + databaseEnumerator.add(dbName); + resolve(); + }, reject); + })]).then(function () { + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(db.on.ready.fire)).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + var remainders = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(remainders)).then(fireRemainders); + } + }); + }).finally(function () { + state.onReadyBeingFired = null; + }).then(function () { + state.isBeingOpened = false; + return db; + }).catch(function (err) { + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (e) { } + state.isBeingOpened = false; + db.close(); + state.dbOpenError = err; + return rejection(state.dbOpenError); + }).finally(function () { + state.openComplete = true; + resolveDbReady(); + }); +} + +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)(); +} + +function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + scopeFunc = args.pop(); + var tables = flatten(args); + return [mode, tables, scopeFunc]; +} +function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) { + return DexiePromise.resolve().then(function () { + var transless = PSD.transless || PSD; + var trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); + var zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + trans.idbtrans = parentTransaction.idbtrans; + } + else { + trans.create(); + } + var scopeFuncIsAsync = isAsyncFunction(scopeFunc); + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var returnValue; + var promiseFollowed = DexiePromise.follow(function () { + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (scopeFuncIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === 'function' ? + DexiePromise.resolve(returnValue).then(function (x) { return trans.active ? + x + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) + : promiseFollowed.then(function () { return returnValue; })).then(function (x) { + if (parentTransaction) + trans._resolve(); + return trans._completion.then(function () { return x; }); + }).catch(function (e) { + trans._reject(e); + return rejection(e); + }); + }); +} + +function pad(a, value, count) { + var result = isArray(a) ? a.slice() : [a]; + for (var i = 0; i < count; ++i) + result.push(value); + return result; +} +function createVirtualIndexMiddleware(down) { + return __assign(__assign({}, down), { table: function (tableName) { + var table = down.table(tableName); + var schema = table.schema; + var indexLookup = {}; + var allVirtualIndexes = []; + function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { + var keyPathAlias = getKeyPathAlias(keyPath); + var indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); + var keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; + var isVirtual = keyTail > 0; + var virtualIndex = __assign(__assign({}, lowLevelIndex), { isVirtual: isVirtual, isPrimaryKey: !isVirtual && lowLevelIndex.isPrimaryKey, keyTail: keyTail, + keyLength: keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); + indexList.push(virtualIndex); + if (!virtualIndex.isPrimaryKey) { + allVirtualIndexes.push(virtualIndex); + } + if (keyLength > 1) { + var virtualKeyPath = keyLength === 2 ? + keyPath[0] : + keyPath.slice(0, keyLength - 1); + addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); + } + indexList.sort(function (a, b) { return a.keyTail - b.keyTail; }); + return virtualIndex; + } + var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); + indexLookup[":id"] = [primaryKey]; + for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) { + var index = _a[_i]; + addVirtualIndexes(index.keyPath, 0, index); + } + function findBestIndex(keyPath) { + var result = indexLookup[getKeyPathAlias(keyPath)]; + return result && result[0]; + } + function translateRange(range, keyTail) { + return { + type: range.type === 1 ? + 2 : + range.type, + lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), + lowerOpen: true, + upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), + upperOpen: true + }; + } + function translateRequest(req) { + var index = req.query.index; + return index.isVirtual ? __assign(__assign({}, req), { query: { + index: index, + range: translateRange(req.query.range, index.keyTail) + } }) : req; + } + var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey: primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function (req) { + return table.count(translateRequest(req)); + }, + query: function (req) { + return table.query(translateRequest(req)); + }, + openCursor: function (req) { + var _a = req.query.index, keyTail = _a.keyTail, isVirtual = _a.isVirtual, keyLength = _a.keyLength; + if (!isVirtual) + return table.openCursor(req); + function createVirtualCursor(cursor) { + function _continue(key) { + key != null ? + cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : + req.unique ? + cursor.continue(pad(cursor.key, req.reverse ? down.MIN_KEY : down.MAX_KEY, keyTail)) : + cursor.continue(); + } + var virtualCursor = Object.create(cursor, { + continue: { value: _continue }, + continuePrimaryKey: { + value: function (key, primaryKey) { + cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); + } + }, + key: { + get: function () { + var key = cursor.key; + return keyLength === 1 ? + key[0] : + key.slice(0, keyLength); + } + }, + value: { + get: function () { + return cursor.value; + } + } + }); + return virtualCursor; + } + return table.openCursor(translateRequest(req)) + .then(function (cursor) { return cursor && createVirtualCursor(cursor); }); + } }); + return result; + } }); +} +var virtualIndexMiddleware = { + stack: "dbcore", + name: "VirtualIndexMiddleware", + level: 1, + create: createVirtualIndexMiddleware +}; + +var hooksMiddleware = { + stack: "dbcore", + name: "HooksMiddleware", + level: 2, + create: function (downCore) { return (__assign(__assign({}, downCore), { table: function (tableName) { + var downTable = downCore.table(tableName); + var primaryKey = downTable.schema.primaryKey; + var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) { + var dxTrans = PSD.trans; + var _a = dxTrans.table(tableName).hook, deleting = _a.deleting, creating = _a.creating, updating = _a.updating; + switch (req.type) { + case 'add': + if (creating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'put': + if (creating.fire === nop && updating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'delete': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'deleteRange': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return deleteRange(req); }, true); + } + return downTable.mutate(req); + function addPutOrDelete(req) { + var dxTrans = PSD.trans; + var keys$$1 = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys$$1) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys$$1, wantResults: true }) : + __assign({}, req); + if (req.type !== 'delete') + req.values = __spreadArrays(req.values); + if (req.keys) + req.keys = __spreadArrays(req.keys); + return getExistingValues(downTable, req, keys$$1).then(function (existingValues) { + var contexts = keys$$1.map(function (key, i) { + var existingValue = existingValues[i]; + var ctx = { onerror: null, onsuccess: null }; + if (req.type === 'delete') { + deleting.fire.call(ctx, key, existingValue, dxTrans); + } + else if (req.type === 'add' || existingValue === undefined) { + var generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans); + if (key == null && generatedPrimaryKey != null) { + key = generatedPrimaryKey; + req.keys[i] = key; + if (!primaryKey.outbound) { + setByKeyPath(req.values[i], primaryKey.keyPath, key); + } + } + } + else { + var objectDiff = getObjectDiff(existingValue, req.values[i]); + var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); + if (additionalChanges_1) { + var requestedValue_1 = req.values[i]; + Object.keys(additionalChanges_1).forEach(function (keyPath) { + setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); + }); + } + } + return ctx; + }); + return downTable.mutate(req).then(function (_a) { + var failures = _a.failures, results = _a.results, numFailures = _a.numFailures, lastResult = _a.lastResult; + for (var i = 0; i < keys$$1.length; ++i) { + var primKey = results ? results[i] : keys$$1[i]; + var ctx = contexts[i]; + if (primKey == null) { + ctx.onerror && ctx.onerror(failures[i]); + } + else { + ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ? + req.values[i] : + primKey + ); + } + } + return { failures: failures, results: results, numFailures: numFailures, lastResult: lastResult }; + }).catch(function (error) { + contexts.forEach(function (ctx) { return ctx.onerror && ctx.onerror(error); }); + return Promise.reject(error); + }); + }); + } + function deleteRange(req) { + return deleteNextChunk(req.trans, req.range, 10000); + } + function deleteNextChunk(trans, range, limit) { + return downTable.query({ trans: trans, values: false, query: { index: primaryKey, range: range }, limit: limit }) + .then(function (_a) { + var result = _a.result; + return addPutOrDelete({ type: 'delete', keys: result, trans: trans }).then(function (res) { + if (res.numFailures > 0) + return Promise.reject(res.failures[0]); + if (result.length < limit) { + return { failures: [], numFailures: 0, lastResult: undefined }; + } + else { + return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); + } + }); + }); + } + } }); + return tableMiddleware; + } })); } +}; + +var Dexie = (function () { + function Dexie(name, options) { + var _this = this; + this._middlewares = {}; + this.verno = 0; + var deps = Dexie.dependencies; + this._options = options = __assign({ + addons: Dexie.addons, autoOpen: true, + indexedDB: deps.indexedDB, IDBKeyRange: deps.IDBKeyRange }, options); + this._deps = { + indexedDB: options.indexedDB, + IDBKeyRange: options.IDBKeyRange + }; + var addons = options.addons; + this._dbSchema = {}; + this._versions = []; + this._storeNames = []; + this._allTables = {}; + this.idbdb = null; + var state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true + }; + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + this._state = state; + this.name = name; + this.on = Events(this, "populate", "blocked", "versionchange", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { + return function (subscriber, bSticky) { + Dexie.vip(function () { + var state = _this._state; + if (state.openComplete) { + if (!state.dbOpenError) + DexiePromise.resolve().then(subscriber); + if (bSticky) + subscribe(subscriber); + } + else if (state.onReadyBeingFired) { + state.onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } + else { + subscribe(subscriber); + var db_1 = _this; + if (!bSticky) + subscribe(function unsubscribe() { + db_1.on.ready.unsubscribe(subscriber); + db_1.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.Collection = createCollectionConstructor(this); + this.Table = createTableConstructor(this); + this.Transaction = createTransactionConstructor(this); + this.Version = createVersionConstructor(this); + this.WhereClause = createWhereClauseConstructor(this); + this.on("versionchange", function (ev) { + if (ev.newVersion > 0) + console.warn("Another connection wants to upgrade database '" + _this.name + "'. Closing db now to resume the upgrade."); + else + console.warn("Another connection wants to delete database '" + _this.name + "'. Closing db now to resume the delete request."); + _this.close(); + }); + this.on("blocked", function (ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn("Dexie.delete('" + _this.name + "') was blocked"); + else + console.warn("Upgrade '" + _this.name + "' blocked by other connection holding version " + ev.oldVersion / 10); + }); + this._maxKey = getMaxKey(options.IDBKeyRange); + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new _this.Transaction(mode, storeNames, dbschema, parentTransaction); }; + this._fireOnBlocked = function (ev) { + _this.on("blocked").fire(ev); + connections + .filter(function (c) { return c.name === _this.name && c !== _this && !c._state.vcFired; }) + .map(function (c) { return c.on("versionchange").fire(ev); }); + }; + this.use(virtualIndexMiddleware); + this.use(hooksMiddleware); + addons.forEach(function (addon) { return addon(_this); }); + } + Dexie.prototype.version = function (versionNumber) { + if (isNaN(versionNumber) || versionNumber < 0.1) + throw new exceptions.Type("Given version is not a positive number"); + versionNumber = Math.round(versionNumber * 10) / 10; + if (this.idbdb || this._state.isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versions = this._versions; + var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; + if (versionInstance) + return versionInstance; + versionInstance = new this.Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + versionInstance.stores({}); + this._state.autoSchema = false; + return versionInstance; + }; + Dexie.prototype._whenReady = function (fn) { + var _this = this; + return this._state.openComplete || PSD.letThrough ? fn() : new DexiePromise(function (resolve, reject) { + if (!_this._state.isBeingOpened) { + if (!_this._options.autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + _this.open().catch(nop); + } + _this._state.dbReadyPromise.then(resolve, reject); + }).then(fn); + }; + Dexie.prototype.use = function (_a) { + var stack = _a.stack, create = _a.create, level = _a.level, name = _a.name; + if (name) + this.unuse({ stack: stack, name: name }); + var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); + middlewares.push({ stack: stack, create: create, level: level == null ? 10 : level, name: name }); + middlewares.sort(function (a, b) { return a.level - b.level; }); + return this; + }; + Dexie.prototype.unuse = function (_a) { + var stack = _a.stack, name = _a.name, create = _a.create; + if (stack && this._middlewares[stack]) { + this._middlewares[stack] = this._middlewares[stack].filter(function (mw) { + return create ? mw.create !== create : + name ? mw.name !== name : + false; + }); + } + return this; + }; + Dexie.prototype.open = function () { + return dexieOpen(this); + }; + Dexie.prototype.close = function () { + var idx = connections.indexOf(this), state = this._state; + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this.idbdb = null; + } + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + }; + Dexie.prototype.delete = function () { + var _this = this; + var hasArguments = arguments.length > 0; + var state = this._state; + return new DexiePromise(function (resolve, reject) { + var doDelete = function () { + _this.close(); + var req = _this._deps.indexedDB.deleteDatabase(_this.name); + req.onsuccess = wrap(function () { + databaseEnumerator.remove(_this.name); + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = _this._fireOnBlocked; + }; + if (hasArguments) + throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (state.isBeingOpened) { + state.dbReadyPromise.then(doDelete); + } + else { + doDelete(); + } + }); + }; + Dexie.prototype.backendDB = function () { + return this.idbdb; + }; + Dexie.prototype.isOpen = function () { + return this.idbdb !== null; + }; + Dexie.prototype.hasBeenClosed = function () { + var dbOpenError = this._state.dbOpenError; + return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); + }; + Dexie.prototype.hasFailed = function () { + return this._state.dbOpenError !== null; + }; + Dexie.prototype.dynamicallyOpened = function () { + return this._state.autoSchema; + }; + Object.defineProperty(Dexie.prototype, "tables", { + get: function () { + var _this = this; + return keys(this._allTables).map(function (name) { return _this._allTables[name]; }); + }, + enumerable: true, + configurable: true + }); + Dexie.prototype.transaction = function () { + var args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + }; + Dexie.prototype._transaction = function (mode, tables, scopeFunc) { + var _this = this; + var parentTransaction = PSD.trans; + if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) + parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); + var idbMode, storeNames; + try { + storeNames = tables.map(function (table) { + var storeName = table instanceof _this.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; + }); + if (mode == "r" || mode === READONLY) + idbMode = READONLY; + else if (mode == "rw" || mode == READWRITE) + idbMode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + if (parentTransaction.mode === READONLY && idbMode === READWRITE) { + if (onlyIfCompatible) { + 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) { + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + parentTransaction = null; + } + } + } + catch (e) { + return parentTransaction ? + parentTransaction._promise(null, function (_, reject) { reject(e); }) : + rejection(e); + } + var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); + return (parentTransaction ? + parentTransaction._promise(idbMode, enterTransaction, "lock") : + PSD.trans ? + usePSD(PSD.transless, function () { return _this._whenReady(enterTransaction); }) : + this._whenReady(enterTransaction)); + }; + Dexie.prototype.table = function (tableName) { + if (!hasOwn(this._allTables, tableName)) { + throw new exceptions.InvalidTable("Table " + tableName + " does not exist"); + } + return this._allTables[tableName]; + }; + return Dexie; +}()); + +var Dexie$1 = Dexie; +props(Dexie$1, __assign(__assign({}, fullNameExceptions), { + delete: function (databaseName) { + var db = new Dexie$1(databaseName); + return db.delete(); + }, + exists: function (name) { + return new Dexie$1(name, { addons: [] }).open().then(function (db) { + db.close(); + return true; + }).catch('NoSuchDatabaseError', function () { return false; }); + }, + getDatabaseNames: function (cb) { + return databaseEnumerator ? + databaseEnumerator.getDatabaseNames().then(cb) : + DexiePromise.resolve([]); + }, + defineClass: function () { + function Class(content) { + extend(this, content); + } + return Class; + }, + ignoreTransaction: function (scopeFunc) { + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : + scopeFunc(); + }, + vip: vip, async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return DexiePromise.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 DexiePromise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }, + currentTransaction: { + get: function () { return PSD.trans || null; } + }, waitFor: function (promiseOrFunction, optionalTimeout) { + var promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? + Dexie$1.ignoreTransaction(promiseOrFunction) : + promiseOrFunction) + .timeout(optionalTimeout || 60000); + return PSD.trans ? + PSD.trans.waitFor(promise) : + promise; + }, + Promise: DexiePromise, + debug: { + get: function () { return debug; }, + set: function (value) { + setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); + } + }, + derive: derive, extend: extend, props: props, override: override, + Events: Events, + getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, asap: asap, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: (function () { + try { + return { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; + } + catch (e) { + return { indexedDB: null, IDBKeyRange: null }; + } + })(), + 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)); }), + default: Dexie$1, + Dexie: Dexie$1 })); +Dexie$1.maxKey = getMaxKey(Dexie$1.dependencies.IDBKeyRange); + +initDatabaseEnumerator(Dexie.dependencies.indexedDB); +DexiePromise.rejectionMapper = mapError; +setDebug(debug, dexieStackFrameFilter); + +return Dexie; + +}))); +//# sourceMappingURL=dexie.js.map diff --git a/dist/dexie.js.map b/dist/dexie.js.map new file mode 100644 index 000000000..0543baa49 --- /dev/null +++ b/dist/dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.js","sources":["../node_modules/tslib/tslib.es6.js","../src/functions/utils.ts","../src/helpers/debug.ts","../src/errors/errors.js","../src/functions/chaining-functions.js","../src/helpers/promise.js","../src/functions/temp-transaction.ts","../src/globals/constants.ts","../src/functions/combine.ts","../src/dbcore/keyrange.ts","../src/classes/table/table.ts","../src/helpers/Events.js","../src/functions/make-class-constructor.ts","../src/classes/table/table-constructor.ts","../src/classes/collection/collection-helpers.ts","../src/classes/collection/collection.ts","../src/classes/collection/collection-constructor.ts","../src/functions/compare-functions.ts","../src/classes/where-clause/where-clause-helpers.ts","../src/classes/where-clause/where-clause.ts","../src/classes/where-clause/where-clause-constructor.ts","../src/functions/quirks.ts","../src/functions/event-wrappers.ts","../src/classes/transaction/transaction.ts","../src/classes/transaction/transaction-constructor.ts","../src/helpers/index-spec.ts","../src/helpers/table-schema.ts","../src/dbcore/get-key-extractor.ts","../src/dbcore/get-effective-keys.ts","../src/dbcore/dbcore-indexeddb.ts","../src/classes/dexie/generate-middleware-stacks.ts","../src/classes/version/schema-helpers.ts","../src/classes/version/version.ts","../src/classes/version/version-constructor.ts","../src/helpers/database-enumerator.ts","../src/classes/dexie/vip.ts","../src/classes/dexie/dexie-open.ts","../src/helpers/yield-support.ts","../src/classes/dexie/transaction-helpers.ts","../src/dbcore/virtual-index-middleware.ts","../src/hooks/hooks-middleware.ts","../src/classes/dexie/dexie.ts","../src/classes/dexie/dexie-static-props.ts","../src/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","declare var global;\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\nconst _global =\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\nif (typeof Promise !== 'undefined' && !_global.Promise){\n // In jsdom, this it can be the case that Promise is not put on the global object.\n // If so, we need to patch the global object for the rest of the code to work as expected.\n // Other dexie code expects Promise to be on the global object (like normal browser environments)\n _global.Promise = Promise;\n}\nexport { _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 const getProto = Object.getPrototypeOf;\nexport const _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(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options?) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {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 const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nconst _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 assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n // @ts-ignore\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array, extractor) {\n return array.reduce((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: (...args: any[])=>void, onerror, args?) : void {\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) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1);\n else delete obj[currentKeyPath];\n } 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) {\n if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);\n else delete obj[keyPath];\n } else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].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\nconst concat = [].concat;\nexport function flatten (a: (T | T[])[]) : T[] {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nconst intrinsicTypeNames =\n \"Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]);\nconst intrinsicTypes = intrinsicTypeNames.map(t=>_global[t]);\nconst intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, x=>[x,true]);\n\nexport function deepClone(any: T): T {\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 (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\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\nconst {toString} = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\nexport const getValueOf = (val:any, type: string) => \n type === \"Array\" ? ''+val.map(v => getValueOf(v, toStringTag(v))) :\n type === \"ArrayBuffer\" ? ''+new Uint8Array(val) :\n type === \"Date\" ? val.getTime() :\n ArrayBuffer.isView(val) ? ''+new Uint8Array(val.buffer) :\n val;\n\n export 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(prop => {\n if (!hasOwn(b, prop))\n 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)\n {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName === bpTypeName) {\n if (intrinsicTypeNameSet[apTypeName]) {\n // This is an intrinsic type. Don't go deep diffing it.\n // Instead compare its value in best-effort:\n // (Can compare real values of Date, ArrayBuffers and views)\n if (getValueOf(ap, apTypeName) !== getValueOf(bp, bpTypeName)) {\n rv[prfx + prop] = b[prop]; // Date / ArrayBuffer etc is of different value\n }\n } else {\n // This is not an intrinsic object. Compare the it deeply:\n getObjectDiff(ap, bp, rv, prfx + prop + \".\");\n }\n } else {\n rv[prfx + prop] = b[prop];// Property changed to other type\n } \n } else if (ap !== bp)\n rv[prfx + prop] = b[prop];// Primitive value changed\n }\n });\n keys(b).forEach(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 const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\nexport const getIteratorOf = iteratorSymbol ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\n\nexport const 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) 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--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\nexport const isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : ()=>false;\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 = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\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)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\n// TODO: Replace this in favor of a decorator instead.\nexport function deprecated (what: string, fn: (...args)=>T) {\n return function () {\n console.warn(`${what} is deprecated. See http://dexie.org/docs/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n } as (...args)=>T\n}\n","import { derive, setProp } from '../functions/utils';\nimport { getErrorWithStack, prettyStack } from '../helpers/debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\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 ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key=>failures[key].toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.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 this.message = getMultiErrorMessage(msg, failures);\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((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((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}${!inner ? '' : '\\n ' + inner}`;\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((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])\n 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((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\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, // 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, // 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, // 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 ?\n (res2 === undefined ? undefined : res2) :\n (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--) 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}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend} from '../functions/utils';\nimport {nop, callBoth, mirror} from '../functions/chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from '../errors';\n\n//\n// Promise and Zone (PSD) 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// 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 micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\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// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, 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.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 100,\n [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (()=>{\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, globalP.__proto__, globalP];\n // Generate a native promise (as window.Promise may have been patched)\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n nativeP.__proto__,\n globalP\n ];\n })(),\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nvar schedulePhysicalTick = resolvedGlobalPromise ?\n () => {resolvedGlobalPromise.then(physicalTick);}\n :\n _global.setImmediate ? \n // setImmediate supported. Those modern platforms also supports Function.bind().\n setImmediate.bind(null, physicalTick) :\n _global.MutationObserver ?\n // MutationObserver supported\n () => {\n var hiddenDiv = document.createElement(\"div\");\n (new MutationObserver(() => {\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 \n ()=>{setTimeout(physicalTick,0);};\n\n// Configurable 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 = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n pgp: false,\n env: {},\n finalize: function () {\n this.unhandleds.forEach(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\nexport default function DexiePromise(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 }\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)\n 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\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n if (possibleAwait) decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(DexiePromise.prototype, {\n then: thenProp, // Defined above.\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, PSD)); \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, err =>\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 : this.then(null, err =>\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 finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\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 timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\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 = zone;\n}\n\n// Promise Static Properties\nprops (DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof DexiePromise) return value;\n if (value && typeof value.then === 'function') return new DexiePromise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n //totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((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 // 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(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\nif (NativePromise) {\n if (NativePromise.allSettled) setProp (DexiePromise, \"allSettled\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined') setProp(DexiePromise, \"any\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0) reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => resolve(value),\n failure => {\n failures[i] = failure;\n if (!--remaining) reject(new AggregateError(failures));\n }));\n });\n });\n}\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\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(value => {\n if (promise._state !== null) return; // Already settled\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, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n 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(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\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(()=>{\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 ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\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 ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n 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 env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.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) { // 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().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\n\nexport function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nexport function 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(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) finalizers[--i](); \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(()=>{\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(p => 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) 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\nfunction PromiseReject (reason) {\n return new DexiePromise(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 switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: DexiePromise, configurable: true, writable: true},\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\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);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits(sourceTaskId) {\n if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) return;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n}\n\nif ((''+nativePromiseThen).indexOf('[native code]') === -1) {\n // If the native promise' prototype is patched, we cannot rely on zone echoing.\n // Disable that here:\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n //console.log(\"Total echoes \", totalEchoes);\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled) GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any) GlobalPromise.any = targetEnv.any;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction enqueueNativeMicroTask (job) {\n //\n // Precondition: nativePromiseThen !== undefined\n //\n nativePromiseThen.call(resolvedNativePromise, job);\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone, false),\n nativeAwaitCompatibleWrap(onRejected, zone, false));\n };\n}\n\nconst 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, 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 {_global.onunhandledrejection(event);} catch (_) {}\n }\n if (debug && event && !event.defaultPrevented) {\n console.warn(`Unhandled rejection: ${err.stack || err}`);\n }\n } catch (e) {}\n}\n\nexport var rejection = DexiePromise.reject;\n\nexport {DexiePromise};\n","import { PSD, rejection, newScope } from \"../helpers/promise\";\nimport { DexieOptions } from \"../public/types/dexie-constructor\";\nimport { exceptions } from \"../errors\";\nimport { nop } from \"./chaining-functions\";\nimport { Transaction } from \"../classes/transaction\";\nimport { Dexie } from '../classes/dexie';\n\n/* Generate a temporary transaction when db operations are done outside a transaction scope.\n*/\nexport function tempTransaction (\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n fn: (resolve, reject, trans: Transaction) => any)\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n{\n if (!db._state.openComplete && (!PSD.letThrough)) {\n if (!db._state.isBeingOpened) {\n if (!db._options.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try { trans.create(); } catch (ex) { return rejection(ex); }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(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(() => result);\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.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n}\n","import { Dexie } from \"../classes/dexie\";\n\nexport const DEXIE_VERSION = '{version}'; // Replaced by build-script.\nexport const maxString = String.fromCharCode(65535);\nexport const minKey = -Infinity; // minKey can be constant. maxKey must be a prop of Dexie (_maxKey)\nexport const INVALID_KEY_ARGUMENT =\n \"Invalid key provided. Keys must be of type string, number, Date or Array.\";\nexport const STRING_EXPECTED = \"String expected.\";\nexport const connections: Dexie[] = [];\nexport const isIEOrEdge =\n typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);\nexport const hasIEDeleteObjectStoreBug = isIEOrEdge;\nexport const hangsOnDeleteLargeKeyRange = isIEOrEdge;\nexport const dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nexport const DBNAMES_DB = '__dbnames';\nexport const READONLY = 'readonly';\nexport const READWRITE = 'readwrite';\n","export function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n","import { DBCoreKeyRange, DBCoreRangeType } from '../public/types/dbcore';\n\nexport const AnyRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Any,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]], // BUGBUG: depends on indexeddb impl.\n upperOpen: false\n}\n\nexport const NeverRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Never,\n lower: -Infinity,\n lowerOpen: true,\n upper: -Infinity,\n upperOpen: true\n}\n","import { BulkError, exceptions } from '../../errors';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { DexiePromise as Promise, PSD, newScope, wrap, rejection, beginMicroTickScope, endMicroTickScope } from '../../helpers/promise';\nimport { Transaction } from '../transaction';\nimport { Dexie } from '../dexie';\nimport { tempTransaction } from '../../functions/temp-transaction';\nimport { Collection } from '../collection';\nimport { isArray, keys, getByKeyPath, hasOwn, setByKeyPath, deepClone, tryCatch, arrayToObject, extend } from '../../functions/utils';\nimport { maxString } from '../../globals/constants';\nimport { combine } from '../../functions/combine';\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { IndexableType } from '../../public/types/indexable-type';\nimport { debug } from '../../helpers/debug';\nimport { DBCoreTable } from '../../public/types/dbcore';\nimport { AnyRange } from '../../dbcore/keyrange';\n\n/** class Table\n * \n * http://dexie.org/docs/Table/Table\n */\nexport class Table implements ITable {\n db: Dexie;\n _tx?: Transaction;\n name: string;\n schema: TableSchema;\n hook: TableHooks;\n core: DBCoreTable;\n\n _trans(\n mode: IDBTransactionMode,\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike | void,\n writeLocked?: boolean | string) : PromiseExtended\n {\n const trans: Transaction = this._tx || PSD.trans;\n const tableName = this.name;\n \n function checkTableInTransaction(resolve, reject, trans: Transaction) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n // Surround all in a microtick scope.\n // Reason: Browsers (modern Safari + older others)\n // still as of 2018-10-10 has problems keeping a transaction\n // alive between micro ticks. Safari because if transaction\n // is created but not used in same microtick, it will go\n // away. That specific issue could be solved in DBCore\n // by opening the transaction just before using it instead.\n // But older Firefoxes and IE11 (with Promise polyfills)\n // will still have probs.\n // The beginMicrotickScope()/endMicrotickScope() works\n // in cooperation with Dexie.Promise to orchestrate\n // the micro-ticks in endMicrotickScope() rather than\n // in native engine.\n const wasRootExec = beginMicroTickScope();\n try {\n return trans && trans.db === this.db ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n } finally {\n if (wasRootExec) endMicroTickScope();\n }\n }\n\n /** Table.get()\n * \n * http://dexie.org/docs/Table/Table.get()\n * \n **/\n get(keyOrCrit, cb?) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit as { [key: string]: IndexableType }).first(cb);\n\n return this._trans('readonly', (trans) => {\n return this.core.get({trans, key: keyOrCrit})\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n\n /** Table.where()\n * \n * http://dexie.org/docs/Table/Table.where()\n * \n **/\n where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n\n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix =>\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\n (ix.keyPath as string[]).every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\n\n if (compoundIndex && this.db._maxKey !== maxString)\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n return this\n .where(compoundIndex.name)\n .equals((compoundIndex.keyPath as string[]).map(kp => indexOrCrit[kp]));\n\n if (!compoundIndex && debug) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n\n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n const { idxByName } = this.schema;\n const idb = this.db._deps.indexedDB;\n\n function equals (a, b) {\n try {\n return idb.cmp(a,b) === 0; // Works with all indexable types including binary keys.\n } catch (e) {\n return false;\n }\n }\n\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index, // idx::=Pick index of first matching keypath\n prevIndex || !index ? // filter::=null if not needed, otherwise combine function filter\n combine(\n prevFilterFn,\n index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily with \"[a+b+c] is not indexed\"\n }\n\n /** Table.filter()\n * \n * http://dexie.org/docs/Table/Table.filter()\n * \n **/\n filter(filterFunction: (obj: any) => boolean) {\n return this.toCollection().and(filterFunction);\n }\n\n /** Table.count()\n * \n * http://dexie.org/docs/Table/Table.count()\n * \n **/\n count(thenShortcut?: any) {\n return this.toCollection().count(thenShortcut);\n }\n\n /** Table.offset()\n * \n * http://dexie.org/docs/Table/Table.offset()\n * \n **/\n offset(offset: number) {\n return this.toCollection().offset(offset);\n }\n\n /** Table.limit()\n * \n * http://dexie.org/docs/Table/Table.limit()\n * \n **/\n limit(numRows: number) {\n return this.toCollection().limit(numRows);\n }\n\n /** Table.each()\n * \n * http://dexie.org/docs/Table/Table.each()\n * \n **/\n each(callback: (obj: any, cursor: { key: IndexableType, primaryKey: IndexableType }) => any) {\n return this.toCollection().each(callback);\n }\n\n /** Table.toArray()\n * \n * http://dexie.org/docs/Table/Table.toArray()\n * \n **/\n toArray(thenShortcut?: any) {\n return this.toCollection().toArray(thenShortcut);\n }\n\n /** Table.toCollection()\n * \n * http://dexie.org/docs/Table/Table.toCollection()\n * \n **/\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n\n /** Table.orderBy()\n * \n * http://dexie.org/docs/Table/Table.orderBy()\n * \n **/\n orderBy(index: string | string[]) {\n return new this.db.Collection(\n new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n\n /** Table.reverse()\n * \n * http://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * http://dexie.org/docs/Table/Table.mapToClass()\n * \n **/\n mapToClass(constructor: Function) {\n this.schema.mappedClass = constructor;\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 const readHook = 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 const res = Object.create(constructor.prototype);\n // Clone members:\n for (var m in obj) if (hasOwn(obj, m)) try { res[m] = obj[m]; } 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\n /** @deprecated */\n defineClass() {\n function Class (content){\n extend(this, content);\n };\n return this.mapToClass(Class);\n }\n\n /** Table.add()\n * \n * http://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [obj]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (!this.core.schema.primaryKey.outbound) {\n try{setByKeyPath(obj, this.core.schema.primaryKey.keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * http://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; }): PromiseExtended {\n if (typeof modifications !== 'object' || isArray(modifications))\n 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(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\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 /** Table.put()\n * \n * http://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [obj], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (!this.core.schema.primaryKey.outbound) {\n try{setByKeyPath(obj, this.core.schema.primaryKey.keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * http://dexie.org/docs/Table/Table.delete()\n * \n **/\n delete(key: IndexableType): PromiseExtended {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'delete', keys: [key]}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.clear()\n * \n * http://dexie.org/docs/Table/Table.clear()\n * \n **/\n clear() {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'deleteRange', range: AnyRange}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.bulkGet()\n * \n * http://dexie.org/docs/Table/Table.bulkGet()\n * \n * @param keys \n */\n bulkGet(keys: IndexableType[]) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n\n /** Table.bulkAdd()\n * \n * http://dexie.org/docs/Table/Table.bulkAdd()\n * \n **/\n bulkAdd(\n objects: any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {outbound} = this.core.schema.primaryKey;\n if (!outbound && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objects, wantResults}\n )\n .then(({numFailures, results,lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`,\n Object.keys(failures).map(pos => failures[pos]));\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * http://dexie.org/docs/Table/Table.bulkPut()\n * \n **/\n bulkPut(\n objects: any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {outbound} = this.core.schema.primaryKey;\n if (!outbound && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objects, wantResults}\n )\n .then(({numFailures, results, lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`,\n Object.keys(failures).map(pos => failures[pos]));\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * http://dexie.org/docs/Table/Table.bulkDelete()\n * \n **/\n bulkDelete(keys: ReadonlyArray): PromiseExtended {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'delete', keys: keys as IndexableType[]});\n }).then(({numFailures, lastResult, failures}) => {\n if (numFailures === 0) return lastResult;\n throw new BulkError(\n `${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n","import {keys, isArray, asap} from '../functions/utils';\nimport {nop, mirror, reverseStoppableEventChain} from '../functions/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, args = new Array(i - 1);\n while (--i) 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) { return fn !== cb; });\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, args = new Array(i);\n while (i--) 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}\n","import { arrayToObject, derive } from './utils';\n\n\nexport function makeClassConstructor (prototype: Object, constructor: Function) {\n /*const propertyDescriptorMap = arrayToObject(\n Object.getOwnPropertyNames(prototype),\n propKey => [propKey, Object.getOwnPropertyDescriptor(prototype, propKey)]);\n\n // Both derive and clone the prototype.\n // derive: So that x instanceof T returns true when T is the class template.\n // clone: Optimizes method access a bit (but actually not nescessary)\n const derivedPrototypeClone = Object.create(prototype, propertyDescriptorMap);\n derivedPrototypeClone.constructor = constructor;\n constructor.prototype = derivedPrototypeClone;\n return constructor as any as TConstructor;*/\n\n // Keep the above code in case we want to clone AND derive the parent prototype.\n // Reason would be optimization of property access.\n // The code below will only create a prototypal inheritance from given constructor function\n // to given prototype.\n derive(constructor).from({prototype});\n return constructor as any as TConstructor; \n}\n","import { Dexie } from '../dexie';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { Transaction } from '../transaction/transaction';\nimport { hookCreatingChain, pureFunctionChain, nop, mirror, hookUpdatingChain, hookDeletingChain } from '../../functions/chaining-functions';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { Table } from './table';\nimport Events from '../../helpers/Events';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\n\nexport interface TableConstructor {\n new (name: string, tableSchema: TableSchema, optionalTrans?: Transaction) : Table;\n prototype: Table;\n}\n\n/** Generates a Table constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTableConstructor (db: Dexie) {\n return makeClassConstructor(\n Table.prototype,\n\n function Table (this: Table, name: string, tableSchema: TableSchema, trans?: Transaction) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n }) as TableHooks;\n }\n\n );\n}\n","import { combine } from \"../../functions/combine\";\nimport { exceptions } from \"../../errors\";\nimport { hasOwn } from \"../../functions/utils\";\nimport { wrap } from \"../../helpers/promise\";\nimport { Collection } from './';\nimport { DBCoreCursor, DBCoreTable, DBCoreTransaction, DBCoreTableSchema, DBCoreRangeType } from '../../public/types/dbcore';\nimport { nop } from '../../functions/chaining-functions';\n\ntype CollectionContext = Collection[\"_ctx\"];\n\nexport function isPlainKeyRange (ctx: CollectionContext, ignoreLimitFilter?: boolean) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n} \n\nexport function addFilter(ctx: CollectionContext, fn: Function) {\n ctx.filter = combine(ctx.filter, fn);\n}\n\nexport function addReplayFilter (ctx: CollectionContext, factory, isLimitFilter?) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\n\nexport function addMatchFilter(ctx: CollectionContext, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\n\nexport function getIndexOrStore(ctx: CollectionContext, coreSchema: DBCoreTableSchema) {\n // TODO: Rewrite this. No need to know ctx.isPrimKey. ctx.index should hold the keypath.\n // Still, throw if not found!\n if (ctx.isPrimKey) return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\n\nexport function openCursor(ctx: CollectionContext, coreTable: DBCoreTable, trans: DBCoreTransaction) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index, \n range: ctx.range\n }\n });\n}\n\nexport function iter (\n ctx: CollectionContext, \n fn: (item, cursor: DBCoreCursor, advance: Function)=>void,\n coreTrans: DBCoreTransaction,\n coreTable: DBCoreTable): Promise\n{\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(\n openCursor(ctx, coreTable, coreTrans),\n combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n } else {\n const set = {};\n\n const union = (item: any, cursor: DBCoreCursor, advance) => {\n if (!filter || filter(cursor, advance, result=>cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\n\nfunction iterate(cursorPromise: Promise, filter, fn, valueMapper): Promise {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn);\n \n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(()=>{\n var c = ()=>cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val=>{cursor.stop(val);c=nop}, e => {cursor.fail(e);c = nop;}))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n","import { Collection as ICollection } from \"../../public/types/collection\";\nimport { Dexie } from \"../dexie\";\nimport { Table } from \"../table\";\nimport { IndexableType, IndexableTypeArrayReadonly } from \"../../public/types/indexable-type\";\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { iter, isPlainKeyRange, getIndexOrStore, addReplayFilter, addFilter, addMatchFilter } from \"./collection-helpers\";\nimport { rejection } from \"../../helpers/promise\";\nimport { combine } from \"../../functions/combine\";\nimport { extend, hasOwn, deepClone, keys, setByKeyPath, getByKeyPath } from \"../../functions/utils\";\nimport { ModifyError } from \"../../errors\";\nimport { hangsOnDeleteLargeKeyRange } from \"../../globals/constants\";\nimport { ThenShortcut } from \"../../public/types/then-shortcut\";\nimport { Transaction } from '../transaction';\nimport { DBCoreCursor, DBCoreTransaction, DBCoreRangeType, DBCoreMutateResponse, DBCoreKeyRange } from '../../public/types/dbcore';\n\n/** class Collection\n * \n * http://dexie.org/docs/Collection/Collection\n */\nexport class Collection implements ICollection {\n db: Dexie;\n _ctx: {\n table: Table;\n index?: string | null;\n isPrimKey?: boolean;\n range: DBCoreKeyRange;\n keysOnly: boolean;\n dir: \"next\" | \"prev\";\n unique: \"\" | \"unique\";\n algorithm?: Function | null;\n filter?: Function | null;\n replayFilter: Function | null;\n justLimit: boolean; // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: Function | null;\n offset: number,\n limit: number,\n error: any, // If set, any promise must be rejected with this error\n or: Collection,\n valueMapper: (any) => any\n }\n \n _ondirectionchange?: Function;\n\n _read(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike, cb?): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n\n _write(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n }\n\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n\n _iterate(\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction) : Promise\n {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n\n /** Collection.clone()\n * \n * http://dexie.org/docs/Collection/Collection.clone()\n * \n **/\n clone(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 /** Collection.raw()\n * \n * http://dexie.org/docs/Collection/Collection.raw()\n * \n **/\n raw() {\n this._ctx.valueMapper = null;\n return this;\n }\n\n /** Collection.each()\n * \n * http://dexie.org/docs/Collection/Collection.each()\n * \n **/\n each(fn: (obj, cursor: DBCoreCursor) => any): PromiseExtended {\n var ctx = this._ctx;\n\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n\n /** Collection.count()\n * \n * http://dexie.org/docs/Collection/Collection.count()\n * \n **/\n count(cb?) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(()=>count);\n }\n }).then(cb);\n }\n\n /** Collection.sortBy()\n * \n * http://dexie.org/docs/Collection/Collection.sortBy()\n * \n **/\n sortBy(keyPath: string): PromiseExtended;\n sortBy(keyPath: string, thenShortcut: ThenShortcut) : PromiseExtended;\n sortBy(keyPath: string, cb?: ThenShortcut) {\n const 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 /** Collection.toArray()\n * \n * http://dexie.org/docs/Collection/Collection.toArray()\n * \n **/\n toArray(cb?): PromiseExtended {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n const {valueMapper} = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({result}) => valueMapper ? result.map(valueMapper) : result);\n } else {\n // Getting array through a cursor.\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(()=>a);\n }\n }, cb);\n }\n\n /** Collection.offset()\n * \n * http://dexie.org/docs/Collection/Collection.offset()\n * \n **/\n offset(offset: number) : Collection{\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n\n /** Collection.limit()\n * \n * http://dexie.org/docs/Collection/Collection.limit()\n * \n **/\n limit(numRows: number) : Collection {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, () => {\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 /** Collection.until()\n * \n * http://dexie.org/docs/Collection/Collection.until()\n * \n **/\n until(filterFunction: (x) => boolean, bIncludeStopEntry?) {\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 /** Collection.first()\n * \n * http://dexie.org/docs/Collection/Collection.first()\n * \n **/\n first(cb?) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.last()\n * \n * http://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * http://dexie.org/docs/Collection/Collection.filter()\n * \n **/\n filter(filterFunction: (x) => boolean): Collection {\n /// function(val){return true/false}\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 /** Collection.and()\n * \n * http://dexie.org/docs/Collection/Collection.and()\n * \n **/\n and(filter: (x) => boolean) {\n return this.filter(filter);\n }\n\n /** Collection.or()\n * \n * http://dexie.org/docs/Collection/Collection.or()\n * \n **/\n or(indexName: string) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n\n /** Collection.reverse()\n * \n * http://dexie.org/docs/Collection/Collection.reverse()\n * \n **/\n reverse() {\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 /** Collection.desc()\n * \n * http://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * http://dexie.org/docs/Collection/Collection.eachKey()\n * \n **/\n eachKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n\n /** Collection.eachUniqueKey()\n * \n * http://dexie.org/docs/Collection/Collection.eachUniqueKey()\n * \n **/\n eachUniqueKey(cb?) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n\n /** Collection.eachPrimaryKey()\n * \n * http://dexie.org/docs/Collection/Collection.eachPrimaryKey()\n * \n **/\n eachPrimaryKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n\n /** Collection.keys()\n * \n * http://dexie.org/docs/Collection/Collection.keys()\n * \n **/\n keys(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 /** Collection.primaryKeys()\n * \n * http://dexie.org/docs/Collection/Collection.primaryKeys()\n * \n **/\n primaryKeys(cb?) : PromiseExtended {\n var ctx = this._ctx;\n if (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(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }});\n }).then(({result})=>result).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 /** Collection.uniqueKeys()\n * \n * http://dexie.org/docs/Collection/Collection.uniqueKeys()\n * \n **/\n uniqueKeys(cb?) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n\n /** Collection.firstKey()\n * \n * http://dexie.org/docs/Collection/Collection.firstKey()\n * \n **/\n firstKey(cb?) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.lastKey()\n * \n * http://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * http://dexie.org/docs/Collection/Collection.distinct()\n * \n **/\n distinct() {\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: DBCoreCursor) {\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 // Methods that mutate storage\n //\n\n /** Collection.modify()\n * \n * http://dexie.org/docs/Collection/Collection.modify()\n * \n **/\n modify(changes: { [keyPath: string]: any }) : PromiseExtended\n modify(changes: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean): PromiseExtended {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean\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 modifyer = changes;\n } else {\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], 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 }\n\n const coreTable = ctx.table.core;\n const {outbound, extractKey} = coreTable.schema.primaryKey;\n const limit = 'testmode' in Dexie ? 1 : 2000;\n const {cmp} = this.db.core;\n const totalFailures = [];\n let successCount = 0;\n const failedKeys: IndexableType[] = [];\n const applyMutateResult = (expectedCount: number, res: DBCoreMutateResponse) => {\n const {failures, numFailures} = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n }\n return this.clone().primaryKeys().then(keys => {\n\n const nextChunk = (offset: number) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({trans, keys: keys.slice(offset, offset + count)}).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i=0; i 0 &&\n coreTable.mutate({trans, type: 'add', values: addValues})\n .then(res => {\n for (let pos in res.failures) {\n // Remove from deleteKeys the key of the object that failed to change its primary key\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })\n ).then(res=>putValues.length > 0 &&\n coreTable.mutate({trans, type: 'put', keys: putKeys, values: putValues})\n .then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>deleteKeys.length > 0 &&\n coreTable.mutate({trans, type: 'delete', keys: deleteKeys})\n .then(res=>applyMutateResult(deleteKeys.length, res))\n ).then(()=>{\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n }\n\n return nextChunk(0).then(()=>{\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys as IndexableTypeArrayReadonly);\n\n return keys.length;\n });\n });\n\n });\n }\n\n /** Collection.delete()\n * \n * http://dexie.org/docs/Collection/Collection.delete()\n * \n **/\n delete() : PromiseExtended {\n var ctx = this._ctx,\n range = ctx.range;\n //deletingHook = ctx.table.hook.deleting.fire,\n //hasDeleteHook = deletingHook !== nop;\n if (isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === DBCoreRangeType.Any)) // 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(trans => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n const {primaryKey} = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({trans, query: {index: primaryKey, range: coreRange}}).then(count => {\n return ctx.table.core.mutate({trans, type: 'deleteRange', range: coreRange})\n .then(({failures, lastResult, results, numFailures}) => {\n if (numFailures) throw new ModifyError(\"Could not delete some values\",\n Object.keys(failures).map(pos => failures[pos]),\n count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n\n return this.modify((value, ctx) => ctx.value = null);\n }\n}\n\n\n","import { Dexie } from '../../classes/dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Collection } from './collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\nimport { mirror } from '../../functions/chaining-functions';\n\n/** Constructs a Collection instance. */\nexport interface CollectionConstructor {\n new(whereClause?: WhereClause | null, keyRangeGenerator?: () => DBCoreKeyRange): Collection;\n prototype: Collection;\n}\n\n/** Generates a Collection constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createCollectionConstructor(db: Dexie) {\n return makeClassConstructor(\n Collection.prototype,\n\n function Collection(\n this: Collection,\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange)\n {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\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: readingHook !== mirror ? readingHook : null\n };\n }\n );\n}\n","import { IndexableType } from '../public/types/indexable-type';\n\nexport function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\n\nexport function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n","import { WhereClause } from './where-clause';\nimport { Collection } from '../collection';\nimport { STRING_EXPECTED } from '../../globals/constants';\nimport { simpleCompare, simpleCompareReverse } from '../../functions/compare-functions';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange, DBCoreRangeType } from '../../public/types/dbcore';\n\nexport function fail(collectionOrWhereClause: Collection | WhereClause, err, T?) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\n\nexport function emptyCollection(whereClause: WhereClause) {\n return new whereClause.Collection (whereClause, () => rangeEqual(\"\")).limit(0);\n}\n\nexport function upperFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toUpperCase() :\n (s: string) => s.toLowerCase();\n}\n\nexport function lowerFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toLowerCase() :\n (s: string) => s.toUpperCase();\n}\n\nexport 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\nexport function addIgnoreCaseAlgorithm(whereClause: WhereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\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){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new whereClause.Collection (\n whereClause,\n ()=>createRange(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 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\n\nexport function createRange (lower: IndexableType, upper: IndexableType, lowerOpen?: boolean, upperOpen?: boolean): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Range,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\n\nexport function rangeEqual (value: IndexableType) : DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Equal,\n lower: value,\n upper: value\n };\n}\n","import { WhereClause as IWhereClause } from \"../../public/types/where-clause\";\nimport { Collection } from \"../collection\";\nimport { Table } from \"../table\";\nimport { IndexableType } from \"../../public/types/indexable-type\";\nimport { emptyCollection, fail, addIgnoreCaseAlgorithm, createRange, rangeEqual } from './where-clause-helpers';\nimport { INVALID_KEY_ARGUMENT, STRING_EXPECTED, maxString, minKey } from '../../globals/constants';\nimport { getArrayOf, NO_CHAR_ARRAY } from '../../functions/utils';\nimport { exceptions } from '../../errors';\nimport { Dexie } from '../dexie';\nimport { Collection as ICollection} from \"../../public/types/collection\";\n\n/** class WhereClause\n * \n * http://dexie.org/docs/WhereClause/WhereClause\n */\nexport class WhereClause implements IWhereClause {\n db: Dexie;\n _IDBKeyRange: typeof IDBKeyRange;\n _ctx: {\n table: Table;\n index: string;\n or: Collection;\n }\n _cmp: (a: IndexableType, b: IndexableType) => number;\n _ascending: (a: IndexableType, b: IndexableType) => number;\n _descending: (a: IndexableType, b: IndexableType) => number;\n _min: (a: IndexableType, b: IndexableType) => IndexableType;\n _max: (a: IndexableType, b: IndexableType) => IndexableType;\n\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n\n /** WhereClause.between()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.between()\n * \n **/\n between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean) {\n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\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.\n return new this.Collection(this, ()=>createRange(lower, upper, !includeLower, !includeUpper));\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n\n /** WhereClause.equals()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.above()\n * \n **/\n above(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n\n /** WhereClause.aboveOrEqual()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.aboveOrEqual()\n * \n **/\n aboveOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n\n /** WhereClause.below()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.below()\n * \n **/\n below(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n\n /** WhereClause.belowOrEqual()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.belowOrEqual()\n * \n **/\n belowOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n\n /** WhereClause.startsWith()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWith()\n * \n **/\n startsWith(str: string) {\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n\n /** WhereClause.startsWithIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWithIgnoreCase()\n * \n **/\n startsWithIgnoreCase(str: string) {\n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n\n /** WhereClause.equalsIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.equalsIgnoreCase()\n * \n **/\n equalsIgnoreCase(str: string) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n\n /** WhereClause.anyOfIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.anyOfIgnoreCase()\n * \n **/\n anyOfIgnoreCase(...values: string[]): Collection;\n anyOfIgnoreCase(values: string[]): Collection;\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n\n /** WhereClause.startsWithAnyOfIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOfIgnoreCase()\n * \n **/\n startsWithAnyOfIgnoreCase(...values: string[]): Collection;\n startsWithAnyOfIgnoreCase(values: string[]): Collection;\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n\n /** WhereClause.anyOf()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.anyOf()\n * \n **/\n anyOf(...values: string[]): Collection;\n anyOf(values: string[]): Collection;\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const 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(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.notEqual()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.notEqual()\n * \n **/\n notEqual(value: IndexableType) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.noneOf()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.noneOf()\n * \n **/\n noneOf(...values: string[]): Collection;\n noneOf(values: string[]): Collection;\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this.Collection(this); // Return entire collection.\n try { set.sort(this._ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n const ranges = set.reduce(\n (res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]],\n null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.inAnyRange()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.inAnyRange()\n * \n **/\n inAnyRange(\n ranges: ReadonlyArray<{ 0: IndexableType, 1: IndexableType }>,\n options?: { includeLowers?: boolean, includeUppers?: boolean })\n {\n const cmp = this._cmp,\n ascending = this._ascending,\n descending = this._descending,\n min = this._min,\n max = this._max;\n\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(range =>\n range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(\n this,\n \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\",\n exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false; // Default to true\n const includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const 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)\n ranges.push(newRange);\n return ranges;\n }\n\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n\n // Join overlapping ranges\n let 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 let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n let checkKey = keyIsBeyondCurrentEntry;\n\n const c = new this.Collection(\n this,\n () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n\n c._ondirectionchange = 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((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++rangePos;\n if (rangePos === 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 (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][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(() => {\n if (sortDirection === ascending) cursor.continue(set[rangePos][0]);\n else cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.startsWithAnyOf()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOf()\n * \n **/\n startsWithAnyOf(...prefixes: string[]): Collection;\n startsWithAnyOf(prefixes: string[]): Collection;\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(s => typeof s === 'string')) {\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((str: string) => [str, str + maxString]));\n }\n\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { WhereClause } from './where-clause';\nimport { Table } from '../table';\nimport { Collection } from '../collection';\nimport { exceptions } from '../../errors';\n\nexport interface WhereClauseConstructor {\n new(table: Table, index?: string, orCollection?: Collection): WhereClause;\n prototype: WhereClause;\n}\n\n/** Generates a WhereClause constructor.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createWhereClauseConstructor(db: Dexie) {\n return makeClassConstructor(\n WhereClause.prototype,\n\n function WhereClause(this: WhereClause, table: Table, index?: string, orCollection?: Collection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n const indexedDB = db._deps.indexedDB;\n if (!indexedDB) throw new exceptions.MissingAPI(\"indexedDB API missing\");\n this._cmp = this._ascending = indexedDB.cmp.bind(indexedDB);\n this._descending = (a, b) => indexedDB.cmp(b, a);\n this._max = (a, b) => indexedDB.cmp(a,b) > 0 ? a : b;\n this._min = (a, b) => indexedDB.cmp(a,b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n }\n );\n}\n","import { maxString } from '../globals/constants';\n\nexport function safariMultiStoreFix(storeNames: string[]) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nexport function getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\nexport function getMaxKey (IdbKeyRange: typeof IDBKeyRange) {\n try {\n IdbKeyRange.only([[]]);\n return [[]];\n } catch (e) {\n return maxString;\n }\n}\n","import { wrap } from \"../helpers/promise\";\n\nexport function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nexport function eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nexport function 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,// 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\nexport function 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 ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\n\nexport function 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\nexport function BulkErrorHandlerCatchAll(errorList, done?, supportHooks?) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n}\n\n","import { Transaction as ITransaction } from '../../public/types/transaction';\nimport { DexiePromise, wrap, rejection } from \"../../helpers/promise\";\nimport { DbSchema } from '../../public/types/db-schema';\nimport { assert, hasOwn } from '../../functions/utils';\nimport { PSD, usePSD } from '../../helpers/promise';\nimport { Dexie } from '../dexie';\nimport { exceptions } from '../../errors';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { preventDefault } from '../../functions/event-wrappers';\nimport { newScope } from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { Table } from '../table';\n\n/** Transaction\n * \n * http://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n idbtrans: IDBTransaction;\n storeNames: string[];\n on: any;\n parent?: Transaction;\n schema: DbSchema;\n _memoizedTables: {[tableName: string]: Table};\n\n _reculock: number;\n _blockedFuncs: { 0: () => any, 1: any }[];\n _resolve: () => void;\n _reject: (Error) => void;\n _waitingFor: DexiePromise; // for waitFor()\n _waitingQueue: Function[]; // for waitFor()\n _spinCount: number; // Just for debugging waitFor()\n _completion: DexiePromise;\n\n //\n // Transaction internal methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _lock() {\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\n /** Transaction._unlock()\n * \n * Internal method.\n */\n _unlock() {\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 fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n }\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _locked() {\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\n /** Transaction.create()\n * \n * Internal method.\n * \n */\n create(idbtrans?: IDBTransaction) {\n if (!this.mode) return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\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); // Completion Promise must still be pending.\n\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode) as IDBTransaction;\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n });\n return this;\n }\n\n /** Transaction._promise()\n * \n * Internal method.\n */\n _promise(\n mode: IDBTransactionMode,\n fn: (resolve, reject, trans: Transaction) => PromiseLike | void,\n bWriteLock?: string | boolean): DexiePromise\n {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n\n /** Transaction._root()\n * \n * Internal method. Retrieves the root transaction in the tree of sub transactions.\n */\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n\n /** Transaction.waitFor()\n * \n * Internal method. Can be accessed from the public API through\n * Dexie.waitFor(): http://dexie.org/docs/Dexie/Dexie.waitFor()\n * \n **/\n waitFor(promiseLike: PromiseLike) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(() => promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n } \n\n /** Transaction.abort()\n * \n * http://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n this.active && this._reject(new exceptions.Abort());\n this.active = false;\n }\n\n /** Transaction.table()\n * \n * http://dexie.org/docs/Transaction/Transaction.table()\n */\n table(tableName: string) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\"); \n }\n\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Transaction } from './transaction';\nimport { DbSchema } from '../../public/types/db-schema';\nimport Events from '../../helpers/Events';\nimport Promise, { rejection } from '../../helpers/promise';\n\nexport interface TransactionConstructor {\n new (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parent?: Transaction) : T;\n prototype: T;\n}\n\n/** Generates a Transaction constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTransactionConstructor(db: Dexie) {\n return makeClassConstructor>(\n Transaction.prototype,\n function Transaction (\n this: Transaction,\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n \n });\n}\n","import { IndexSpec } from '../public/types/index-spec';\n\nexport function createIndexSpec(\n name: string,\n keyPath: string | string[],\n unique: boolean,\n multi: boolean,\n auto: boolean,\n compound: boolean,\n isPrimKey: boolean\n): IndexSpec {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n }\n}\n\nexport function nameFromKeyPath (keyPath?: string | string[]): string {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n","import { IndexSpec } from '../public/types/index-spec';\nimport { TableSchema } from '../public/types/table-schema';\nimport { createIndexSpec } from './index-spec';\nimport { arrayToObject } from '../functions/utils';\n\nexport function createTableSchema (\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n): TableSchema {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n","import { getByKeyPath } from '../functions/utils';\n\nexport function getKeyExtractor (keyPath: null | string | string[]) : (a: any) => any {\n if (keyPath == null) {\n return () => undefined;\n } else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nexport function getSinglePathKeyExtractor(keyPath: string) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n","import {\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreTable,\n} from \"../public/types/dbcore\";\n\nexport function getEffectiveKeys (\n primaryKey: DBCoreIndex,\n req: (Pick & {keys?: any[]}) | Pick)\n{\n //const {outbound} = primaryKey;\n if (req.type === 'delete') return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey)\n}\n\nexport function getExistingValues (table: DBCoreTable, req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest, effectiveKeys: any[]) {\n return req.type === 'add' ? Promise.resolve(new Array(req.values.length)) :\n table.getMany({trans: req.trans, keys: effectiveKeys});\n}\n","import {\n DBCore,\n DBCoreCursor,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryResponse,\n DBCoreRangeType,\n DBCoreSchema,\n DBCoreTableSchema,\n DBCoreTable,\n DBCoreMutateResponse,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { eventRejectHandler, preventDefault } from '../functions/event-wrappers';\nimport { wrap } from '../helpers/promise';\nimport { getMaxKey } from '../functions/quirks';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getEffectiveKeys } from './get-effective-keys';\n\nexport function arrayify(arrayLike: {length: number, [index: number]: T}): T[] {\n return [].slice.call(arrayLike);\n}\nexport function pick(obj: T, props: Prop[]): Pick {\n const result = {} as Pick;\n props.forEach(prop => result[prop] = obj[prop]);\n return result;\n}\n\nlet _id_counter = 0;\n\nexport function getKeyPathAlias(keyPath: null | string | string[]) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\n\nexport function createDBCore (\n db: IDBDatabase,\n indexedDB: IDBFactory,\n IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\n{\n const cmp = indexedDB.cmp.bind(indexedDB);\n \n function extractSchema(db: IDBDatabase, trans: IDBTransaction) : {schema: DBCoreSchema, hasGetAll: boolean} {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const {keyPath, autoIncrement} = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath: {[keyPathAlias: string]: DBCoreIndex} = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n } as DBCoreIndex,\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const {name, unique, multiEntry, keyPath} = index;\n const compound = isArray(keyPath);\n const result: DBCoreIndex = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath: null | string | string[]) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) // Bug with getAll() on Safari ver<604. See discussion following PR #579\n };\n }\n\n function makeIDBKeyRange (range: DBCoreKeyRange) : IDBKeyRange | null {\n if (range.type === DBCoreRangeType.Any) return null;\n if (range.type === DBCoreRangeType.Never) throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const {lower, upper, lowerOpen, upperOpen} = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null : //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)\n IdbKeyRange.upperBound(upper, !!upperOpen) : // below\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) : // above\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n\n function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {\n const tableName = tableSchema.name;\n\n function mutate ({trans, type, keys, values, range, wantResults}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error (\"Invalid operation type: \" + type);\n\n const {length} = keys || values || {length: 1}; // keys.length if keys. values.length if values. 1 if range.\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n // No items to write. Don't even bother!\n return resolve({numFailures: 0, failures: {}, results: [], lastResult: undefined});\n\n const results = wantResults && [...(keys ?\n keys : // keys already resolved in an earlier middleware. Don't re-resolve them.\n getEffectiveKeys(tableSchema.primaryKey, {type, keys, values}))];\n \n let req: IDBRequest & { _reqno?};\n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\n if (results) results[(event.target as any)._reqno] = undefined;\n failures[(event.target as any)._reqno] = event.target.error;\n };\n const setResult = ({target}) => {\n results[target._reqno] = target.result;\n }\n \n if (type === 'deleteRange') {\n // Here the argument is the range\n if (range.type === DBCoreRangeType.Never)\n return resolve({numFailures, failures, results, lastResult: undefined}); // Deleting the Never range shoulnt do anything.\n if (range.type === DBCoreRangeType.Any)\n req = store.clear(); // Deleting the Any range is equivalent to store.clear()\n else\n req = store.delete(makeIDBKeyRange(range));\n } else {\n // No matter add, put or delete - find out arrays of first and second arguments to it.\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n\n if (isAddOrPut) {\n for (let i=0; i {\n const lastResult = event.target.result;\n if (results) results[length-1] = lastResult;\n resolve({\n numFailures,\n failures,\n results,\n lastResult\n });\n };\n \n req.onerror = event => { // wrap() not needed. All paths calling outside will wrap!\n errorHandler(event);\n done(event);\n };\n \n req.onsuccess = done;\n });\n }\n \n function openCursor ({trans, values, query, reverse, unique}: DBCoreOpenCursorRequest): Promise\n {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n // source\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n // direction\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n // request\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n \n // iteration\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n\n const cursor = req.result as unknown as DBCoreCursor;\n if (!cursor) {\n resolve(null);\n return;\n }\n (cursor as any).___id = ++_id_counter;\n (cursor as any).done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey) _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = ()=>{throw new Error(\"Cursor not started\");}\n const doThrowCursorIsStopped = ()=>{throw new Error(\"Cursor not stopped\");}\n (cursor as any).trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function (this: DBCoreCursor) {\n // next() must work with \"this\" pointer in order to function correctly for ProxyCursors (derived objects)\n // without having to re-define next() on each child.\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n //console.log(\"Starting cursor\", (cursor as any).___id);\n const iterationPromise = new Promise((resolveIteration, rejectIteration) =>{\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n //console.log(\"Cursor stop\", cursor);\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n // Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()\n const guardedCallback = () => {\n if (req.result) {\n //console.log(\"Next result\", cursor);\n try {\n callback();\n } catch (err) {\n cursor.fail(err);\n }\n } else {\n (cursor as any).done = true;\n cursor.start = ()=>{throw new Error(\"Cursor behind last entry\");}\n cursor.stop();\n }\n }\n req.onsuccess = wrap(ev => {\n //cursor.continue = _cursorContinue;\n //cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n //cursor.advance = _cursorAdvance;\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject); \n });\n }\n \n function query (hasGetAll: boolean) {\n return (request: DBCoreQueryRequest) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {trans, values, limit, query} = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0) return resolve({result: []});\n if (hasGetAll) {\n const req = values ?\n (source as any).getAll(idbKeyRange, nonInfinitLimit) :\n (source as any).getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({result: event.target.result});\n req.onerror = eventRejectHandler(reject);\n } else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange)\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result as IDBCursorWithValue;\n if (!cursor) return resolve({result});\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit) return resolve({result});\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n \n return {\n name: tableName,\n schema: tableSchema,\n \n mutate,\n\n getMany ({trans, keys}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let valueCount = 0;\n let req: IDBRequest & {_pos?: number};\n \n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null) ++valueCount;\n if (++callbackCount === keyCount) resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n \n for (let i=0; i((resolve, reject) => {\n resolve = wrap (resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve((event.target as any).result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n\n query: query(hasGetAll),\n \n openCursor,\n\n count ({query, trans}) {\n const {index, range} = query;\n return new Promise((resolve, reject) => {\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve((ev.target as IDBRequest).result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n\n const {schema, hasGetAll} = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap: {[name: string]: DBCoreTable} = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n \n transaction: db.transaction.bind(db),\n\n table(name: string) {\n const result = tableMap[name];\n if (!result) throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n\n cmp,\n\n MIN_KEY: -Infinity,\n\n MAX_KEY: getMaxKey(IdbKeyRange),\n\n schema\n\n };\n}\n","import { Dexie } from './';\nimport { createDBCore } from '../../dbcore/dbcore-indexeddb';\nimport { DBCore } from '../../public/types/dbcore';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { DexieStacks, Middleware } from '../../public/types/middleware';\nimport { exceptions } from '../../errors';\n\nfunction createMiddlewareStack(\n stackImpl: {stack: string},\n middlewares: Middleware<{stack: string}>[]): TStack {\n return middlewares.reduce((down, {create}) => ({...down, ...create(down)}), stackImpl) as TStack;\n} \n\nfunction createMiddlewareStacks(\n middlewares: {[StackName in keyof DexieStacks]?: Middleware[]},\n idbdb: IDBDatabase,\n {IDBKeyRange, indexedDB}: DexieDOMDependencies,\n tmpTrans: IDBTransaction): {[StackName in keyof DexieStacks]?: DexieStacks[StackName]}\n{\n const dbcore = createMiddlewareStack(\n createDBCore(idbdb, indexedDB, IDBKeyRange, tmpTrans),\n middlewares.dbcore);\n \n // TODO: Create other stacks the same way as above. They might be dependant on the result\n // of creating dbcore stack.\n\n return {\n dbcore\n };\n}\n\nexport function generateMiddlewareStacks(db: Dexie, tmpTrans: IDBTransaction) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore!;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n","import { Dexie } from '../dexie';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { setProp, keys, slice, _global, isArray, shallowClone, isAsyncFunction, defineProperty } from '../../functions/utils';\nimport { Transaction } from '../transaction';\nimport { Version } from './version';\nimport Promise, { PSD, newScope, NativePromise, decrementExpectedAwaits, incrementExpectedAwaits } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { hasIEDeleteObjectStoreBug, isIEOrEdge } from '../../globals/constants';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { createIndexSpec, nameFromKeyPath } from '../../helpers/index-spec';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { generateMiddlewareStacks } from '../dexie/generate-middleware-stacks';\n\nexport function setApiOnPlace(db: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n if (!(tableName in obj)) {\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {\n get(this: Transaction) { return this.table(tableName); },\n set(value: any) {\n // Issue #1039\n // Let \"this.schema = dbschema;\" and other props in transaction constructor work even if there's a name collision with the table name.\n defineProperty(this, tableName, {value, writable: true, configurable: true, enumerable: true});\n }\n });\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\n\nexport function removeTablesApi(db: Dexie, objs: Object[]) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table) delete obj[key];\n }\n });\n}\n\nexport function lowerVersionFirst(a: Version, b: Version) {\n return a._cfg.version - b._cfg.version;\n}\n\nexport function runUpgraders(db: Dexie, oldVersion: number, idbUpgradeTrans: IDBTransaction, reject) {\n const globalSchema = db._dbSchema;\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n Promise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction);\n });\n}\n\nexport type UpgradeQueueItem = (idbtrans: IDBTransaction) => PromiseLike | void;\n\nexport function updateTablesAndIndexes(\n db: Dexie,\n oldVersion: number,\n trans: Transaction,\n idbUpgradeTrans: IDBTransaction)\n{\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 const queue: UpgradeQueueItem[] = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n\n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n\n globalSchema = db._dbSchema = newSchema;\n\n const diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n const store = idbUpgradeTrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(idx => addIndex(store, idx));\n // Update indexes\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n\n const contentUpgrade = version._cfg.contentUpgrade;\n\n if (contentUpgrade && version._cfg.version > oldVersion) {\n // Update db.core with new tables and indexes:\n generateMiddlewareStacks(db, idbUpgradeTrans);\n\n anyContentUpgraderHasRun = true;\n\n // Add to-be-deleted tables to contentUpgrade transaction\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n\n // Safe to affect Transaction.prototype globally in this moment,\n // because when this code runs, there may not be any other code\n // that can access any transaction instance, else than this particular\n // upgrader function.\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n\n // Support for native async await.\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n \n let returnValue: any;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n // contentUpgrade is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n Promise.resolve(returnValue) : promiseFollowed.then(()=>returnValue));\n }\n });\n queue.push(idbtrans => {\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.\n const newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n // Restore the final API\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\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) :\n Promise.resolve();\n }\n\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n}\n\nexport interface SchemaDiff {\n del: string[],\n add: [string, TableSchema][];\n change: TableSchemaDiff[];\n}\n\nexport interface TableSchemaDiff {\n name: string,\n recreate: boolean,\n del: string[],\n add: IndexSpec[],\n change: IndexSpec[]\n}\n\nexport function getSchemaDiff(oldSchema: DbSchema, newSchema: DbSchema): SchemaDiff {\n const diff: SchemaDiff = {\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 let table: string;\n for (table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n const 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 !isIEOrEdge // IE and non-chromium Edge has a bug reading spec of primary key\n ) \n { \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 const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName: string;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n 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\nexport function createTable(\n idbtrans: IDBTransaction,\n tableName: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n) {\n const store = idbtrans.db.createObjectStore(\n tableName,\n primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto }\n );\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\n\nexport function createMissingTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\n\nexport function deleteRemovedTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\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\nexport function addIndex(store: IDBObjectStore, idx: IndexSpec) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\n\nfunction buildGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(\n nameFromKeyPath(keyPath),\n keyPath || \"\",\n false,\n false,\n !!store.autoIncrement,\n keyPath && typeof keyPath !== \"string\",\n true\n );\n const indexes: IndexSpec[] = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(\n idbindex.name,\n keyPath,\n !!idbindex.unique,\n !!idbindex.multiEntry,\n false,\n keyPath && typeof keyPath !== \"string\",\n false\n );\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\n\nexport function readGlobalSchema(db: Dexie, idbdb: IDBDatabase, tmpTrans: IDBTransaction) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\n\nexport function adjustToExistingIndexNames(db: Dexie, schema: DbSchema, idbtrans: IDBTransaction) {\n // Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n const storeNames = idbtrans.db.objectStoreNames;\n\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n db._hasGetAll = false;\n }\n}\n\nexport function parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n return createIndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n indexNum === 0\n );\n });\n}\n","import { Version as IVersion } from '../../public/types/version';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { extend, keys } from '../../functions/utils';\nimport { Dexie } from '../dexie';\nimport { Transaction } from '../transaction';\nimport { removeTablesApi, setApiOnPlace, parseIndexSyntax } from './schema-helpers';\nimport { exceptions } from '../../errors';\nimport { createTableSchema } from '../../helpers/table-schema';\n\n/** class Version\n * \n * http://dexie.org/docs/Version/Version\n */\nexport class Version implements IVersion {\n db: Dexie;\n _cfg: {\n version: number,\n storesSource: { [tableName: string]: string | null },\n dbschema: DbSchema,\n tables: {},\n contentUpgrade: Function | null\n }\n\n _parseStoresSpec(stores: { [tableName: string]: string | null }, outSchema: DbSchema): any {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\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 indexes.forEach(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 });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n\n stores(stores: { [key: string]: string; }): IVersion {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n const storesSpec: { [key: string]: string; } = {};\n let dbschema = {};\n versions.forEach(version => { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n // Update the latest schema to this version\n db._dbSchema = dbschema;\n // Update APIs\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n\n upgrade(upgradeFunction: (trans: Transaction) => PromiseLike | void): Version {\n this._cfg.contentUpgrade = upgradeFunction;\n return this;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Version } from './version';\n\nexport interface VersionConstructor {\n new(versionNumber: number): Version;\n prototype: Version;\n}\n\n/** Generates a Version constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createVersionConstructor(db: Dexie) {\n return makeClassConstructor(\n Version.prototype,\n\n function Version(this: Version, versionNumber: number) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n\n}\n","import Promise from './promise';\nimport { Dexie } from '../classes/dexie/dexie';\nimport { Table } from '../public/types/table';\nimport { nop } from '../functions/chaining-functions';\nimport { PromiseExtended } from '../public/types/promise-extended';\nimport { DBNAMES_DB } from '../globals/constants';\n\nexport let databaseEnumerator: DatabaseEnumerator;\n\nexport interface DatabaseEnumerator {\n getDatabaseNames (): PromiseExtended;\n add (name: string): undefined | PromiseExtended;\n remove (name: string): undefined | PromiseExtended;\n}\n\nexport function DatabaseEnumerator (indexedDB: IDBFactory & {databases?: ()=>Promise<{name: string}[]>}) : DatabaseEnumerator {\n const hasDatabasesNative = indexedDB && typeof indexedDB.databases === 'function';\n let dbNamesTable: Table<{name: string}, string>;\n\n if (!hasDatabasesNative) {\n const db = new Dexie (DBNAMES_DB, {addons: []});\n db.version(1).stores({dbnames: 'name'});\n dbNamesTable = db.table<{name: string}, string>('dbnames');\n }\n\n return {\n getDatabaseNames () {\n return hasDatabasesNative\n ?\n // Use Promise.resolve() to wrap the native promise into a Dexie promise,\n // to keep PSD zone.\n Promise.resolve(indexedDB.databases()).then(infos => infos\n // Select name prop of infos:\n .map(info => info.name)\n // Filter out DBNAMES_DB as previous Dexie or browser version would not have included it in the result.\n .filter(name => name !== DBNAMES_DB)\n )\n :\n // Use dexie's manually maintained list of database names:\n dbNamesTable.toCollection().primaryKeys();\n },\n\n add (name: string) : PromiseExtended | undefined {\n return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.put({name}).catch(nop);\n },\n\n remove (name: string) : PromiseExtended | undefined {\n return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.delete(name).catch(nop);\n }\n };\n}\n\nexport function initDatabaseEnumerator(indexedDB: IDBFactory) {\n try {\n databaseEnumerator = DatabaseEnumerator(indexedDB);\n } catch (e) {}\n}\n\n","import { newScope } from '../../helpers/promise';\nimport { PSD } from '../../helpers/promise';\n\nexport function vip (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","import { Dexie } from './dexie';\nimport * as Debug from '../../helpers/debug';\nimport { rejection } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { eventRejectHandler, preventDefault } from '../../functions/event-wrappers';\nimport Promise, { wrap } from '../../helpers/promise';\nimport { connections } from '../../globals/constants';\nimport { runUpgraders, readGlobalSchema, adjustToExistingIndexNames } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { databaseEnumerator } from '../../helpers/database-enumerator';\nimport { vip } from './vip';\nimport { promisableChain, nop } from '../../functions/chaining-functions';\nimport { generateMiddlewareStacks } from './generate-middleware-stacks';\nimport { slice } from '../../functions/utils';\n\nexport function dexieOpen (db: Dexie) {\n const state = db._state;\n const {indexedDB} = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection (state.dbOpenError) :\n db);\n Debug.debug && (state.openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n \n // Function pointers to call when the core opening process completes.\n let resolveDbReady = state.dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction: (IDBTransaction | null) = null;\n \n return Promise.race([state.openCanceller, new Promise((resolve, reject) => {\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(\n \"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \"+\n \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\n const dbName = db.name;\n \n const req = state.autoSchema ?\n indexedDB.open(dbName) :\n 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 = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap (e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) { // 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 const 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(() => {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n db.idbdb = req.result;\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n \n req.onsuccess = wrap (() => {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n const idbdb = db.idbdb = req.result;\n\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0) try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema) readGlobalSchema(db, idbdb, tmpTrans);\n else adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n generateMiddlewareStacks(db, tmpTrans);\n } catch (e) {\n // Safari 8 may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n // BUGBUG: It will bail out anyway as of Dexie 3.\n // Should we support Safari 8 anymore? Believe all\n // Dexie users use the shim for that platform anyway?!\n // If removing Safari 8 support, go ahead and remove the safariMultiStoreFix() function\n // as well as absurd upgrade version quirk for Safari.\n }\n \n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n \n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n databaseEnumerator.add(dbName);\n\n resolve();\n\n }, reject);\n })]).then(() => {\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 state.onReadyBeingFired = [];\n return Promise.resolve(vip(db.on.ready.fire)).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(remainders)).then(fireRemainders)\n }\n });\n }).finally(()=>{\n state.onReadyBeingFired = null;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n state.isBeingOpened = false;\n return db;\n }).catch(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 state.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 state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n return rejection (state.dbOpenError);\n }).finally(()=>{\n state.openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n });\n}\n","import { isArray } from '../functions/utils';\n\nexport function awaitIterator (iterator: Iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext: (any)=>any) {\n return (val?) => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n","import { TransactionMode } from '../../public/types/transaction-mode';\nimport { exceptions } from '../../errors';\nimport { flatten, isAsyncFunction } from '../../functions/utils';\nimport { Dexie } from './dexie';\nimport { Transaction } from '../transaction';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise, {\n PSD,\n NativePromise,\n decrementExpectedAwaits,\n rejection,\n incrementExpectedAwaits\n} from '../../helpers/promise';\n\nexport function extractTransactionArgs(mode: TransactionMode, _tableArgs_, scopeFunc) {\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) 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 return [mode, tables, scopeFunc];\n}\n\nexport function enterTransactionScope(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n parentTransaction: Transaction | undefined,\n scopeFunc: ()=>PromiseLike | any\n) {\n return Promise.resolve().then(() => {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n const transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n const zoneProps = {\n trans: trans,\n transless: transless\n };\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 // Support for native async await.\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n // scopeFunc is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else 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 }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(() => returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(() => x);\n }).catch(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","import {\n DBCore,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryRequest,\n DBCoreRangeType,\n DBCoreOpenCursorRequest,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreTable,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getKeyPathAlias } from './dbcore-indexeddb';\nimport { Middleware } from '../public/types/middleware';\n\ninterface VirtualIndex extends DBCoreIndex {\n /** True if this index is virtual, i.e. represents a compound index internally,\n * but makes it act as as having a subset of its keyPaths.\n */\n isVirtual: boolean;\n\n /** Number of keypaths that this index comprises. Can be 0..N.\n * Note: This is the length of the *virtual index*, not the real index.\n */\n keyLength: number;\n\n /** Number of popped keypaths from the real index.\n */\n keyTail: number;\n}\n\n// Move into some util:\nexport function pad (a: any | any[], value: any, count: number) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i=0; i 0;\n const virtualIndex = {\n ...lowLevelIndex,\n isVirtual,\n isPrimaryKey: !isVirtual && lowLevelIndex.isPrimaryKey,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] : // This is a compound [a, b]. Add a virtual normal index a.\n keyPath.slice(0, keyLength - 1); // This is compound [a,b,c]. Add virtual compound [a,b].\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a,b) => a.keyTail - b.keyTail); // Shortest keyTail is the best one (represents real index)\n return virtualIndex;\n }\n \n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n \n function findBestIndex(keyPath: null | string | string[]): VirtualIndex {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n \n function translateRange (range: DBCoreKeyRange, keyTail: number): DBCoreKeyRange {\n return {\n type: range.type === DBCoreRangeType.Equal ?\n DBCoreRangeType.Range :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true, // doesn't matter true or false\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true // doesn't matter true or false\n };\n }\n \n function translateRequest (req: DBCoreQueryRequest): DBCoreQueryRequest;\n function translateRequest (req: DBCoreOpenCursorRequest): DBCoreOpenCursorRequest;\n function translateRequest (req: DBCoreCountRequest): DBCoreCountRequest {\n const index = req.query.index as VirtualIndex;\n return index.isVirtual ? {\n ...req,\n query: {\n index,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n \n const result: DBCoreTable = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n\n count(req) {\n return table.count(translateRequest(req));\n }, \n \n query(req) {\n return table.query(translateRequest(req));\n },\n \n openCursor(req) {\n const {keyTail, isVirtual, keyLength} = (req.query.index as VirtualIndex);\n if (!isVirtual) return table.openCursor(req);\n \n function createVirtualCursor(cursor: DBCoreCursor) : DBCoreCursor {\n function _continue (key?: any) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(pad(cursor.key, req.reverse ? down.MIN_KEY : down.MAX_KEY, keyTail)) :\n cursor.continue()\n }\n const virtualCursor = Object.create(cursor, {\n continue: {value: _continue},\n continuePrimaryKey: {\n value(key: any, primaryKey: any) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n key: {\n get() {\n const key = cursor.key as any[]; // A virtual cursor always operates on compound key\n return keyLength === 1 ?\n key[0] : // Cursor.key should not be an array.\n key.slice(0, keyLength); // Cursor.key should be first part of array.\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n \n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n }\n}\n\nexport const virtualIndexMiddleware : Middleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\n","import {\n DBCore,\n DBCoreTable,\n DBCoreMutateResponse,\n DBCoreDeleteRangeRequest,\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreTransaction,\n DBCoreKeyRange,\n} from \"../public/types/dbcore\";\nimport { nop } from '../functions/chaining-functions';\nimport { getObjectDiff, setByKeyPath } from '../functions/utils';\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys, getExistingValues } from '../dbcore/get-effective-keys';\nimport { Middleware } from '../public/types/middleware';\nimport { Transaction } from '../classes/transaction';\n\nexport const hooksMiddleware: Middleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore: DBCore) => ({\n ...downCore,\n table(tableName: string) {\n const downTable = downCore.table(tableName);\n const {primaryKey} = downTable.schema;\n \n const tableMiddleware: DBCoreTable = {\n ...downTable,\n mutate(req):Promise {\n const dxTrans = PSD.trans as Transaction;\n // Hooks can be transaction-bound. Need to grab them from transaction.table and not\n // db.table!\n const {deleting, creating, updating} = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>deleteRange(req), true);\n }\n // Any of the breaks above happened (no hooks) - do the default:\n return downTable.mutate(req);\n\n\n function addPutOrDelete(req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest): Promise {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys) throw new Error(\"Keys missing\");\n // Clone Request and set keys arg\n req = req.type === 'add' || req.type === 'put' ?\n {...req, keys, wantResults: true} : // Tell lower layer to deliver results. Hooks onsuccess needs it.\n {...req};\n if (req.type !== 'delete') req.values = [...req.values];\n if (req.keys) req.keys = [...req.keys];\n \n return getExistingValues(downTable, req, keys).then (existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n // delete operation\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n } else if (req.type === 'add' || existingValue === undefined) {\n // The add() or put() resulted in a create\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n } else {\n // The put() operation resulted in an update\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({failures, results, numFailures, lastResult}) => {\n for (let i=0; i {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n \n function deleteRange(req: DBCoreDeleteRangeRequest): Promise {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n \n function deleteNextChunk(trans: DBCoreTransaction, range: DBCoreKeyRange, limit: number) {\n // Query what keys in the DB within the given range\n return downTable.query({trans, values: false, query: {index: primaryKey, range}, limit})\n .then(({result}) => {\n // Given a set of keys, bulk delete those using the same procedure as in addPutOrDelete().\n // This will make sure that deleting hook is called.\n return addPutOrDelete({type: 'delete', keys: result, trans}).then(res => {\n if (res.numFailures > 0) return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return {failures: [], numFailures: 0, lastResult: undefined} as DBCoreMutateResponse;\n } else {\n return deleteNextChunk(trans, {...range, lower: result[result.length - 1], lowerOpen: true}, limit);\n }\n });\n })\n }\n }\n };\n //const {lock, lockableMiddleware} = LockableTableMiddleware(tableMiddleware);\n\n return tableMiddleware;\n },\n }) as DBCore\n};\n","// Import types from the public API\nimport { Dexie as IDexie } from \"../../public/types/dexie\";\nimport { DexieOptions, DexieConstructor } from \"../../public/types/dexie-constructor\";\nimport { DbEvents } from \"../../public/types/db-events\";\n//import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from \"../../public/types/table-schema\";\nimport { DbSchema } from '../../public/types/db-schema';\n\n// Internal imports\nimport { Table, TableConstructor, createTableConstructor } from \"../table\";\nimport { Collection, CollectionConstructor, createCollectionConstructor } from '../collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { WhereClauseConstructor, createWhereClauseConstructor } from '../where-clause/where-clause-constructor';\nimport { Transaction } from '../transaction';\nimport { TransactionConstructor, createTransactionConstructor } from '../transaction/transaction-constructor';\nimport { Version } from \"../version/version\";\nimport { VersionConstructor, createVersionConstructor } from '../version/version-constructor';\n\n// Other imports...\nimport { DexieEventSet } from '../../public/types/dexie-event-set';\nimport { DexieExceptionClasses } from '../../public/types/errors';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport Promise, { PSD } from '../../helpers/promise';\nimport { extend, override, keys, hasOwn } from '../../functions/utils';\nimport Events from '../../helpers/Events';\nimport { maxString, connections, READONLY, READWRITE } from '../../globals/constants';\nimport { getMaxKey } from '../../functions/quirks';\nimport { exceptions } from '../../errors';\nimport { lowerVersionFirst } from '../version/schema-helpers';\nimport { dexieOpen } from './dexie-open';\nimport { wrap } from '../../helpers/promise';\nimport { databaseEnumerator } from '../../helpers/database-enumerator';\nimport { eventRejectHandler } from '../../functions/event-wrappers';\nimport { extractTransactionArgs, enterTransactionScope } from './transaction-helpers';\nimport { TransactionMode } from '../../public/types/transaction-mode';\nimport { rejection } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { DBCore } from '../../public/types/dbcore';\nimport { Middleware, DexieStacks } from '../../public/types/middleware';\nimport { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware';\nimport { hooksMiddleware } from '../../hooks/hooks-middleware';\nimport { IndexableType } from '../../public';\n\nexport interface DbReadyState {\n dbOpenError: any;\n isBeingOpened: boolean;\n onReadyBeingFired: undefined | Function[];\n openComplete: boolean;\n dbReadyResolve: () => void;\n dbReadyPromise: Promise;\n cancelOpen: (reason?: Error) => void;\n openCanceller: Promise & { _stackHolder?: Error };\n autoSchema: boolean;\n vcFired?: boolean;\n}\n\nexport class Dexie implements IDexie {\n _options: DexieOptions;\n _state: DbReadyState;\n _versions: Version[];\n _storeNames: string[];\n _deps: DexieDOMDependencies;\n _allTables: { [name: string]: Table; };\n _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike, dbschema: { [tableName: string]: TableSchema; }, parentTransaction?: Transaction) => Transaction;\n _dbSchema: { [tableName: string]: TableSchema; };\n _hasGetAll?: boolean;\n _maxKey: IndexableType;\n _fireOnBlocked: (ev: Event) => void;\n _middlewares: {[StackName in keyof DexieStacks]?: Middleware[]} = {};\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n on: DbEvents;\n\n Table: TableConstructor;\n WhereClause: WhereClauseConstructor;\n Collection: CollectionConstructor;\n Version: VersionConstructor;\n Transaction: TransactionConstructor;\n\n constructor(name: string, options?: DexieOptions) {\n const deps = (Dexie as any as DexieConstructor).dependencies;\n this._options = options = {\n // Default Options\n addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n // Default DOM dependency implementations from static prop.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env.\n ...options\n };\n this._deps = {\n indexedDB: options.indexedDB as IDBFactory,\n IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange\n };\n const {\n addons,\n } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n const state: DbReadyState = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null as Promise,\n cancelOpen: nop,\n openCanceller: null as Promise,\n autoSchema: true\n };\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", { ready: [promisableChain, nop] }) as DbEvents;\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n (Dexie as any as DexieConstructor).vip(() => {\n const state = this._state;\n if (state.openComplete) {\n // Database already open. Call subscriber asap.\n if (!state.dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (state.onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n state.onReadyBeingFired.push(subscriber);\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 const db = this;\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 // Create derived classes bound to this instance of Dexie:\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n\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 this.on(\"versionchange\", 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)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.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 this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n\n this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange);\n\n this._createTransaction = (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parentTransaction?: Transaction) => new this.Transaction(mode, storeNames, dbschema, parentTransaction);\n\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n // Default middlewares:\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n\n // Call each addon:\n addons.forEach(addon => addon(this));\n }\n\n version(versionNumber: number): Version {\n if (isNaN(versionNumber) || versionNumber < 0.1) throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(\n v => v._cfg.version === versionNumber)[0];\n if (versionInstance) return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({}); // Derive earlier schemas by default.\n // Disable autoschema mode, as at least one version is specified.\n this._state.autoSchema = false;\n return versionInstance;\n }\n\n _whenReady(fn: () => Promise): Promise {\n return this._state.openComplete || PSD.letThrough ? fn() : new Promise((resolve, reject) => {\n if (!this._state.isBeingOpened) {\n if (!this._options.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n\n use({stack, create, level, name}: Middleware): this {\n if (name) this.unuse({stack, name}); // Be able to replace existing middleware.\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({stack, create, level: level == null ? 10 : level, name});\n middlewares.sort((a, b) => a.level - b.level);\n // Todo update db.core and db.tables...core ? Or should be expect this to have effect\n // only after next open()?\n return this;\n }\n\n unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this;\n unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this;\n unuse({stack, name, create}: {stack: keyof DexieStacks, name?: string, create?: Function}) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw =>\n create ? mw.create !== create : // Given middleware has a create method. Match that exactly.\n name ? mw.name !== name : // Given middleware spec \n false);\n }\n return this;\n }\n\n open() {\n return dexieOpen(this);\n }\n\n close(): void {\n const idx = connections.indexOf(this),\n state = this._state;\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this.idbdb = null;\n }\n this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\n\n // Reset dbReadyPromise promise:\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n\n delete(): Promise {\n const hasArguments = arguments.length > 0;\n const state = this._state;\n return new Promise((resolve, reject) => {\n const doDelete = () => {\n this.close();\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n databaseEnumerator.remove(this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n }\n\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n });\n }\n\n backendDB() {\n return this.idbdb;\n }\n\n isOpen() {\n return this.idbdb !== null;\n }\n\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n\n get tables () {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n\n transaction(): Promise {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n\n _transaction(mode: TransactionMode, tables: Array, scopeFunc: Function) {\n let parentTransaction = PSD.trans as Transaction | undefined;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n let idbMode: IDBTransactionMode,\n storeNames;\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n storeNames = tables.map(table => {\n var storeName = table instanceof this.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)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\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(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>this._whenReady(enterTransaction)) :\n this._whenReady (enterTransaction));\n }\n\n table(tableName: string): Table;\n table(tableName: string): ITable;\n table(tableName: string): Table {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return this._allTables[tableName];\n }\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, getObjectDiff, asap, _global } from '../../functions/utils';\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { DatabaseEnumerator, databaseEnumerator } from '../../helpers/database-enumerator';\nimport { PSD } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { newScope } from '../../helpers/promise';\nimport { rejection } from '../../helpers/promise';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { dexieStackFrameFilter, minKey, connections, DEXIE_VERSION } from '../../globals/constants';\nimport Events from '../../helpers/Events';\nimport { exceptions } from '../../errors';\nimport { errnames } from '../../errors';\nimport { getMaxKey } from '../../functions/quirks';\nimport { vip } from './vip';\n\n/* (Dexie) is an instance of DexieConstructor, as defined in public/types/dexie-constructor.d.ts\n* (new Dexie()) is an instance of Dexie, as defined in public/types/dexie.d.ts\n* \n* Why we're doing this?\n\n* Because we've choosen to define the public Dexie API using a DexieConstructor interface\n* rather than declaring a class. On that interface, all static props are defined.\n* In practice, class Dexie's constructor implements DexieConstructor and all member props\n* are defined in interface Dexie. We could say, it's a typescript limitation of not being\n* able to define a static interface that forces us to do the cast below.\n*/\nconst Dexie = _Dexie as any as DexieConstructor;\n\n//\n// Set all static methods and properties onto Dexie:\n// \nprops(Dexie, {\n\n // Dexie.BulkError = class BulkError {...};\n // Dexie.XXXError = class XXXError {...};\n ...fullNameExceptions,\n\n //\n // Static delete() method.\n //\n delete(databaseName: string) {\n const db = new Dexie(databaseName);\n return db.delete();\n },\n\n //\n // Static exists() method.\n //\n exists(name: string) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames(cb) {\n return databaseEnumerator ?\n databaseEnumerator.getDatabaseNames().then(cb) :\n Promise.resolve([]);\n },\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n\n ignoreTransaction(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 ?\n 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,\n\n async: function (generatorFn: Function) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n 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')\n 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: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n const promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\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: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive, // Deprecate?\n extend: extend, // Deprecate?\n props: props,\n override: override, // Deprecate?\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\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: new Dexie('',{addons:[]})._maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n //MultiModifyError: exceptions.Modify, // Obsolete!\n errnames: errnames,\n\n // Export other static classes\n //IndexSpec: IndexSpec, Obsolete!\n //TableSchema: TableSchema, Obsolete!\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 try {\n return {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n } catch (e) {\n return {indexedDB: null, IDBKeyRange: null};\n }\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('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\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 // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n Dexie: Dexie\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { Dexie } from './classes/dexie';\nimport { DexieConstructor } from './public/types/dexie-constructor';\nimport { DexiePromise } from './helpers/promise';\nimport { mapError } from './errors';\nimport * as Debug from './helpers/debug';\nimport { dexieStackFrameFilter } from './globals/constants';\nimport { initDatabaseEnumerator } from './helpers/database-enumerator';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\n\n// Init Database Enumerator (for Dexie.getDatabaseNames())\ninitDatabaseEnumerator((Dexie as any as DexieConstructor).dependencies.indexedDB);\n\n// Set rejectionMapper of DexiePromise so that it generally tries to map\n// DOMErrors and DOMExceptions to a DexieError instance with same name but with\n// async stack support and with a prototypal inheritance from DexieError and Error.\n// of Map DOMErrors and DOMExceptions to corresponding Dexie errors.\nDexiePromise.rejectionMapper = mapError;\n\n// Let the async stack filter focus on app code and filter away frames from dexie.min.js:\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport default Dexie;\n"],"names":["asap","props","Promise","keys","Table","Collection","WhereClause","Transaction","Version","Debug.debug","Debug.getErrorWithStack","Dexie","_Dexie","Debug.setDebug"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BO,IAAI,QAAQ,GAAG,WAAW;IAC7B,QAAQ,GAAG,MAAM,CAAC,MAAM,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE;QAC7C,KAAK,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YACjD,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;YACjB,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;SAChF;QACD,OAAO,CAAC,CAAC;MACZ;IACD,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;EAC1C;AAED,AAUC;AAED,AAKC;AAED,AAEC;AAED,AAEC;AAED,AAQC;AAED,AA0BC;AAED,AAEC;AAED,AAUC;AAED,AAeC;AAED,AAIC;AAED,AAAO,SAAS,cAAc,GAAG;IAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IACpF,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,CA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,MAAM,EAAE,EAAE;IAEV,WAAW,EAAE,WAAW;IAGxB,QAAQ,EAAE,QAAQ;IAclB,YAAY,EAAE,CAAC;QACb,IAAI;YACF,OAAO;gBAEL,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,YAAY,IAAI,OAAO,CAAC,eAAe,IAAI,OAAO,CAAC,WAAW;gBACtG,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,iBAAiB;aAC9D,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,EAAC,SAAS,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAC,CAAC;SAC7C;KACF,GAAG;IAGJ,MAAM,EAAE,aAAa,EACrB,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC;SAC9B,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,QAAQ,CAAC,CAAC,CAAC,GAAA,CAAC;SACrB,MAAM,CAAC,UAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAK,OAAA,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAA,CAAC;IAKrD,OAAO,EAAEF,OAAK;IAMd,KAAK,EAAEA,OAAK,IACZ,CAAC;AAEHA,OAAK,CAAC,MAAM,GAAG,SAAS,CAACA,OAAK,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC;;ACzNzD,sBAAsB,CAAE,KAAiC,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AAMlF,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCE,QAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC,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..a2b87a84c --- /dev/null +++ b/dist/dexie.min.js @@ -0,0 +1 @@ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Dexie=t()})(this,function(){"use strict";var m=function(){return(m=Object.assign||function(e){for(var t,n=1,r=arguments.length;n.",mt="String expected.",gt=[],bt="undefined"!=typeof navigator&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),_t=bt,wt=bt,xt="__dbnames",kt="readonly",Et="readwrite";function Ot(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}var Pt={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1},jt=(At.prototype._trans=function(e,r,t){var n=this._tx||Ce.trans,i=this.name;function o(e,t,n){if(!n.schema[i])throw new Z.NotFound("Table "+i+" not part of transaction");return r(n.idbtrans,n)}var u=ze();try{return n&&n.db===this.db?n===Ce.trans?n._promise(e,o,t):tt(function(){return n._promise(e,o,t)},{trans:n,transless:Ce.transless||Ce}):function e(t,n,r,i){if(t._state.openComplete||Ce.letThrough){var o=t._createTransaction(n,r,t._dbSchema);try{o.create()}catch(e){return pt(e)}return o._promise(n,function(e,t){return tt(function(){return Ce.trans=o,i(e,t,o)})}).then(function(e){return o._completion.then(function(){return e})})}if(!t._state.isBeingOpened){if(!t._options.autoOpen)return pt(new Z.DatabaseClosed);t.open().catch(ne)}return t._state.dbReadyPromise.then(function(){return e(t,n,r,i)})}(this.db,e,[this.name],o)}finally{u&&Le()}},At.prototype.get=function(t,e){var n=this;return t&&t.constructor===Object?this.where(t).first(e):this._trans("readonly",function(e){return n.core.get({trans:e,key:t}).then(function(e){return n.hook.reading.fire(e)})}).then(e)},At.prototype.where=function(u){if("string"==typeof u)return new this.db.WhereClause(this,u);if(d(u))return new this.db.WhereClause(this,"["+u.join("+")+"]");var n=_(u);if(1===n.length)return this.where(n[0]).equals(u[n[0]]);var e=this.schema.indexes.concat(this.schema.primKey).filter(function(t){return t.compound&&n.every(function(e){return 0<=t.keyPath.indexOf(e)})&&t.keyPath.every(function(e){return 0<=n.indexOf(e)})})[0];if(e&&this.db._maxKey!==yt)return this.where(e.name).equals(e.keyPath.map(function(e){return u[e]}));!e&&q&&console.warn("The query "+JSON.stringify(u)+" on "+this.name+" would benefit of a compound index ["+n.join("+")+"]");var a=this.schema.idxByName,r=this.db._deps.indexedDB;function s(e,t){try{return 0===r.cmp(e,t)}catch(e){return!1}}var t=n.reduce(function(e,n){var t=e[0],r=e[1],i=a[n],o=u[n];return[t||i,t||!i?Ot(r,i&&i.multi?function(e){var t=w(e,n);return d(t)&&t.some(function(e){return s(o,e)})}:function(e){return s(o,w(e,n))}):r]},[null,null]),i=t[0],o=t[1];return i?this.where(i.name).equals(u[i.keyPath]).filter(o):e?this.filter(o):this.where(n).equals("")},At.prototype.filter=function(e){return this.toCollection().and(e)},At.prototype.count=function(e){return this.toCollection().count(e)},At.prototype.offset=function(e){return this.toCollection().offset(e)},At.prototype.limit=function(e){return this.toCollection().limit(e)},At.prototype.each=function(e){return this.toCollection().each(e)},At.prototype.toArray=function(e){return this.toCollection().toArray(e)},At.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},At.prototype.orderBy=function(e){return new this.db.Collection(new this.db.WhereClause(this,d(e)?"["+e.join("+")+"]":e))},At.prototype.reverse=function(){return this.toCollection().reverse()},At.prototype.mapToClass=function(r){function e(e){if(!e)return e;var t=Object.create(r.prototype);for(var n in e)if(c(e,n))try{t[n]=e[n]}catch(e){}return t}return this.schema.mappedClass=r,this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=e,this.hook("reading",e),r},At.prototype.defineClass=function(){return this.mapToClass(function(e){s(this,e)})},At.prototype.add=function(t,n){var r=this;return this._trans("readwrite",function(e){return r.core.mutate({trans:e,type:"add",keys:null!=n?[n]:null,values:[t]})}).then(function(e){return e.numFailures?De.reject(e.failures[0]):e.lastResult}).then(function(e){if(!r.core.schema.primaryKey.outbound)try{x(t,r.core.schema.primaryKey.keyPath,e)}catch(e){}return e})},At.prototype.update=function(t,n){if("object"!=typeof n||d(n))throw new Z.InvalidArgument("Modifications must be an object.");if("object"!=typeof t||d(t))return this.where(":id").equals(t).modify(n);_(n).forEach(function(e){x(t,e,n[e])});var e=w(t,this.schema.primKey.keyPath);return void 0===e?pt(new Z.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(e).modify(n)},At.prototype.put=function(t,n){var r=this;return this._trans("readwrite",function(e){return r.core.mutate({trans:e,type:"put",values:[t],keys:null!=n?[n]:null})}).then(function(e){return e.numFailures?De.reject(e.failures[0]):e.lastResult}).then(function(e){if(!r.core.schema.primaryKey.outbound)try{x(t,r.core.schema.primaryKey.keyPath,e)}catch(e){}return e})},At.prototype.delete=function(t){var n=this;return this._trans("readwrite",function(e){return n.core.mutate({trans:e,type:"delete",keys:[t]})}).then(function(e){return e.numFailures?De.reject(e.failures[0]):void 0})},At.prototype.clear=function(){var t=this;return this._trans("readwrite",function(e){return t.core.mutate({trans:e,type:"deleteRange",range:Pt})}).then(function(e){return e.numFailures?De.reject(e.failures[0]):void 0})},At.prototype.bulkGet=function(t){var n=this;return this._trans("readonly",function(e){return n.core.getMany({keys:t,trans:e}).then(function(e){return e.map(function(e){return n.hook.reading.fire(e)})})})},At.prototype.bulkAdd=function(t,e,n){var u=this,r=Array.isArray(e)?e:void 0,a=(n=n||(r?void 0:e))?n.allKeys:void 0;return this._trans("readwrite",function(e){if(!u.core.schema.primaryKey.outbound&&r)throw new Z.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(r&&r.length!==t.length)throw new Z.InvalidArgument("Arguments objects and keys must have the same length");var o=t.length;return u.core.mutate({trans:e,type:"add",keys:r,values:t,wantResults:a}).then(function(e){var t=e.numFailures,n=e.results,r=e.lastResult,i=e.failures;if(0===t)return a?n:r;throw new X(u.name+".bulkAdd(): "+t+" of "+o+" operations failed",Object.keys(i).map(function(e){return i[e]}))})})},At.prototype.bulkPut=function(t,e,n){var u=this,r=Array.isArray(e)?e:void 0,a=(n=n||(r?void 0:e))?n.allKeys:void 0;return this._trans("readwrite",function(e){if(!u.core.schema.primaryKey.outbound&&r)throw new Z.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(r&&r.length!==t.length)throw new Z.InvalidArgument("Arguments objects and keys must have the same length");var o=t.length;return u.core.mutate({trans:e,type:"put",keys:r,values:t,wantResults:a}).then(function(e){var t=e.numFailures,n=e.results,r=e.lastResult,i=e.failures;if(0===t)return a?n:r;throw new X(u.name+".bulkPut(): "+t+" of "+o+" operations failed",Object.keys(i).map(function(e){return i[e]}))})})},At.prototype.bulkDelete=function(t){var i=this,o=t.length;return this._trans("readwrite",function(e){return i.core.mutate({trans:e,type:"delete",keys:t})}).then(function(e){var t=e.numFailures,n=e.lastResult,r=e.failures;if(0===t)return n;throw new X(i.name+".bulkDelete(): "+t+" of "+o+" operations failed",r)})},At);function At(){}function Kt(i){var u={},t=function(e,t){if(t){for(var n=arguments.length,r=new Array(n-1);--n;)r[n-1]=arguments[n];return u[e].subscribe.apply(null,r),i}if("string"==typeof e)return u[e]};t.addEventType=a;for(var e=1,n=arguments.length;es+c&&f(s+g)})})};return f(0).then(function(){if(0=l}).forEach(function(s){t.push(function(){var t=p,e=s._cfg.dbschema;wn(c,t,h),wn(c,e,h),p=c._dbSchema=e;var n=function(e,t){var n,r={del:[],add:[],change:[]};for(n in e)t[n]||r.del.push(n);for(n in t){var i=e[n],o=t[n];if(i){var u={name:n,def:o,recreate:!1,del:[],add:[],change:[]};if(i.primKey.src===o.primKey.src||bt){var a=i.idxByName,s=o.idxByName,c=void 0;for(c in a)s[c]||u.del.push(c);for(c in s){var l=a[c],f=s[c];l?l.src!==f.src&&u.change.push(f):u.add.push(f)}(0l){pn(c,h),d=!0;var i=k(e);n.del.forEach(function(e){i[e]=t[e]}),yn(c,[c.Transaction.prototype]),dn(c,[c.Transaction.prototype],_(i),i),f.schema=i;var o,u=F(r);u&&nt();var a=De.follow(function(){var e;(o=r(f))&&u&&(e=rt.bind(null,null),o.then(e,e))});return o&&"function"==typeof o.then?De.resolve(o):a.then(function(){return o})}}),t.push(function(e){d&&_t||function(e,t){for(var n=0;nMath.pow(2,62)?0:e.oldVersion,a.idbdb=u.result,mn(a,n/10,l,i))},i),u.onsuccess=He(function(){l=null;var e=a.idbdb=u.result,t=p(e.objectStoreNames);if(0= 0) { + rv = any; + } + 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; +} +var toString = {}.toString; +function toStringTag(o) { + return toString.call(o).slice(8, -1); +} +var getValueOf = function (val, type) { + return type === "Array" ? '' + val.map(function (v) { return getValueOf(v, toStringTag(v)); }) : + type === "ArrayBuffer" ? '' + new Uint8Array(val) : + type === "Date" ? val.getTime() : + ArrayBuffer.isView(val) ? '' + new Uint8Array(val.buffer) : + val; +}; +function getObjectDiff(a, b, rv, prfx) { + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(function (prop) { + if (!hasOwn(b, prop)) + rv[prfx + prop] = undefined; + else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) { + var apTypeName = toStringTag(ap); + var bpTypeName = toStringTag(bp); + if (apTypeName === bpTypeName) { + if (intrinsicTypeNameSet[apTypeName]) { + if (getValueOf(ap, apTypeName) !== getValueOf(bp, bpTypeName)) { + rv[prfx + prop] = b[prop]; + } + } + else { + getObjectDiff(ap, bp, rv, prfx + prop + "."); + } + } + else { + rv[prfx + prop] = b[prop]; + } + } + else if (ap !== bp) + rv[prfx + prop] = b[prop]; + } + }); + keys(b).forEach(function (prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; + } + }); + return rv; +} +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 = {}; +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 isAsyncFunction = typeof Symbol !== 'undefined' + ? function (fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; } + : function () { return false; }; + +var debug = typeof location !== 'undefined' && + /^(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() { + if (NEEDS_THROW_FOR_STACK) + try { + throw new Error(); + } + 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(''); +} + +var dexieErrorNames = [ + 'Modify', + 'Bulk', + 'OpenFailed', + 'VersionChange', + 'Schema', + 'Upgrade', + 'InvalidTable', + 'MissingAPI', + 'NoSuchDatabase', + 'InvalidArgument', + 'SubTransaction', + 'Unsupported', + 'Internal', + 'DatabaseClosed', + 'PrematureCommit', + 'ForeignAwait' +]; +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" +}; +function DexieError(name, msg) { + 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: " + Object.keys(failures) + .map(function (key) { return failures[key].toString(); }) + .filter(function (v, i, s) { return s.indexOf(v) === i; }) + .join('\n'); +} +function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; + this.message = getMultiErrorMessage(msg, failures); +} +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); +var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); +var BaseException = DexieError; +var exceptions = errorList.reduce(function (obj, name) { + 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 + (!inner ? '' : '\n ' + inner); + 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; +}, {}); +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) { + 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 nop() { } +function mirror(val) { return val; } +function pureFunctionChain(f1, f2) { + 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) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) + arguments[0] = res; + var onsuccess = this.onsuccess, + onerror = 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, + onerror = 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); + var onsuccess = this.onsuccess, + onerror = 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); + }; +} + +var INTERNAL = {}; +var LONG_STACKS_CLIP_LIMIT = 100; +var MAX_LONG_STACKS = 20; +var ZONE_ECHO_LIMIT = 100; +var _a = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, globalP.__proto__, globalP]; + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + nativeP.__proto__, + globalP + ]; + })(); +var resolvedNativePromise = _a[0]; +var nativePromiseProto = _a[1]; +var resolvedGlobalPromise = _a[2]; +var nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; +var patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +var schedulePhysicalTick = resolvedGlobalPromise ? + function () { resolvedGlobalPromise.then(physicalTick); } + : + _global.setImmediate ? + setImmediate.bind(null, physicalTick) : + _global.MutationObserver ? + function () { + var hiddenDiv = document.createElement("div"); + (new MutationObserver(function () { + physicalTick(); + hiddenDiv = null; + })).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); + } : + function () { setTimeout(physicalTick, 0); }; +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; +var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + pgp: false, + env: {}, + finalize: function () { + this.unhandleds.forEach(function (uh) { + try { + globalError(uh[0], uh[1]); + } + catch (e) { } + }); + } +}; +var PSD = globalPSD; +var microtickQueue = []; +var numScheduledCalls = 0; +var tickFinalizers = []; +function DexiePromise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this.onuncatched = nop; + this._lib = false; + var psd = (this._PSD = PSD); + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) + throw new TypeError('Not a function'); + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); + return; + } + this._state = null; + this._value = null; + ++psd.ref; + executePromiseTask(this, fn); +} +var thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + if (possibleAwait) + decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; + return then; + }, + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : + { + get: function () { + return value; + }, + set: thenProp.set + }); + } +}; +props(DexiePromise.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + var type = arguments[0], handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + return err instanceof type ? handler(err) : PromiseReject(err); + }) + : this.then(null, function (err) { + return 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); + }); + }, + 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; + return stack; + } + finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? + new DexiePromise(function (resolve, reject) { + var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms); + _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } +}); +if (typeof Symbol !== 'undefined' && Symbol.toStringTag) + setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); +globalPSD.env = snapShot(); +function Listener(onFulfilled, onRejected, resolve, reject, zone) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = zone; +} +props(DexiePromise, { + all: function () { + var values = getArrayOf.apply(null, arguments) + .map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + values.map(function (value) { return DexiePromise.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; } + }, + follow: function (fn, zoneProps) { + return new DexiePromise(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; + psd.onunhandled = reject; + psd.finalize = callBoth(function () { + var _this = this; + run_at_end_of_this_or_next_physical_tick(function () { + _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } +}); +if (NativePromise) { + if (NativePromise.allSettled) + setProp(DexiePromise, "allSettled", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve) { + if (possiblePromises.length === 0) + resolve([]); + var remaining = possiblePromises.length; + var results = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) + .then(function () { return --remaining || resolve(results); }); }); + }); + }); + if (NativePromise.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + var remaining = possiblePromises.length; + var failures = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + }); }); + }); + }); +} +function executePromiseTask(promise, fn) { + 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 DexiePromise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } + else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); + } + 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; + } + }); + }); + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); +} +function propagateAllListeners(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 (numScheduledCalls === 0) { + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } +} +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap$1(callListener, [cb, promise, listener]); +} +function callListener(cb, promise, listener) { + try { + currentFulfiller = promise; + var ret, value = promise._value; + if (promise._state) { + ret = cb(value); + } + else { + if (rejectingErrors.length) + rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); + } + listener.resolve(ret); + } + catch (e) { + listener.reject(e); + } + finally { + currentFulfiller = null; + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + --listener.psd.ref || listener.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; + 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) { + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } +} +function physicalTick() { + beginMicroTickScope() && endMicroTickScope(); +} +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} +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); + 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) { + if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) + unhandledErrors.push(promise); +} +function markErrorAsHandled(promise) { + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + unhandledErrors.splice(i, 1); + return; + } +} +function PromiseReject(reason) { + return new DexiePromise(INTERNAL, false, reason); +} +function wrap(fn, errorCatcher) { + var psd = PSD; + return function () { + var wasRootExec = beginMicroTickScope(), outerScope = PSD; + try { + switchToZone(psd, true); + return fn.apply(this, arguments); + } + catch (e) { + errorCatcher && errorCatcher(e); + } + finally { + switchToZone(outerScope, false); + if (wasRootExec) + endMicroTickScope(); + } + }; +} +var task = { awaits: 0, echoes: 0, id: 0 }; +var taskCounter = 0; +var zoneStack = []; +var zoneEchoes = 0; +var totalEchoes = 0; +var zone_id_counter = 0; +function newScope(fn, props$$1, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: DexiePromise, + PromiseProp: { value: DexiePromise, configurable: true, writable: true }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) + } : {}; + if (props$$1) + extend(psd, props$$1); + ++parent.ref; + psd.finalize = function () { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD(psd, fn, a1, a2); + if (psd.ref === 0) + psd.finalize(); + return rv; +} +function incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; +} +function decrementExpectedAwaits(sourceTaskId) { + if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) + return; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; +} +if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + incrementExpectedAwaits = decrementExpectedAwaits = nop; +} +function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { + incrementExpectedAwaits(); + return possiblePromise.then(function (x) { + decrementExpectedAwaits(); + return x; + }, function (e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; +} +function zoneEnterEcho(targetZone) { + ++totalEchoes; + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.id = 0; + } + zoneStack.push(PSD); + switchToZone(targetZone, true); +} +function zoneLeaveEcho() { + var zone = zoneStack[zoneStack.length - 1]; + zoneStack.pop(); + switchToZone(zone, false); +} +function switchToZone(targetZone, bEnteringZone) { + var currentZone = PSD; + if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { + enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + var GlobalPromise_1 = globalPSD.env.Promise; + var targetEnv = targetZone.env; + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise_1.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + GlobalPromise_1.all = targetEnv.all; + GlobalPromise_1.race = targetEnv.race; + GlobalPromise_1.resolve = targetEnv.resolve; + GlobalPromise_1.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise_1.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise_1.any = targetEnv.any; + } + } +} +function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + resolve: GlobalPromise.resolve, + reject: GlobalPromise.reject, + nthen: nativePromiseProto.then, + gthen: GlobalPromise.prototype.then + } : {}; +} +function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + switchToZone(psd, true); + return fn(a1, a2, a3); + } + finally { + switchToZone(outerScope, false); + } +} +function enqueueNativeMicroTask(job) { + nativePromiseThen.call(resolvedNativePromise, job); +} +function nativeAwaitCompatibleWrap(fn, zone, possibleAwait) { + return typeof fn !== 'function' ? fn : function () { + var outerZone = PSD; + if (possibleAwait) + incrementExpectedAwaits(); + switchToZone(zone, true); + try { + return fn.apply(this, arguments); + } + finally { + switchToZone(outerZone, false); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone, false), nativeAwaitCompatibleWrap(onRejected, zone, false)); + }; +} +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) + try { + _global.onunhandledrejection(event); + } + catch (_) { } + } + if (debug && event && !event.defaultPrevented) { + console.warn("Unhandled rejection: " + (err.stack || err)); + } + } + catch (e) { } +} +var rejection = DexiePromise.reject; + +function tempTransaction(db, mode, storeNames, fn) { + if (!db._state.openComplete && (!PSD.letThrough)) { + if (!db._state.isBeingOpened) { + if (!db._options.autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); + } + return db._state.dbReadyPromise.then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + else { + var trans = db._createTransaction(mode, storeNames, db._dbSchema); + try { + trans.create(); + } + catch (ex) { + return rejection(ex); + } + return trans._promise(mode, function (resolve, reject) { + return newScope(function () { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(function (result) { + return trans._completion.then(function () { return result; }); + }); + } +} + +var DEXIE_VERSION = '3.0.2'; +var maxString = String.fromCharCode(65535); +var minKey = -Infinity; +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); }; +var DBNAMES_DB = '__dbnames'; +var READONLY = 'readonly'; +var READWRITE = 'readwrite'; + +function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; +} + +var AnyRange = { + type: 3 , + lower: -Infinity, + lowerOpen: false, + upper: [[]], + upperOpen: false +}; + +var Table = (function () { + function Table() { + } + Table.prototype._trans = function (mode, fn, writeLocked) { + var trans = this._tx || PSD.trans; + var tableName = this.name; + function checkTableInTransaction(resolve, reject, trans) { + if (!trans.schema[tableName]) + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + return fn(trans.idbtrans, trans); + } + var wasRootExec = beginMicroTickScope(); + try { + return trans && trans.db === this.db ? + trans === PSD.trans ? + trans._promise(mode, checkTableInTransaction, writeLocked) : + newScope(function () { return trans._promise(mode, checkTableInTransaction, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(this.db, mode, [this.name], checkTableInTransaction); + } + finally { + if (wasRootExec) + endMicroTickScope(); + } + }; + Table.prototype.get = function (keyOrCrit, cb) { + var _this = this; + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + return this._trans('readonly', function (trans) { + return _this.core.get({ trans: trans, key: keyOrCrit }) + .then(function (res) { return _this.hook.reading.fire(res); }); + }).then(cb); + }; + Table.prototype.where = function (indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new this.db.WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new this.db.WhereClause(this, "[" + indexOrCrit.join('+') + "]"); + var keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { + return ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; }) && + ix.keyPath.every(function (keyPath) { return keyPaths.indexOf(keyPath) >= 0; }); + })[0]; + if (compoundIndex && this.db._maxKey !== maxString) + return this + .where(compoundIndex.name) + .equals(compoundIndex.keyPath.map(function (kp) { return indexOrCrit[kp]; })); + if (!compoundIndex && debug) + console.warn("The query " + JSON.stringify(indexOrCrit) + " on " + this.name + " would benefit of a " + + ("compound index [" + keyPaths.join('+') + "]")); + var idxByName = this.schema.idxByName; + var idb = this.db._deps.indexedDB; + function equals(a, b) { + try { + return idb.cmp(a, b) === 0; + } + catch (e) { + return false; + } + } + var _a = keyPaths.reduce(function (_a, keyPath) { + var prevIndex = _a[0], prevFilterFn = _a[1]; + var index = idxByName[keyPath]; + var value = indexOrCrit[keyPath]; + return [ + prevIndex || index, + prevIndex || !index ? + combine(prevFilterFn, index && index.multi ? + function (x) { + var prop = getByKeyPath(x, keyPath); + return isArray(prop) && prop.some(function (item) { return equals(value, item); }); + } : function (x) { return equals(value, getByKeyPath(x, keyPath)); }) + : prevFilterFn + ]; + }, [null, null]), idx = _a[0], filterFunction = _a[1]; + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(filterFunction) : + compoundIndex ? + this.filter(filterFunction) : + this.where(keyPaths).equals(''); + }; + Table.prototype.filter = function (filterFunction) { + return this.toCollection().and(filterFunction); + }; + Table.prototype.count = function (thenShortcut) { + return this.toCollection().count(thenShortcut); + }; + Table.prototype.offset = function (offset) { + return this.toCollection().offset(offset); + }; + Table.prototype.limit = function (numRows) { + return this.toCollection().limit(numRows); + }; + Table.prototype.each = function (callback) { + return this.toCollection().each(callback); + }; + Table.prototype.toArray = function (thenShortcut) { + return this.toCollection().toArray(thenShortcut); + }; + Table.prototype.toCollection = function () { + return new this.db.Collection(new this.db.WhereClause(this)); + }; + Table.prototype.orderBy = function (index) { + return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? + "[" + index.join('+') + "]" : + index)); + }; + Table.prototype.reverse = function () { + return this.toCollection().reverse(); + }; + Table.prototype.mapToClass = function (constructor) { + this.schema.mappedClass = constructor; + var readHook = function (obj) { + if (!obj) + return obj; + var res = Object.create(constructor.prototype); + 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; + }; + Table.prototype.defineClass = function () { + function Class(content) { + extend(this, content); + } + + return this.mapToClass(Class); + }; + Table.prototype.add = function (obj, key) { + var _this = this; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [obj] }); + }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (!_this.core.schema.primaryKey.outbound) { + try { + setByKeyPath(obj, _this.core.schema.primaryKey.keyPath, lastResult); + } + catch (_) { } + + } + return lastResult; + }); + }; + Table.prototype.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)) { + 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")); + return this.where(":id").equals(key).modify(modifications); + } + else { + return this.where(":id").equals(keyOrObject).modify(modifications); + } + }; + Table.prototype.put = function (obj, key) { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [obj], keys: key != null ? [key] : null }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (!_this.core.schema.primaryKey.outbound) { + try { + setByKeyPath(obj, _this.core.schema.primaryKey.keyPath, lastResult); + } + catch (_) { } + + } + return lastResult; + }); + }; + Table.prototype.delete = function (key) { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.clear = function () { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.bulkGet = function (keys$$1) { + var _this = this; + return this._trans('readonly', function (trans) { + return _this.core.getMany({ + keys: keys$$1, + trans: trans + }).then(function (result) { return result.map(function (res) { return _this.hook.reading.fire(res); }); }); + }); + }; + Table.prototype.bulkAdd = function (objects, keysOrOptions, options) { + var _this = this; + var keys$$1 = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys$$1 ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var outbound = _this.core.schema.primaryKey.outbound; + if (!outbound && 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"); + var numObjects = objects.length; + return _this.core.mutate({ trans: trans, type: 'add', keys: keys$$1, values: objects, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(_this.name + ".bulkAdd(): " + numFailures + " of " + numObjects + " operations failed", Object.keys(failures).map(function (pos) { return failures[pos]; })); + }); + }); + }; + Table.prototype.bulkPut = function (objects, keysOrOptions, options) { + var _this = this; + var keys$$1 = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys$$1 ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var outbound = _this.core.schema.primaryKey.outbound; + if (!outbound && 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"); + var numObjects = objects.length; + return _this.core.mutate({ trans: trans, type: 'put', keys: keys$$1, values: objects, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(_this.name + ".bulkPut(): " + numFailures + " of " + numObjects + " operations failed", Object.keys(failures).map(function (pos) { return failures[pos]; })); + }); + }); + }; + Table.prototype.bulkDelete = function (keys$$1) { + var _this = this; + var numKeys = keys$$1.length; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'delete', keys: keys$$1 }); + }).then(function (_a) { + var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures; + if (numFailures === 0) + return lastResult; + throw new BulkError(_this.name + ".bulkDelete(): " + numFailures + " of " + numKeys + " operations failed", failures); + }); + }; + return Table; +}()); + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + 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 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) { + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } + else if (args === 'asap') { + var context = add(eventName, mirror, function fire() { + var i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + context.subscribers.forEach(function (fn) { + asap(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +function makeClassConstructor(prototype, constructor) { + derive(constructor).from({ prototype: prototype }); + return constructor; +} + +function createTableConstructor(db) { + return makeClassConstructor(Table.prototype, function Table$$1(name, tableSchema, trans) { + this.db = db; + this._tx = trans; + this.name = name; + this.schema = tableSchema; + this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + }); +} + +function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); +} +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); +} +function getIndexOrStore(ctx, coreSchema) { + if (ctx.isPrimKey) + return coreSchema.primaryKey; + var index = coreSchema.getIndexByKeyPath(ctx.index); + if (!index) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); + return index; +} +function openCursor(ctx, coreTable, trans) { + var index = getIndexOrStore(ctx, coreTable.schema); + return coreTable.openCursor({ + trans: trans, + values: !ctx.keysOnly, + reverse: ctx.dir === 'prev', + unique: !!ctx.unique, + query: { + index: index, + range: ctx.range + } + }); +} +function iter(ctx, fn, coreTrans, coreTable) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); + } + else { + var set_1 = {}; + var union = function (item, cursor, advance) { + if (!filter || filter(cursor, advance, function (result) { return cursor.stop(result); }, function (err) { return cursor.fail(err); })) { + var primaryKey = cursor.primaryKey; + var key = '' + primaryKey; + if (key === '[object ArrayBuffer]') + key = '' + new Uint8Array(primaryKey); + if (!hasOwn(set_1, key)) { + set_1[key] = true; + fn(item, cursor, advance); + } + } + }; + return Promise.all([ + ctx.or._iterate(union, coreTrans), + iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) + ]); + } +} +function iterate(cursorPromise, filter, fn, valueMapper) { + var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; + var wrappedFn = wrap(mappedFn); + return cursorPromise.then(function (cursor) { + if (cursor) { + return cursor.start(function () { + var c = function () { return cursor.continue(); }; + if (!filter || filter(cursor, function (advancer) { return c = advancer; }, function (val) { cursor.stop(val); c = nop; }, function (e) { cursor.fail(e); c = nop; })) + wrappedFn(cursor.value, cursor, function (advancer) { return c = advancer; }); + c(); + }); + } + }); +} + +var Collection = (function () { + function Collection() { + } + Collection.prototype._read = function (fn, cb) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readonly', fn).then(cb); + }; + Collection.prototype._write = function (fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readwrite', fn, "locked"); + }; + Collection.prototype._addAlgorithm = function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }; + Collection.prototype._iterate = function (fn, coreTrans) { + return iter(this._ctx, fn, coreTrans, this._ctx.table.core); + }; + Collection.prototype.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; + }; + Collection.prototype.raw = function () { + this._ctx.valueMapper = null; + return this; + }; + Collection.prototype.each = function (fn) { + var ctx = this._ctx; + return this._read(function (trans) { return iter(ctx, fn, trans, ctx.table.core); }); + }; + Collection.prototype.count = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + var coreTable = ctx.table.core; + if (isPlainKeyRange(ctx, true)) { + return coreTable.count({ + trans: trans, + query: { + index: getIndexOrStore(ctx, coreTable.schema), + range: ctx.range + } + }).then(function (count) { return Math.min(count, ctx.limit); }); + } + else { + var count = 0; + return iter(ctx, function () { ++count; return false; }, trans, coreTable) + .then(function () { return count; }); + } + }).then(cb); + }; + Collection.prototype.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); + }; + Collection.prototype.toArray = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + var valueMapper_1 = ctx.valueMapper; + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + limit: ctx.limit, + values: true, + query: { + index: index, + range: ctx.range + } + }).then(function (_a) { + var result = _a.result; + return valueMapper_1 ? result.map(valueMapper_1) : result; + }); + } + else { + var a_1 = []; + return iter(ctx, function (item) { return a_1.push(item); }, trans, ctx.table.core).then(function () { return a_1; }); + } + }, cb); + }; + Collection.prototype.offset = function (offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; + 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; + }; + Collection.prototype.limit = function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); + addReplayFilter(this._ctx, function () { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); + return rowsLeft >= 0; + }; + }, true); + return this; + }; + Collection.prototype.until = function (filterFunction, bIncludeStopEntry) { + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + }; + Collection.prototype.first = function (cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.last = function (cb) { + return this.reverse().first(cb); + }; + Collection.prototype.filter = function (filterFunction) { + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + addMatchFilter(this._ctx, filterFunction); + return this; + }; + Collection.prototype.and = function (filter) { + return this.filter(filter); + }; + Collection.prototype.or = function (indexName) { + return new this.db.WhereClause(this._ctx.table, indexName, this); + }; + Collection.prototype.reverse = function () { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + }; + Collection.prototype.desc = function () { + return this.reverse(); + }; + Collection.prototype.eachKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + }; + Collection.prototype.eachUniqueKey = function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }; + Collection.prototype.eachPrimaryKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + }; + Collection.prototype.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); + }; + Collection.prototype.primaryKeys = function (cb) { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + return this._read(function (trans) { + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + values: false, + limit: ctx.limit, + query: { + index: index, + range: ctx.range + } + }); + }).then(function (_a) { + var result = _a.result; + return result; + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }; + Collection.prototype.uniqueKeys = function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }; + Collection.prototype.firstKey = function (cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.lastKey = function (cb) { + return this.reverse().firstKey(cb); + }; + Collection.prototype.distinct = function () { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + }; + Collection.prototype.modify = function (changes) { + var _this = this; + var ctx = this._ctx; + return this._write(function (trans) { + var modifyer; + if (typeof changes === 'function') { + modifyer = changes; + } + else { + 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); + anythingModified = true; + } + } + return anythingModified; + }; + } + var coreTable = ctx.table.core; + var _a = coreTable.schema.primaryKey, outbound = _a.outbound, extractKey = _a.extractKey; + var limit = 'testmode' in Dexie ? 1 : 2000; + var cmp = _this.db.core.cmp; + var totalFailures = []; + var successCount = 0; + var failedKeys = []; + var applyMutateResult = function (expectedCount, res) { + var failures = res.failures, numFailures = res.numFailures; + successCount += expectedCount - numFailures; + for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) { + var pos = _a[_i]; + totalFailures.push(failures[pos]); + } + }; + return _this.clone().primaryKeys().then(function (keys$$1) { + var nextChunk = function (offset) { + var count = Math.min(limit, keys$$1.length - offset); + return coreTable.getMany({ trans: trans, keys: keys$$1.slice(offset, offset + count) }).then(function (values) { + var addValues = []; + var putValues = []; + var putKeys = outbound ? [] : null; + var deleteKeys = []; + for (var i = 0; i < count; ++i) { + var origValue = values[i]; + var ctx_1 = { + value: deepClone(origValue), + primKey: keys$$1[offset + i] + }; + if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { + if (ctx_1.value == null) { + deleteKeys.push(keys$$1[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { + deleteKeys.push(keys$$1[offset + i]); + addValues.push(ctx_1.value); + } + else { + putValues.push(ctx_1.value); + if (outbound) + putKeys.push(keys$$1[offset + i]); + } + } + } + return Promise.resolve(addValues.length > 0 && + coreTable.mutate({ trans: trans, type: 'add', values: addValues }) + .then(function (res) { + for (var pos in res.failures) { + deleteKeys.splice(parseInt(pos), 1); + } + applyMutateResult(addValues.length, res); + })).then(function (res) { return putValues.length > 0 && + coreTable.mutate({ trans: trans, type: 'put', keys: putKeys, values: putValues }) + .then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return deleteKeys.length > 0 && + coreTable.mutate({ trans: trans, type: 'delete', keys: deleteKeys }) + .then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { + return keys$$1.length > offset + count && nextChunk(offset + limit); + }); + }); + }; + return nextChunk(0).then(function () { + if (totalFailures.length > 0) + throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); + return keys$$1.length; + }); + }); + }); + }; + Collection.prototype.delete = function () { + var ctx = this._ctx, range = ctx.range; + if (isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 )) + { + return this._write(function (trans) { + var primaryKey = ctx.table.core.schema.primaryKey; + var coreRange = range; + return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) { + return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange }) + .then(function (_a) { + var failures = _a.failures, lastResult = _a.lastResult, results = _a.results, numFailures = _a.numFailures; + if (numFailures) + throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures); + return count - numFailures; + }); + }); + }); + } + return this.modify(function (value, ctx) { return ctx.value = null; }); + }; + return Collection; +}()); + +function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection$$1(whereClause, keyRangeGenerator) { + this.db = db; + var keyRange = AnyRange, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + var whereCtx = whereClause._ctx; + var table = whereCtx.table; + var readingHook = table.hook.reading.fire; + 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, + isMatch: null, + offset: 0, + limit: Infinity, + error: error, + or: whereCtx.or, + valueMapper: readingHook !== mirror ? readingHook : null + }; + }); +} + +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 fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new collectionOrWhereClause.Collection(collectionOrWhereClause) : + collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; +} +function emptyCollection(whereClause) { + return new whereClause.Collection(whereClause, function () { return rangeEqual(""); }).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.Collection(whereClause, function () { return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); + c._ondirectionchange = function (direction) { + 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; +} +function createRange(lower, upper, lowerOpen, upperOpen) { + return { + type: 2 , + lower: lower, + upper: upper, + lowerOpen: lowerOpen, + upperOpen: upperOpen + }; +} +function rangeEqual(value) { + return { + type: 1 , + lower: value, + upper: value + }; +} + +var WhereClause = (function () { + function WhereClause() { + } + Object.defineProperty(WhereClause.prototype, "Collection", { + get: function () { + return this._ctx.table.db.Collection; + }, + enumerable: true, + configurable: true + }); + WhereClause.prototype.between = function (lower, upper, includeLower, includeUpper) { + includeLower = includeLower !== false; + includeUpper = includeUpper === true; + try { + if ((this._cmp(lower, upper) > 0) || + (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); + return new this.Collection(this, function () { return createRange(lower, upper, !includeLower, !includeUpper); }); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }; + WhereClause.prototype.equals = function (value) { + return new this.Collection(this, function () { return rangeEqual(value); }); + }; + WhereClause.prototype.above = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, true); }); + }; + WhereClause.prototype.aboveOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, false); }); + }; + WhereClause.prototype.below = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value, false, true); }); + }; + WhereClause.prototype.belowOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value); }); + }; + WhereClause.prototype.startsWith = function (str) { + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }; + WhereClause.prototype.startsWithIgnoreCase = function (str) { + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); + }; + WhereClause.prototype.equalsIgnoreCase = function (str) { + return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); + }; + WhereClause.prototype.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, ""); + }; + WhereClause.prototype.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); + }; + WhereClause.prototype.anyOf = function () { + var _this = this; + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = this._cmp; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + var c = new this.Collection(this, function () { return createRange(set[0], set[set.length - 1]); }); + c._ondirectionchange = function (direction) { + compare = (direction === "next" ? + _this._ascending : + _this._descending); + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + ++i; + if (i === set.length) { + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + return true; + } + else { + advance(function () { cursor.continue(set[i]); }); + return false; + } + }); + return c; + }; + WhereClause.prototype.notEqual = function (value) { + return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.noneOf = function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new this.Collection(this); + try { + set.sort(this._ascending); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var ranges = set.reduce(function (res, val) { return res ? + res.concat([[res[res.length - 1][1], val]]) : + [[minKey, val]]; }, null); + ranges.push([set[set.length - 1], this.db._maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.inAnyRange = function (ranges, options) { + var _this = this; + var cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; + 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; + var includeUppers = options && options.includeUppers === true; + function addRange(ranges, newRange) { + var i = 0, l = ranges.length; + for (; 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]); } + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var rangePos = 0; + var keyIsBeyondCurrentEntry = includeUppers ? + function (key) { return ascending(key, set[rangePos][1]) > 0; } : + function (key) { return ascending(key, set[rangePos][1]) >= 0; }; + var keyIsBeforeCurrentEntry = includeLowers ? + function (key) { return descending(key, set[rangePos][0]) > 0; } : + function (key) { return descending(key, set[rangePos][0]) >= 0; }; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + var checkKey = keyIsBeyondCurrentEntry; + var c = new this.Collection(this, function () { return createRange(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)) { + ++rangePos; + if (rangePos === set.length) { + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + return true; + } + else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { + return false; + } + else { + advance(function () { + if (sortDirection === ascending) + cursor.continue(set[rangePos][0]); + else + cursor.continue(set[rangePos][1]); + }); + return false; + } + }); + return c; + }; + WhereClause.prototype.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]; })); + }; + return WhereClause; +}()); + +function createWhereClauseConstructor(db) { + return makeClassConstructor(WhereClause.prototype, function WhereClause$$1(table, index, orCollection) { + this.db = db; + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + var indexedDB = db._deps.indexedDB; + if (!indexedDB) + throw new exceptions.MissingAPI("indexedDB API missing"); + this._cmp = this._ascending = indexedDB.cmp.bind(indexedDB); + this._descending = function (a, b) { return indexedDB.cmp(b, a); }; + this._max = function (a, b) { return indexedDB.cmp(a, b) > 0 ? a : b; }; + this._min = function (a, b) { return indexedDB.cmp(a, b) < 0 ? a : b; }; + this._IDBKeyRange = db._deps.IDBKeyRange; + }); +} + +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} + +function getMaxKey(IdbKeyRange) { + try { + IdbKeyRange.only([[]]); + return [[]]; + } + catch (e) { + return maxString; + } +} + +function eventRejectHandler(reject) { + return wrap(function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }); +} + + + +function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); +} + +var Transaction = (function () { + function Transaction() { + } + Transaction.prototype._lock = function () { + assert(!PSD.global); + ++this._reculock; + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + }; + Transaction.prototype._unlock = function () { + assert(!PSD.global); + if (--this._reculock === 0) { + if (!PSD.global) + PSD.lockOwnerFor = null; + while (this._blockedFuncs.length > 0 && !this._locked()) { + var fnAndPSD = this._blockedFuncs.shift(); + try { + usePSD(fnAndPSD[1], fnAndPSD[0]); + } + catch (e) { } + } + } + return this; + }; + Transaction.prototype._locked = function () { + return this._reculock && PSD.lockOwnerFor !== this; + }; + Transaction.prototype.create = function (idbtrans) { + var _this = this; + if (!this.mode) + return this; + var idbdb = this.db.idbdb; + var dbOpenError = this.db._state.dbOpenError; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + 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); + _this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(function (ev) { + preventDefault(ev); + _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); + _this.active = false; + _this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(function () { + _this.active = false; + _this._resolve(); + }); + return this; + }; + Transaction.prototype._promise = function (mode, fn, bWriteLock) { + var _this = this; + if (mode === 'readwrite' && this.mode !== 'readwrite') + return rejection(new exceptions.ReadOnly("Transaction is readonly")); + if (!this.active) + return rejection(new exceptions.TransactionInactive()); + if (this._locked()) { + return new DexiePromise(function (resolve, reject) { + _this._blockedFuncs.push([function () { + _this._promise(mode, fn, bWriteLock).then(resolve, reject); + }, PSD]); + }); + } + else if (bWriteLock) { + return newScope(function () { + var p = new DexiePromise(function (resolve, reject) { + _this._lock(); + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p.finally(function () { return _this._unlock(); }); + p._lib = true; + return p; + }); + } + else { + var p = new DexiePromise(function (resolve, reject) { + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + }; + Transaction.prototype._root = function () { + return this.parent ? this.parent._root() : this; + }; + Transaction.prototype.waitFor = function (promiseLike) { + var root = this._root(); + var promise = DexiePromise.resolve(promiseLike); + if (root._waitingFor) { + root._waitingFor = root._waitingFor.then(function () { return promise; }); + } + else { + root._waitingFor = promise; + root._waitingQueue = []; + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; + while (root._waitingQueue.length) + (root._waitingQueue.shift())(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + }()); + } + var currentWaitPromise = root._waitingFor; + return new DexiePromise(function (resolve, reject) { + promise.then(function (res) { return root._waitingQueue.push(wrap(resolve.bind(null, res))); }, function (err) { return root._waitingQueue.push(wrap(reject.bind(null, err))); }).finally(function () { + if (root._waitingFor === currentWaitPromise) { + root._waitingFor = null; + } + }); + }); + }; + Transaction.prototype.abort = function () { + this.active && this._reject(new exceptions.Abort()); + this.active = false; + }; + Transaction.prototype.table = function (tableName) { + var memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); + if (hasOwn(memoizedTables, tableName)) + return memoizedTables[tableName]; + var tableSchema = this.schema[tableName]; + if (!tableSchema) { + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + } + var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); + transactionBoundTable.core = this.db.core.table(tableName); + memoizedTables[tableName] = transactionBoundTable; + return transactionBoundTable; + }; + return Transaction; +}()); + +function createTransactionConstructor(db) { + return makeClassConstructor(Transaction.prototype, function Transaction$$1(mode, storeNames, dbschema, parent) { + var _this = this; + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.idbtrans = null; + this.on = Events(this, "complete", "error", "abort"); + this.parent = parent || null; + this.active = true; + this._reculock = 0; + this._blockedFuncs = []; + this._resolve = null; + this._reject = null; + this._waitingFor = null; + this._waitingQueue = null; + this._spinCount = 0; + this._completion = new DexiePromise(function (resolve, reject) { + _this._resolve = resolve; + _this._reject = reject; + }); + this._completion.then(function () { + _this.active = false; + _this.on.complete.fire(); + }, function (e) { + var wasActive = _this.active; + _this.active = false; + _this.on.error.fire(e); + _this.parent ? + _this.parent._reject(e) : + wasActive && _this.idbtrans && _this.idbtrans.abort(); + return rejection(e); + }); + }); +} + +function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) { + return { + name: name, + keyPath: keyPath, + unique: unique, + multi: multi, + auto: auto, + compound: compound, + src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath) + }; +} +function nameFromKeyPath(keyPath) { + return typeof keyPath === 'string' ? + keyPath : + keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; +} + +function createTableSchema(name, primKey, indexes) { + return { + name: name, + primKey: primKey, + indexes: indexes, + mappedClass: null, + idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }) + }; +} + +function getKeyExtractor(keyPath) { + if (keyPath == null) { + return function () { return undefined; }; + } + else if (typeof keyPath === 'string') { + return getSinglePathKeyExtractor(keyPath); + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } +} +function getSinglePathKeyExtractor(keyPath) { + var split = keyPath.split('.'); + if (split.length === 1) { + return function (obj) { return obj[keyPath]; }; + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } +} + +function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); +} +function getExistingValues(table, req, effectiveKeys) { + return req.type === 'add' ? Promise.resolve(new Array(req.values.length)) : + table.getMany({ trans: req.trans, keys: effectiveKeys }); +} + +function arrayify(arrayLike) { + return [].slice.call(arrayLike); +} + +var _id_counter = 0; +function getKeyPathAlias(keyPath) { + return keyPath == null ? + ":id" : + typeof keyPath === 'string' ? + keyPath : + "[" + keyPath.join('+') + "]"; +} +function createDBCore(db, indexedDB, IdbKeyRange, tmpTrans) { + var cmp = indexedDB.cmp.bind(indexedDB); + function extractSchema(db, trans) { + var tables = arrayify(db.objectStoreNames); + return { + schema: { + name: db.name, + tables: tables.map(function (table) { return trans.objectStore(table); }).map(function (store) { + var keyPath = store.keyPath, autoIncrement = store.autoIncrement; + var compound = isArray(keyPath); + var outbound = keyPath == null; + var indexByKeyPath = {}; + var result = { + name: store.name, + primaryKey: { + name: null, + isPrimaryKey: true, + outbound: outbound, + compound: compound, + keyPath: keyPath, + autoIncrement: autoIncrement, + unique: true, + extractKey: getKeyExtractor(keyPath) + }, + indexes: arrayify(store.indexNames).map(function (indexName) { return store.index(indexName); }) + .map(function (index) { + var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath = index.keyPath; + var compound = isArray(keyPath); + var result = { + name: name, + compound: compound, + keyPath: keyPath, + unique: unique, + multiEntry: multiEntry, + extractKey: getKeyExtractor(keyPath) + }; + indexByKeyPath[getKeyPathAlias(keyPath)] = result; + return result; + }), + getIndexByKeyPath: function (keyPath) { return indexByKeyPath[getKeyPathAlias(keyPath)]; } + }; + indexByKeyPath[":id"] = result.primaryKey; + if (keyPath != null) { + indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; + } + return result; + }) + }, + hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) && + !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) + }; + } + function makeIDBKeyRange(range) { + if (range.type === 3 ) + return null; + if (range.type === 4 ) + throw new Error("Cannot convert never type to IDBKeyRange"); + var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; + var idbRange = lower === undefined ? + upper === undefined ? + null : + IdbKeyRange.upperBound(upper, !!upperOpen) : + upper === undefined ? + IdbKeyRange.lowerBound(lower, !!lowerOpen) : + IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); + return idbRange; + } + function createDbCoreTable(tableSchema) { + var tableName = tableSchema.name; + function mutate(_a) { + var trans = _a.trans, type = _a.type, keys$$1 = _a.keys, values = _a.values, range = _a.range, wantResults = _a.wantResults; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var outbound = store.keyPath == null; + var isAddOrPut = type === "put" || type === "add"; + if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') + throw new Error("Invalid operation type: " + type); + var length = (keys$$1 || values || { length: 1 }).length; + if (keys$$1 && values && keys$$1.length !== values.length) { + throw new Error("Given keys array must have same length as given values array."); + } + if (length === 0) + return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined }); + var results = wantResults && __spreadArrays((keys$$1 ? + keys$$1 : + getEffectiveKeys(tableSchema.primaryKey, { type: type, keys: keys$$1, values: values }))); + var req; + var failures = []; + var numFailures = 0; + var errorHandler = function (event) { + ++numFailures; + preventDefault(event); + if (results) + results[event.target._reqno] = undefined; + failures[event.target._reqno] = event.target.error; + }; + var setResult = function (_a) { + var target = _a.target; + results[target._reqno] = target.result; + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures: numFailures, failures: failures, results: results, lastResult: undefined }); + if (range.type === 3 ) + req = store.clear(); + else + req = store.delete(makeIDBKeyRange(range)); + } + else { + var _a = isAddOrPut ? + outbound ? + [values, keys$$1] : + [values, null] : + [keys$$1, null], args1 = _a[0], args2 = _a[1]; + if (isAddOrPut) { + for (var i = 0; i < length; ++i) { + req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i])); + req._reqno = i; + if (results && results[i] === undefined) { + req.onsuccess = setResult; + } + req.onerror = errorHandler; + } + } + else { + for (var i = 0; i < length; ++i) { + req = store[type](args1[i]); + req._reqno = i; + req.onerror = errorHandler; + } + } + } + var done = function (event) { + var lastResult = event.target.result; + if (results) + results[length - 1] = lastResult; + resolve({ + numFailures: numFailures, + failures: failures, + results: results, + lastResult: lastResult + }); + }; + req.onerror = function (event) { + errorHandler(event); + done(event); + }; + req.onsuccess = done; + }); + } + function openCursor(_a) { + var trans = _a.trans, values = _a.values, query = _a.query, reverse = _a.reverse, unique = _a.unique; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? + store : + store.index(index.name); + var direction = reverse ? + unique ? + "prevunique" : + "prev" : + unique ? + "nextunique" : + "next"; + var req = values || !('openKeyCursor' in source) ? + source.openCursor(makeIDBKeyRange(range), direction) : + source.openKeyCursor(makeIDBKeyRange(range), direction); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function (ev) { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + cursor.___id = ++_id_counter; + cursor.done = false; + var _cursorContinue = cursor.continue.bind(cursor); + var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; + if (_cursorContinuePrimaryKey) + _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); + var _cursorAdvance = cursor.advance.bind(cursor); + var doThrowCursorIsNotStarted = function () { throw new Error("Cursor not started"); }; + var doThrowCursorIsStopped = function () { throw new Error("Cursor not stopped"); }; + cursor.trans = trans; + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; + cursor.fail = wrap(reject); + cursor.next = function () { + var _this = this; + var gotOne = 1; + return this.start(function () { return gotOne-- ? _this.continue() : _this.stop(); }).then(function () { return _this; }); + }; + cursor.start = function (callback) { + var iterationPromise = new Promise(function (resolveIteration, rejectIteration) { + resolveIteration = wrap(resolveIteration); + req.onerror = eventRejectHandler(rejectIteration); + cursor.fail = rejectIteration; + cursor.stop = function (value) { + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; + resolveIteration(value); + }; + }); + var guardedCallback = function () { + if (req.result) { + try { + callback(); + } + catch (err) { + cursor.fail(err); + } + } + else { + cursor.done = true; + cursor.start = function () { throw new Error("Cursor behind last entry"); }; + cursor.stop(); + } + }; + req.onsuccess = wrap(function (ev) { + req.onsuccess = guardedCallback; + guardedCallback(); + }); + cursor.continue = _cursorContinue; + cursor.continuePrimaryKey = _cursorContinuePrimaryKey; + cursor.advance = _cursorAdvance; + guardedCallback(); + return iterationPromise; + }; + resolve(cursor); + }, reject); + }); + } + function query(hasGetAll) { + return function (request) { + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var trans = request.trans, values = request.values, limit = request.limit, query = request.query; + var nonInfinitLimit = limit === Infinity ? undefined : limit; + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + if (limit === 0) + return resolve({ result: [] }); + if (hasGetAll) { + var req = values ? + source.getAll(idbKeyRange, nonInfinitLimit) : + source.getAllKeys(idbKeyRange, nonInfinitLimit); + req.onsuccess = function (event) { return resolve({ result: event.target.result }); }; + req.onerror = eventRejectHandler(reject); + } + else { + var count_1 = 0; + var req_1 = values || !('openKeyCursor' in source) ? + source.openCursor(idbKeyRange) : + source.openKeyCursor(idbKeyRange); + var result_1 = []; + req_1.onsuccess = function (event) { + var cursor = req_1.result; + if (!cursor) + return resolve({ result: result_1 }); + result_1.push(values ? cursor.value : cursor.primaryKey); + if (++count_1 === limit) + return resolve({ result: result_1 }); + cursor.continue(); + }; + req_1.onerror = eventRejectHandler(reject); + } + }); + }; + } + return { + name: tableName, + schema: tableSchema, + mutate: mutate, + getMany: function (_a) { + var trans = _a.trans, keys$$1 = _a.keys; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var length = keys$$1.length; + var result = new Array(length); + var keyCount = 0; + var callbackCount = 0; + var valueCount = 0; + var req; + var successHandler = function (event) { + var req = event.target; + if ((result[req._pos] = req.result) != null) + ++valueCount; + if (++callbackCount === keyCount) + resolve(result); + }; + var errorHandler = eventRejectHandler(reject); + for (var i = 0; i < length; ++i) { + var key = keys$$1[i]; + if (key != null) { + req = store.get(keys$$1[i]); + req._pos = i; + req.onsuccess = successHandler; + req.onerror = errorHandler; + ++keyCount; + } + } + if (keyCount === 0) + resolve(result); + }); + }, + get: function (_a) { + var trans = _a.trans, key = _a.key; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var req = store.get(key); + req.onsuccess = function (event) { return resolve(event.target.result); }; + req.onerror = eventRejectHandler(reject); + }); + }, + query: query(hasGetAll), + openCursor: openCursor, + count: function (_a) { + var query = _a.query, trans = _a.trans; + var index = query.index, range = query.range; + return new Promise(function (resolve, reject) { + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); + req.onsuccess = wrap(function (ev) { return resolve(ev.target.result); }); + req.onerror = eventRejectHandler(reject); + }); + } + }; + } + var _a = extractSchema(db, tmpTrans), schema = _a.schema, hasGetAll = _a.hasGetAll; + var tables = schema.tables.map(function (tableSchema) { return createDbCoreTable(tableSchema); }); + var tableMap = {}; + tables.forEach(function (table) { return tableMap[table.name] = table; }); + return { + stack: "dbcore", + transaction: db.transaction.bind(db), + table: function (name) { + var result = tableMap[name]; + if (!result) + throw new Error("Table '" + name + "' not found"); + return tableMap[name]; + }, + cmp: cmp, + MIN_KEY: -Infinity, + MAX_KEY: getMaxKey(IdbKeyRange), + schema: schema + }; +} + +function createMiddlewareStack(stackImpl, middlewares) { + return middlewares.reduce(function (down, _a) { + var create = _a.create; + return (__assign(__assign({}, down), create(down))); + }, stackImpl); +} +function createMiddlewareStacks(middlewares, idbdb, _a, tmpTrans) { + var IDBKeyRange = _a.IDBKeyRange, indexedDB = _a.indexedDB; + var dbcore = createMiddlewareStack(createDBCore(idbdb, indexedDB, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore: dbcore + }; +} +function generateMiddlewareStacks(db, tmpTrans) { + var idbdb = tmpTrans.db; + var stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); + db.core = stacks.dbcore; + db.tables.forEach(function (table) { + var tableName = table.name; + if (db.core.schema.tables.some(function (tbl) { return tbl.name === tableName; })) { + table.core = db.core.table(tableName); + if (db[tableName] instanceof db.Table) { + db[tableName].core = table.core; + } + } + }); +} + +function setApiOnPlace(db, objs, tableNames, dbschema) { + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + if (!(tableName in obj)) { + if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { + setProp(obj, tableName, { + get: function () { return this.table(tableName); }, + set: function (value) { + defineProperty(this, tableName, { value: value, writable: true, configurable: true, enumerable: true }); + } + }); + } + else { + obj[tableName] = new db.Table(tableName, schema); + } + } + }); + }); +} +function removeTablesApi(db, objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof db.Table) + delete obj[key]; + } + }); +} +function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; +} +function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) { + var globalSchema = db._dbSchema; + var trans = db._createTransaction('readwrite', db._storeNames, globalSchema); + trans.create(idbUpgradeTrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + var transless = PSD.transless || PSD; + newScope(function () { + PSD.trans = trans; + PSD.transless = transless; + if (oldVersion === 0) { + keys(globalSchema).forEach(function (tableName) { + createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + generateMiddlewareStacks(db, idbUpgradeTrans); + DexiePromise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); + } + else + updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction); + }); +} +function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) { + var queue = []; + var versions = db._versions; + var globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); + 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(db, oldSchema, idbUpgradeTrans); + adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + diff.add.forEach(function (tuple) { + createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + var store_1 = idbUpgradeTrans.objectStore(change.name); + change.add.forEach(function (idx) { return addIndex(store_1, idx); }); + change.change.forEach(function (idx) { + store_1.deleteIndex(idx.name); + addIndex(store_1, idx); + }); + change.del.forEach(function (idxName) { return store_1.deleteIndex(idxName); }); + } + }); + var contentUpgrade = version._cfg.contentUpgrade; + if (contentUpgrade && version._cfg.version > oldVersion) { + generateMiddlewareStacks(db, idbUpgradeTrans); + anyContentUpgraderHasRun = true; + var upgradeSchema_1 = shallowClone(newSchema); + diff.del.forEach(function (table) { + upgradeSchema_1[table] = oldSchema[table]; + }); + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); + trans.schema = upgradeSchema_1; + var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); + if (contentUpgradeIsAsync_1) { + incrementExpectedAwaits(); + } + var returnValue_1; + var promiseFollowed = DexiePromise.follow(function () { + returnValue_1 = contentUpgrade(trans); + if (returnValue_1) { + if (contentUpgradeIsAsync_1) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue_1.then(decrementor, decrementor); + } + } + }); + return (returnValue_1 && typeof returnValue_1.then === 'function' ? + DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function () { return returnValue_1; })); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + var newSchema = version._cfg.dbschema; + deleteRemovedTables(newSchema, idbtrans); + } + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema); + trans.schema = db._dbSchema; + }); + }); + function runQueue() { + return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + DexiePromise.resolve(); + } + return runQueue().then(function () { + createMissingTables(globalSchema, idbUpgradeTrans); + }); +} +function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], + add: [], + change: [] + }; + var table; + for (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 && + !isIEOrEdge + ) { + change.recreate = true; + diff.change.push(change); + } + else { + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + var idxName = void 0; + for (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) { return 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 buildGlobalSchema(db, idbdb, tmpTrans) { + var globalSchema = {}; + var dbStoreNames = slice(idbdb.objectStoreNames, 0); + dbStoreNames.forEach(function (storeName) { + var store = tmpTrans.objectStore(storeName); + var keyPath = store.keyPath; + var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); + indexes.push(index); + } + globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); + }); + return globalSchema; +} +function readGlobalSchema(db, idbdb, tmpTrans) { + db.verno = idbdb.version / 10; + var globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); + db._storeNames = slice(idbdb.objectStoreNames, 0); + setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); +} +function adjustToExistingIndexNames(db, schema, idbtrans) { + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + db._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; + delete schema[storeName].idxByName[dexieName]; + schema[storeName].idxByName[indexName] = indexSpec; + } + } + } + } + if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + db._hasGetAll = false; + } +} +function parseIndexSyntax(primKeyAndIndexes) { + return primKeyAndIndexes.split(',').map(function (index, indexNum) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); + }); +} + +var Version = (function () { + function Version() { + } + Version.prototype._parseStoresSpec = function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multi-valued"); + 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"); + }); + outSchema[tableName] = createTableSchema(tableName, primKey, indexes); + } + }); + }; + Version.prototype.stores = function (stores) { + var db = this.db; + this._cfg.storesSource = this._cfg.storesSource ? + extend(this._cfg.storesSource, stores) : + stores; + var versions = db._versions; + var storesSpec = {}; + var dbschema = {}; + versions.forEach(function (version) { + extend(storesSpec, version._cfg.storesSource); + dbschema = (version._cfg.dbschema = {}); + version._parseStoresSpec(storesSpec, dbschema); + }); + db._dbSchema = dbschema; + removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]); + setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + db._storeNames = keys(dbschema); + return this; + }; + Version.prototype.upgrade = function (upgradeFunction) { + this._cfg.contentUpgrade = upgradeFunction; + return this; + }; + return Version; +}()); + +function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version$$1(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); +} + +var databaseEnumerator; +function DatabaseEnumerator(indexedDB) { + var hasDatabasesNative = indexedDB && typeof indexedDB.databases === 'function'; + var dbNamesTable; + if (!hasDatabasesNative) { + var db = new Dexie(DBNAMES_DB, { addons: [] }); + db.version(1).stores({ dbnames: 'name' }); + dbNamesTable = db.table('dbnames'); + } + return { + getDatabaseNames: function () { + return hasDatabasesNative + ? + DexiePromise.resolve(indexedDB.databases()).then(function (infos) { return infos + .map(function (info) { return info.name; }) + .filter(function (name) { return name !== DBNAMES_DB; }); }) + : + dbNamesTable.toCollection().primaryKeys(); + }, + add: function (name) { + return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.put({ name: name }).catch(nop); + }, + remove: function (name) { + return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.delete(name).catch(nop); + } + }; +} +function initDatabaseEnumerator(indexedDB) { + try { + databaseEnumerator = DatabaseEnumerator(indexedDB); + } + catch (e) { } +} + +function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); +} + +function dexieOpen(db) { + var state = db._state; + var indexedDB = db._deps.indexedDB; + if (state.isBeingOpened || db.idbdb) + return state.dbReadyPromise.then(function () { return state.dbOpenError ? + rejection(state.dbOpenError) : + db; }); + debug && (state.openCanceller._stackHolder = getErrorWithStack()); + state.isBeingOpened = true; + state.dbOpenError = null; + state.openComplete = false; + var resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null; + return DexiePromise.race([state.openCanceller, new DexiePromise(function (resolve, reject) { + 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 dbName = db.name; + var req = state.autoSchema ? + indexedDB.open(dbName) : + indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI("IndexedDB API not available"); + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(db._fireOnBlocked); + req.onupgradeneeded = wrap(function (e) { + upgradeTransaction = req.transaction; + if (state.autoSchema && !db._options.allowEmptyDB) { + req.onerror = preventDefault; + upgradeTransaction.abort(); + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); + delreq.onsuccess = delreq.onerror = wrap(function () { + reject(new exceptions.NoSuchDatabase("Database " + dbName + " doesnt exist")); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; + db.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(function () { + upgradeTransaction = null; + var idbdb = db.idbdb = req.result; + var objectStoreNames = slice(idbdb.objectStoreNames); + if (objectStoreNames.length > 0) + try { + var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); + if (state.autoSchema) + readGlobalSchema(db, idbdb, tmpTrans); + else + adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(function (ev) { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + databaseEnumerator.add(dbName); + resolve(); + }, reject); + })]).then(function () { + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(db.on.ready.fire)).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + var remainders = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(remainders)).then(fireRemainders); + } + }); + }).finally(function () { + state.onReadyBeingFired = null; + }).then(function () { + state.isBeingOpened = false; + return db; + }).catch(function (err) { + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (e) { } + state.isBeingOpened = false; + db.close(); + state.dbOpenError = err; + return rejection(state.dbOpenError); + }).finally(function () { + state.openComplete = true; + resolveDbReady(); + }); +} + +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)(); +} + +function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + scopeFunc = args.pop(); + var tables = flatten(args); + return [mode, tables, scopeFunc]; +} +function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) { + return DexiePromise.resolve().then(function () { + var transless = PSD.transless || PSD; + var trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); + var zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + trans.idbtrans = parentTransaction.idbtrans; + } + else { + trans.create(); + } + var scopeFuncIsAsync = isAsyncFunction(scopeFunc); + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var returnValue; + var promiseFollowed = DexiePromise.follow(function () { + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (scopeFuncIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === 'function' ? + DexiePromise.resolve(returnValue).then(function (x) { return trans.active ? + x + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) + : promiseFollowed.then(function () { return returnValue; })).then(function (x) { + if (parentTransaction) + trans._resolve(); + return trans._completion.then(function () { return x; }); + }).catch(function (e) { + trans._reject(e); + return rejection(e); + }); + }); +} + +function pad(a, value, count) { + var result = isArray(a) ? a.slice() : [a]; + for (var i = 0; i < count; ++i) + result.push(value); + return result; +} +function createVirtualIndexMiddleware(down) { + return __assign(__assign({}, down), { table: function (tableName) { + var table = down.table(tableName); + var schema = table.schema; + var indexLookup = {}; + var allVirtualIndexes = []; + function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { + var keyPathAlias = getKeyPathAlias(keyPath); + var indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); + var keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; + var isVirtual = keyTail > 0; + var virtualIndex = __assign(__assign({}, lowLevelIndex), { isVirtual: isVirtual, isPrimaryKey: !isVirtual && lowLevelIndex.isPrimaryKey, keyTail: keyTail, + keyLength: keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); + indexList.push(virtualIndex); + if (!virtualIndex.isPrimaryKey) { + allVirtualIndexes.push(virtualIndex); + } + if (keyLength > 1) { + var virtualKeyPath = keyLength === 2 ? + keyPath[0] : + keyPath.slice(0, keyLength - 1); + addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); + } + indexList.sort(function (a, b) { return a.keyTail - b.keyTail; }); + return virtualIndex; + } + var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); + indexLookup[":id"] = [primaryKey]; + for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) { + var index = _a[_i]; + addVirtualIndexes(index.keyPath, 0, index); + } + function findBestIndex(keyPath) { + var result = indexLookup[getKeyPathAlias(keyPath)]; + return result && result[0]; + } + function translateRange(range, keyTail) { + return { + type: range.type === 1 ? + 2 : + range.type, + lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), + lowerOpen: true, + upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), + upperOpen: true + }; + } + function translateRequest(req) { + var index = req.query.index; + return index.isVirtual ? __assign(__assign({}, req), { query: { + index: index, + range: translateRange(req.query.range, index.keyTail) + } }) : req; + } + var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey: primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function (req) { + return table.count(translateRequest(req)); + }, + query: function (req) { + return table.query(translateRequest(req)); + }, + openCursor: function (req) { + var _a = req.query.index, keyTail = _a.keyTail, isVirtual = _a.isVirtual, keyLength = _a.keyLength; + if (!isVirtual) + return table.openCursor(req); + function createVirtualCursor(cursor) { + function _continue(key) { + key != null ? + cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : + req.unique ? + cursor.continue(pad(cursor.key, req.reverse ? down.MIN_KEY : down.MAX_KEY, keyTail)) : + cursor.continue(); + } + var virtualCursor = Object.create(cursor, { + continue: { value: _continue }, + continuePrimaryKey: { + value: function (key, primaryKey) { + cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); + } + }, + key: { + get: function () { + var key = cursor.key; + return keyLength === 1 ? + key[0] : + key.slice(0, keyLength); + } + }, + value: { + get: function () { + return cursor.value; + } + } + }); + return virtualCursor; + } + return table.openCursor(translateRequest(req)) + .then(function (cursor) { return cursor && createVirtualCursor(cursor); }); + } }); + return result; + } }); +} +var virtualIndexMiddleware = { + stack: "dbcore", + name: "VirtualIndexMiddleware", + level: 1, + create: createVirtualIndexMiddleware +}; + +var hooksMiddleware = { + stack: "dbcore", + name: "HooksMiddleware", + level: 2, + create: function (downCore) { return (__assign(__assign({}, downCore), { table: function (tableName) { + var downTable = downCore.table(tableName); + var primaryKey = downTable.schema.primaryKey; + var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) { + var dxTrans = PSD.trans; + var _a = dxTrans.table(tableName).hook, deleting = _a.deleting, creating = _a.creating, updating = _a.updating; + switch (req.type) { + case 'add': + if (creating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'put': + if (creating.fire === nop && updating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'delete': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'deleteRange': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return deleteRange(req); }, true); + } + return downTable.mutate(req); + function addPutOrDelete(req) { + var dxTrans = PSD.trans; + var keys$$1 = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys$$1) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys$$1, wantResults: true }) : + __assign({}, req); + if (req.type !== 'delete') + req.values = __spreadArrays(req.values); + if (req.keys) + req.keys = __spreadArrays(req.keys); + return getExistingValues(downTable, req, keys$$1).then(function (existingValues) { + var contexts = keys$$1.map(function (key, i) { + var existingValue = existingValues[i]; + var ctx = { onerror: null, onsuccess: null }; + if (req.type === 'delete') { + deleting.fire.call(ctx, key, existingValue, dxTrans); + } + else if (req.type === 'add' || existingValue === undefined) { + var generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans); + if (key == null && generatedPrimaryKey != null) { + key = generatedPrimaryKey; + req.keys[i] = key; + if (!primaryKey.outbound) { + setByKeyPath(req.values[i], primaryKey.keyPath, key); + } + } + } + else { + var objectDiff = getObjectDiff(existingValue, req.values[i]); + var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); + if (additionalChanges_1) { + var requestedValue_1 = req.values[i]; + Object.keys(additionalChanges_1).forEach(function (keyPath) { + setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); + }); + } + } + return ctx; + }); + return downTable.mutate(req).then(function (_a) { + var failures = _a.failures, results = _a.results, numFailures = _a.numFailures, lastResult = _a.lastResult; + for (var i = 0; i < keys$$1.length; ++i) { + var primKey = results ? results[i] : keys$$1[i]; + var ctx = contexts[i]; + if (primKey == null) { + ctx.onerror && ctx.onerror(failures[i]); + } + else { + ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ? + req.values[i] : + primKey + ); + } + } + return { failures: failures, results: results, numFailures: numFailures, lastResult: lastResult }; + }).catch(function (error) { + contexts.forEach(function (ctx) { return ctx.onerror && ctx.onerror(error); }); + return Promise.reject(error); + }); + }); + } + function deleteRange(req) { + return deleteNextChunk(req.trans, req.range, 10000); + } + function deleteNextChunk(trans, range, limit) { + return downTable.query({ trans: trans, values: false, query: { index: primaryKey, range: range }, limit: limit }) + .then(function (_a) { + var result = _a.result; + return addPutOrDelete({ type: 'delete', keys: result, trans: trans }).then(function (res) { + if (res.numFailures > 0) + return Promise.reject(res.failures[0]); + if (result.length < limit) { + return { failures: [], numFailures: 0, lastResult: undefined }; + } + else { + return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); + } + }); + }); + } + } }); + return tableMiddleware; + } })); } +}; + +var Dexie = (function () { + function Dexie(name, options) { + var _this = this; + this._middlewares = {}; + this.verno = 0; + var deps = Dexie.dependencies; + this._options = options = __assign({ + addons: Dexie.addons, autoOpen: true, + indexedDB: deps.indexedDB, IDBKeyRange: deps.IDBKeyRange }, options); + this._deps = { + indexedDB: options.indexedDB, + IDBKeyRange: options.IDBKeyRange + }; + var addons = options.addons; + this._dbSchema = {}; + this._versions = []; + this._storeNames = []; + this._allTables = {}; + this.idbdb = null; + var state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true + }; + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + this._state = state; + this.name = name; + this.on = Events(this, "populate", "blocked", "versionchange", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { + return function (subscriber, bSticky) { + Dexie.vip(function () { + var state = _this._state; + if (state.openComplete) { + if (!state.dbOpenError) + DexiePromise.resolve().then(subscriber); + if (bSticky) + subscribe(subscriber); + } + else if (state.onReadyBeingFired) { + state.onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } + else { + subscribe(subscriber); + var db_1 = _this; + if (!bSticky) + subscribe(function unsubscribe() { + db_1.on.ready.unsubscribe(subscriber); + db_1.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.Collection = createCollectionConstructor(this); + this.Table = createTableConstructor(this); + this.Transaction = createTransactionConstructor(this); + this.Version = createVersionConstructor(this); + this.WhereClause = createWhereClauseConstructor(this); + this.on("versionchange", function (ev) { + if (ev.newVersion > 0) + console.warn("Another connection wants to upgrade database '" + _this.name + "'. Closing db now to resume the upgrade."); + else + console.warn("Another connection wants to delete database '" + _this.name + "'. Closing db now to resume the delete request."); + _this.close(); + }); + this.on("blocked", function (ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn("Dexie.delete('" + _this.name + "') was blocked"); + else + console.warn("Upgrade '" + _this.name + "' blocked by other connection holding version " + ev.oldVersion / 10); + }); + this._maxKey = getMaxKey(options.IDBKeyRange); + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new _this.Transaction(mode, storeNames, dbschema, parentTransaction); }; + this._fireOnBlocked = function (ev) { + _this.on("blocked").fire(ev); + connections + .filter(function (c) { return c.name === _this.name && c !== _this && !c._state.vcFired; }) + .map(function (c) { return c.on("versionchange").fire(ev); }); + }; + this.use(virtualIndexMiddleware); + this.use(hooksMiddleware); + addons.forEach(function (addon) { return addon(_this); }); + } + Dexie.prototype.version = function (versionNumber) { + if (isNaN(versionNumber) || versionNumber < 0.1) + throw new exceptions.Type("Given version is not a positive number"); + versionNumber = Math.round(versionNumber * 10) / 10; + if (this.idbdb || this._state.isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versions = this._versions; + var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; + if (versionInstance) + return versionInstance; + versionInstance = new this.Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + versionInstance.stores({}); + this._state.autoSchema = false; + return versionInstance; + }; + Dexie.prototype._whenReady = function (fn) { + var _this = this; + return this._state.openComplete || PSD.letThrough ? fn() : new DexiePromise(function (resolve, reject) { + if (!_this._state.isBeingOpened) { + if (!_this._options.autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + _this.open().catch(nop); + } + _this._state.dbReadyPromise.then(resolve, reject); + }).then(fn); + }; + Dexie.prototype.use = function (_a) { + var stack = _a.stack, create = _a.create, level = _a.level, name = _a.name; + if (name) + this.unuse({ stack: stack, name: name }); + var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); + middlewares.push({ stack: stack, create: create, level: level == null ? 10 : level, name: name }); + middlewares.sort(function (a, b) { return a.level - b.level; }); + return this; + }; + Dexie.prototype.unuse = function (_a) { + var stack = _a.stack, name = _a.name, create = _a.create; + if (stack && this._middlewares[stack]) { + this._middlewares[stack] = this._middlewares[stack].filter(function (mw) { + return create ? mw.create !== create : + name ? mw.name !== name : + false; + }); + } + return this; + }; + Dexie.prototype.open = function () { + return dexieOpen(this); + }; + Dexie.prototype.close = function () { + var idx = connections.indexOf(this), state = this._state; + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this.idbdb = null; + } + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + }; + Dexie.prototype.delete = function () { + var _this = this; + var hasArguments = arguments.length > 0; + var state = this._state; + return new DexiePromise(function (resolve, reject) { + var doDelete = function () { + _this.close(); + var req = _this._deps.indexedDB.deleteDatabase(_this.name); + req.onsuccess = wrap(function () { + databaseEnumerator.remove(_this.name); + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = _this._fireOnBlocked; + }; + if (hasArguments) + throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (state.isBeingOpened) { + state.dbReadyPromise.then(doDelete); + } + else { + doDelete(); + } + }); + }; + Dexie.prototype.backendDB = function () { + return this.idbdb; + }; + Dexie.prototype.isOpen = function () { + return this.idbdb !== null; + }; + Dexie.prototype.hasBeenClosed = function () { + var dbOpenError = this._state.dbOpenError; + return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); + }; + Dexie.prototype.hasFailed = function () { + return this._state.dbOpenError !== null; + }; + Dexie.prototype.dynamicallyOpened = function () { + return this._state.autoSchema; + }; + Object.defineProperty(Dexie.prototype, "tables", { + get: function () { + var _this = this; + return keys(this._allTables).map(function (name) { return _this._allTables[name]; }); + }, + enumerable: true, + configurable: true + }); + Dexie.prototype.transaction = function () { + var args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + }; + Dexie.prototype._transaction = function (mode, tables, scopeFunc) { + var _this = this; + var parentTransaction = PSD.trans; + if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) + parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); + var idbMode, storeNames; + try { + storeNames = tables.map(function (table) { + var storeName = table instanceof _this.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; + }); + if (mode == "r" || mode === READONLY) + idbMode = READONLY; + else if (mode == "rw" || mode == READWRITE) + idbMode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + if (parentTransaction.mode === READONLY && idbMode === READWRITE) { + if (onlyIfCompatible) { + 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) { + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + parentTransaction = null; + } + } + } + catch (e) { + return parentTransaction ? + parentTransaction._promise(null, function (_, reject) { reject(e); }) : + rejection(e); + } + var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); + return (parentTransaction ? + parentTransaction._promise(idbMode, enterTransaction, "lock") : + PSD.trans ? + usePSD(PSD.transless, function () { return _this._whenReady(enterTransaction); }) : + this._whenReady(enterTransaction)); + }; + Dexie.prototype.table = function (tableName) { + if (!hasOwn(this._allTables, tableName)) { + throw new exceptions.InvalidTable("Table " + tableName + " does not exist"); + } + return this._allTables[tableName]; + }; + return Dexie; +}()); + +var Dexie$1 = Dexie; +props(Dexie$1, __assign(__assign({}, fullNameExceptions), { + delete: function (databaseName) { + var db = new Dexie$1(databaseName); + return db.delete(); + }, + exists: function (name) { + return new Dexie$1(name, { addons: [] }).open().then(function (db) { + db.close(); + return true; + }).catch('NoSuchDatabaseError', function () { return false; }); + }, + getDatabaseNames: function (cb) { + return databaseEnumerator ? + databaseEnumerator.getDatabaseNames().then(cb) : + DexiePromise.resolve([]); + }, + defineClass: function () { + function Class(content) { + extend(this, content); + } + return Class; + }, + ignoreTransaction: function (scopeFunc) { + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : + scopeFunc(); + }, + vip: vip, async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return DexiePromise.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 DexiePromise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }, + currentTransaction: { + get: function () { return PSD.trans || null; } + }, waitFor: function (promiseOrFunction, optionalTimeout) { + var promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? + Dexie$1.ignoreTransaction(promiseOrFunction) : + promiseOrFunction) + .timeout(optionalTimeout || 60000); + return PSD.trans ? + PSD.trans.waitFor(promise) : + promise; + }, + Promise: DexiePromise, + debug: { + get: function () { return debug; }, + set: function (value) { + setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); + } + }, + derive: derive, extend: extend, props: props, override: override, + Events: Events, + getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, asap: asap, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: (function () { + try { + return { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; + } + catch (e) { + return { indexedDB: null, IDBKeyRange: null }; + } + })(), + 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)); }), + default: Dexie$1, + Dexie: Dexie$1 })); +Dexie$1.maxKey = getMaxKey(Dexie$1.dependencies.IDBKeyRange); + +initDatabaseEnumerator(Dexie.dependencies.indexedDB); +DexiePromise.rejectionMapper = mapError; +setDebug(debug, dexieStackFrameFilter); + +export default Dexie; +//# sourceMappingURL=dexie.mjs.map diff --git a/dist/dexie.mjs.map b/dist/dexie.mjs.map new file mode 100644 index 000000000..3cdda2176 --- /dev/null +++ b/dist/dexie.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.mjs","sources":["../node_modules/tslib/tslib.es6.js","../src/functions/utils.ts","../src/helpers/debug.ts","../src/errors/errors.js","../src/functions/chaining-functions.js","../src/helpers/promise.js","../src/functions/temp-transaction.ts","../src/globals/constants.ts","../src/functions/combine.ts","../src/dbcore/keyrange.ts","../src/classes/table/table.ts","../src/helpers/Events.js","../src/functions/make-class-constructor.ts","../src/classes/table/table-constructor.ts","../src/classes/collection/collection-helpers.ts","../src/classes/collection/collection.ts","../src/classes/collection/collection-constructor.ts","../src/functions/compare-functions.ts","../src/classes/where-clause/where-clause-helpers.ts","../src/classes/where-clause/where-clause.ts","../src/classes/where-clause/where-clause-constructor.ts","../src/functions/quirks.ts","../src/functions/event-wrappers.ts","../src/classes/transaction/transaction.ts","../src/classes/transaction/transaction-constructor.ts","../src/helpers/index-spec.ts","../src/helpers/table-schema.ts","../src/dbcore/get-key-extractor.ts","../src/dbcore/get-effective-keys.ts","../src/dbcore/dbcore-indexeddb.ts","../src/classes/dexie/generate-middleware-stacks.ts","../src/classes/version/schema-helpers.ts","../src/classes/version/version.ts","../src/classes/version/version-constructor.ts","../src/helpers/database-enumerator.ts","../src/classes/dexie/vip.ts","../src/classes/dexie/dexie-open.ts","../src/helpers/yield-support.ts","../src/classes/dexie/transaction-helpers.ts","../src/dbcore/virtual-index-middleware.ts","../src/hooks/hooks-middleware.ts","../src/classes/dexie/dexie.ts","../src/classes/dexie/dexie-static-props.ts","../src/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","declare var global;\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\nconst _global =\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\nif (typeof Promise !== 'undefined' && !_global.Promise){\n // In jsdom, this it can be the case that Promise is not put on the global object.\n // If so, we need to patch the global object for the rest of the code to work as expected.\n // Other dexie code expects Promise to be on the global object (like normal browser environments)\n _global.Promise = Promise;\n}\nexport { _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 const getProto = Object.getPrototypeOf;\nexport const _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(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options?) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {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 const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nconst _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 assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n // @ts-ignore\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array, extractor) {\n return array.reduce((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: (...args: any[])=>void, onerror, args?) : void {\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) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1);\n else delete obj[currentKeyPath];\n } 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) {\n if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);\n else delete obj[keyPath];\n } else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].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\nconst concat = [].concat;\nexport function flatten (a: (T | T[])[]) : T[] {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nconst intrinsicTypeNames =\n \"Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]);\nconst intrinsicTypes = intrinsicTypeNames.map(t=>_global[t]);\nconst intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, x=>[x,true]);\n\nexport function deepClone(any: T): T {\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 (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\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\nconst {toString} = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\nexport const getValueOf = (val:any, type: string) => \n type === \"Array\" ? ''+val.map(v => getValueOf(v, toStringTag(v))) :\n type === \"ArrayBuffer\" ? ''+new Uint8Array(val) :\n type === \"Date\" ? val.getTime() :\n ArrayBuffer.isView(val) ? ''+new Uint8Array(val.buffer) :\n val;\n\n export 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(prop => {\n if (!hasOwn(b, prop))\n 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)\n {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName === bpTypeName) {\n if (intrinsicTypeNameSet[apTypeName]) {\n // This is an intrinsic type. Don't go deep diffing it.\n // Instead compare its value in best-effort:\n // (Can compare real values of Date, ArrayBuffers and views)\n if (getValueOf(ap, apTypeName) !== getValueOf(bp, bpTypeName)) {\n rv[prfx + prop] = b[prop]; // Date / ArrayBuffer etc is of different value\n }\n } else {\n // This is not an intrinsic object. Compare the it deeply:\n getObjectDiff(ap, bp, rv, prfx + prop + \".\");\n }\n } else {\n rv[prfx + prop] = b[prop];// Property changed to other type\n } \n } else if (ap !== bp)\n rv[prfx + prop] = b[prop];// Primitive value changed\n }\n });\n keys(b).forEach(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 const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\nexport const getIteratorOf = iteratorSymbol ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\n\nexport const 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) 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--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\nexport const isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : ()=>false;\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 = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\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)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\n// TODO: Replace this in favor of a decorator instead.\nexport function deprecated (what: string, fn: (...args)=>T) {\n return function () {\n console.warn(`${what} is deprecated. See http://dexie.org/docs/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n } as (...args)=>T\n}\n","import { derive, setProp } from '../functions/utils';\nimport { getErrorWithStack, prettyStack } from '../helpers/debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\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 ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key=>failures[key].toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.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 this.message = getMultiErrorMessage(msg, failures);\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((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((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}${!inner ? '' : '\\n ' + inner}`;\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((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])\n 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((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\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, // 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, // 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, // 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 ?\n (res2 === undefined ? undefined : res2) :\n (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--) 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}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend} from '../functions/utils';\nimport {nop, callBoth, mirror} from '../functions/chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from '../errors';\n\n//\n// Promise and Zone (PSD) 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// 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 micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\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// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, 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.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 100,\n [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (()=>{\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, globalP.__proto__, globalP];\n // Generate a native promise (as window.Promise may have been patched)\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n nativeP.__proto__,\n globalP\n ];\n })(),\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nvar schedulePhysicalTick = resolvedGlobalPromise ?\n () => {resolvedGlobalPromise.then(physicalTick);}\n :\n _global.setImmediate ? \n // setImmediate supported. Those modern platforms also supports Function.bind().\n setImmediate.bind(null, physicalTick) :\n _global.MutationObserver ?\n // MutationObserver supported\n () => {\n var hiddenDiv = document.createElement(\"div\");\n (new MutationObserver(() => {\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 \n ()=>{setTimeout(physicalTick,0);};\n\n// Configurable 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 = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n pgp: false,\n env: {},\n finalize: function () {\n this.unhandleds.forEach(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\nexport default function DexiePromise(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 }\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)\n 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\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n if (possibleAwait) decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(DexiePromise.prototype, {\n then: thenProp, // Defined above.\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, PSD)); \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, err =>\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 : this.then(null, err =>\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 finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\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 timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\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 = zone;\n}\n\n// Promise Static Properties\nprops (DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof DexiePromise) return value;\n if (value && typeof value.then === 'function') return new DexiePromise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n //totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((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 // 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(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\nif (NativePromise) {\n if (NativePromise.allSettled) setProp (DexiePromise, \"allSettled\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined') setProp(DexiePromise, \"any\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0) reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => resolve(value),\n failure => {\n failures[i] = failure;\n if (!--remaining) reject(new AggregateError(failures));\n }));\n });\n });\n}\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\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(value => {\n if (promise._state !== null) return; // Already settled\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, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n 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(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\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(()=>{\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 ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\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 ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n 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 env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.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) { // 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().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\n\nexport function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nexport function 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(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) finalizers[--i](); \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(()=>{\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(p => 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) 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\nfunction PromiseReject (reason) {\n return new DexiePromise(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 switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: DexiePromise, configurable: true, writable: true},\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\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);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits(sourceTaskId) {\n if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) return;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n}\n\nif ((''+nativePromiseThen).indexOf('[native code]') === -1) {\n // If the native promise' prototype is patched, we cannot rely on zone echoing.\n // Disable that here:\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n //console.log(\"Total echoes \", totalEchoes);\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled) GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any) GlobalPromise.any = targetEnv.any;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction enqueueNativeMicroTask (job) {\n //\n // Precondition: nativePromiseThen !== undefined\n //\n nativePromiseThen.call(resolvedNativePromise, job);\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone, false),\n nativeAwaitCompatibleWrap(onRejected, zone, false));\n };\n}\n\nconst 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, 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 {_global.onunhandledrejection(event);} catch (_) {}\n }\n if (debug && event && !event.defaultPrevented) {\n console.warn(`Unhandled rejection: ${err.stack || err}`);\n }\n } catch (e) {}\n}\n\nexport var rejection = DexiePromise.reject;\n\nexport {DexiePromise};\n","import { PSD, rejection, newScope } from \"../helpers/promise\";\nimport { DexieOptions } from \"../public/types/dexie-constructor\";\nimport { exceptions } from \"../errors\";\nimport { nop } from \"./chaining-functions\";\nimport { Transaction } from \"../classes/transaction\";\nimport { Dexie } from '../classes/dexie';\n\n/* Generate a temporary transaction when db operations are done outside a transaction scope.\n*/\nexport function tempTransaction (\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n fn: (resolve, reject, trans: Transaction) => any)\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n{\n if (!db._state.openComplete && (!PSD.letThrough)) {\n if (!db._state.isBeingOpened) {\n if (!db._options.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try { trans.create(); } catch (ex) { return rejection(ex); }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(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(() => result);\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.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n}\n","import { Dexie } from \"../classes/dexie\";\n\nexport const DEXIE_VERSION = '{version}'; // Replaced by build-script.\nexport const maxString = String.fromCharCode(65535);\nexport const minKey = -Infinity; // minKey can be constant. maxKey must be a prop of Dexie (_maxKey)\nexport const INVALID_KEY_ARGUMENT =\n \"Invalid key provided. Keys must be of type string, number, Date or Array.\";\nexport const STRING_EXPECTED = \"String expected.\";\nexport const connections: Dexie[] = [];\nexport const isIEOrEdge =\n typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);\nexport const hasIEDeleteObjectStoreBug = isIEOrEdge;\nexport const hangsOnDeleteLargeKeyRange = isIEOrEdge;\nexport const dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nexport const DBNAMES_DB = '__dbnames';\nexport const READONLY = 'readonly';\nexport const READWRITE = 'readwrite';\n","export function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n","import { DBCoreKeyRange, DBCoreRangeType } from '../public/types/dbcore';\n\nexport const AnyRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Any,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]], // BUGBUG: depends on indexeddb impl.\n upperOpen: false\n}\n\nexport const NeverRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Never,\n lower: -Infinity,\n lowerOpen: true,\n upper: -Infinity,\n upperOpen: true\n}\n","import { BulkError, exceptions } from '../../errors';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { DexiePromise as Promise, PSD, newScope, wrap, rejection, beginMicroTickScope, endMicroTickScope } from '../../helpers/promise';\nimport { Transaction } from '../transaction';\nimport { Dexie } from '../dexie';\nimport { tempTransaction } from '../../functions/temp-transaction';\nimport { Collection } from '../collection';\nimport { isArray, keys, getByKeyPath, hasOwn, setByKeyPath, deepClone, tryCatch, arrayToObject, extend } from '../../functions/utils';\nimport { maxString } from '../../globals/constants';\nimport { combine } from '../../functions/combine';\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { IndexableType } from '../../public/types/indexable-type';\nimport { debug } from '../../helpers/debug';\nimport { DBCoreTable } from '../../public/types/dbcore';\nimport { AnyRange } from '../../dbcore/keyrange';\n\n/** class Table\n * \n * http://dexie.org/docs/Table/Table\n */\nexport class Table implements ITable {\n db: Dexie;\n _tx?: Transaction;\n name: string;\n schema: TableSchema;\n hook: TableHooks;\n core: DBCoreTable;\n\n _trans(\n mode: IDBTransactionMode,\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike | void,\n writeLocked?: boolean | string) : PromiseExtended\n {\n const trans: Transaction = this._tx || PSD.trans;\n const tableName = this.name;\n \n function checkTableInTransaction(resolve, reject, trans: Transaction) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n // Surround all in a microtick scope.\n // Reason: Browsers (modern Safari + older others)\n // still as of 2018-10-10 has problems keeping a transaction\n // alive between micro ticks. Safari because if transaction\n // is created but not used in same microtick, it will go\n // away. That specific issue could be solved in DBCore\n // by opening the transaction just before using it instead.\n // But older Firefoxes and IE11 (with Promise polyfills)\n // will still have probs.\n // The beginMicrotickScope()/endMicrotickScope() works\n // in cooperation with Dexie.Promise to orchestrate\n // the micro-ticks in endMicrotickScope() rather than\n // in native engine.\n const wasRootExec = beginMicroTickScope();\n try {\n return trans && trans.db === this.db ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n } finally {\n if (wasRootExec) endMicroTickScope();\n }\n }\n\n /** Table.get()\n * \n * http://dexie.org/docs/Table/Table.get()\n * \n **/\n get(keyOrCrit, cb?) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit as { [key: string]: IndexableType }).first(cb);\n\n return this._trans('readonly', (trans) => {\n return this.core.get({trans, key: keyOrCrit})\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n\n /** Table.where()\n * \n * http://dexie.org/docs/Table/Table.where()\n * \n **/\n where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n\n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix =>\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\n (ix.keyPath as string[]).every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\n\n if (compoundIndex && this.db._maxKey !== maxString)\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n return this\n .where(compoundIndex.name)\n .equals((compoundIndex.keyPath as string[]).map(kp => indexOrCrit[kp]));\n\n if (!compoundIndex && debug) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n\n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n const { idxByName } = this.schema;\n const idb = this.db._deps.indexedDB;\n\n function equals (a, b) {\n try {\n return idb.cmp(a,b) === 0; // Works with all indexable types including binary keys.\n } catch (e) {\n return false;\n }\n }\n\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index, // idx::=Pick index of first matching keypath\n prevIndex || !index ? // filter::=null if not needed, otherwise combine function filter\n combine(\n prevFilterFn,\n index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily with \"[a+b+c] is not indexed\"\n }\n\n /** Table.filter()\n * \n * http://dexie.org/docs/Table/Table.filter()\n * \n **/\n filter(filterFunction: (obj: any) => boolean) {\n return this.toCollection().and(filterFunction);\n }\n\n /** Table.count()\n * \n * http://dexie.org/docs/Table/Table.count()\n * \n **/\n count(thenShortcut?: any) {\n return this.toCollection().count(thenShortcut);\n }\n\n /** Table.offset()\n * \n * http://dexie.org/docs/Table/Table.offset()\n * \n **/\n offset(offset: number) {\n return this.toCollection().offset(offset);\n }\n\n /** Table.limit()\n * \n * http://dexie.org/docs/Table/Table.limit()\n * \n **/\n limit(numRows: number) {\n return this.toCollection().limit(numRows);\n }\n\n /** Table.each()\n * \n * http://dexie.org/docs/Table/Table.each()\n * \n **/\n each(callback: (obj: any, cursor: { key: IndexableType, primaryKey: IndexableType }) => any) {\n return this.toCollection().each(callback);\n }\n\n /** Table.toArray()\n * \n * http://dexie.org/docs/Table/Table.toArray()\n * \n **/\n toArray(thenShortcut?: any) {\n return this.toCollection().toArray(thenShortcut);\n }\n\n /** Table.toCollection()\n * \n * http://dexie.org/docs/Table/Table.toCollection()\n * \n **/\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n\n /** Table.orderBy()\n * \n * http://dexie.org/docs/Table/Table.orderBy()\n * \n **/\n orderBy(index: string | string[]) {\n return new this.db.Collection(\n new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n\n /** Table.reverse()\n * \n * http://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * http://dexie.org/docs/Table/Table.mapToClass()\n * \n **/\n mapToClass(constructor: Function) {\n this.schema.mappedClass = constructor;\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 const readHook = 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 const res = Object.create(constructor.prototype);\n // Clone members:\n for (var m in obj) if (hasOwn(obj, m)) try { res[m] = obj[m]; } 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\n /** @deprecated */\n defineClass() {\n function Class (content){\n extend(this, content);\n };\n return this.mapToClass(Class);\n }\n\n /** Table.add()\n * \n * http://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [obj]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (!this.core.schema.primaryKey.outbound) {\n try{setByKeyPath(obj, this.core.schema.primaryKey.keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * http://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; }): PromiseExtended {\n if (typeof modifications !== 'object' || isArray(modifications))\n 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(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\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 /** Table.put()\n * \n * http://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [obj], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (!this.core.schema.primaryKey.outbound) {\n try{setByKeyPath(obj, this.core.schema.primaryKey.keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * http://dexie.org/docs/Table/Table.delete()\n * \n **/\n delete(key: IndexableType): PromiseExtended {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'delete', keys: [key]}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.clear()\n * \n * http://dexie.org/docs/Table/Table.clear()\n * \n **/\n clear() {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'deleteRange', range: AnyRange}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.bulkGet()\n * \n * http://dexie.org/docs/Table/Table.bulkGet()\n * \n * @param keys \n */\n bulkGet(keys: IndexableType[]) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n\n /** Table.bulkAdd()\n * \n * http://dexie.org/docs/Table/Table.bulkAdd()\n * \n **/\n bulkAdd(\n objects: any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {outbound} = this.core.schema.primaryKey;\n if (!outbound && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objects, wantResults}\n )\n .then(({numFailures, results,lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`,\n Object.keys(failures).map(pos => failures[pos]));\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * http://dexie.org/docs/Table/Table.bulkPut()\n * \n **/\n bulkPut(\n objects: any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {outbound} = this.core.schema.primaryKey;\n if (!outbound && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objects, wantResults}\n )\n .then(({numFailures, results, lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`,\n Object.keys(failures).map(pos => failures[pos]));\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * http://dexie.org/docs/Table/Table.bulkDelete()\n * \n **/\n bulkDelete(keys: ReadonlyArray): PromiseExtended {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'delete', keys: keys as IndexableType[]});\n }).then(({numFailures, lastResult, failures}) => {\n if (numFailures === 0) return lastResult;\n throw new BulkError(\n `${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n","import {keys, isArray, asap} from '../functions/utils';\nimport {nop, mirror, reverseStoppableEventChain} from '../functions/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, args = new Array(i - 1);\n while (--i) 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) { return fn !== cb; });\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, args = new Array(i);\n while (i--) 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}\n","import { arrayToObject, derive } from './utils';\n\n\nexport function makeClassConstructor (prototype: Object, constructor: Function) {\n /*const propertyDescriptorMap = arrayToObject(\n Object.getOwnPropertyNames(prototype),\n propKey => [propKey, Object.getOwnPropertyDescriptor(prototype, propKey)]);\n\n // Both derive and clone the prototype.\n // derive: So that x instanceof T returns true when T is the class template.\n // clone: Optimizes method access a bit (but actually not nescessary)\n const derivedPrototypeClone = Object.create(prototype, propertyDescriptorMap);\n derivedPrototypeClone.constructor = constructor;\n constructor.prototype = derivedPrototypeClone;\n return constructor as any as TConstructor;*/\n\n // Keep the above code in case we want to clone AND derive the parent prototype.\n // Reason would be optimization of property access.\n // The code below will only create a prototypal inheritance from given constructor function\n // to given prototype.\n derive(constructor).from({prototype});\n return constructor as any as TConstructor; \n}\n","import { Dexie } from '../dexie';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { Transaction } from '../transaction/transaction';\nimport { hookCreatingChain, pureFunctionChain, nop, mirror, hookUpdatingChain, hookDeletingChain } from '../../functions/chaining-functions';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { Table } from './table';\nimport Events from '../../helpers/Events';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\n\nexport interface TableConstructor {\n new (name: string, tableSchema: TableSchema, optionalTrans?: Transaction) : Table;\n prototype: Table;\n}\n\n/** Generates a Table constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTableConstructor (db: Dexie) {\n return makeClassConstructor(\n Table.prototype,\n\n function Table (this: Table, name: string, tableSchema: TableSchema, trans?: Transaction) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n }) as TableHooks;\n }\n\n );\n}\n","import { combine } from \"../../functions/combine\";\nimport { exceptions } from \"../../errors\";\nimport { hasOwn } from \"../../functions/utils\";\nimport { wrap } from \"../../helpers/promise\";\nimport { Collection } from './';\nimport { DBCoreCursor, DBCoreTable, DBCoreTransaction, DBCoreTableSchema, DBCoreRangeType } from '../../public/types/dbcore';\nimport { nop } from '../../functions/chaining-functions';\n\ntype CollectionContext = Collection[\"_ctx\"];\n\nexport function isPlainKeyRange (ctx: CollectionContext, ignoreLimitFilter?: boolean) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n} \n\nexport function addFilter(ctx: CollectionContext, fn: Function) {\n ctx.filter = combine(ctx.filter, fn);\n}\n\nexport function addReplayFilter (ctx: CollectionContext, factory, isLimitFilter?) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\n\nexport function addMatchFilter(ctx: CollectionContext, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\n\nexport function getIndexOrStore(ctx: CollectionContext, coreSchema: DBCoreTableSchema) {\n // TODO: Rewrite this. No need to know ctx.isPrimKey. ctx.index should hold the keypath.\n // Still, throw if not found!\n if (ctx.isPrimKey) return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\n\nexport function openCursor(ctx: CollectionContext, coreTable: DBCoreTable, trans: DBCoreTransaction) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index, \n range: ctx.range\n }\n });\n}\n\nexport function iter (\n ctx: CollectionContext, \n fn: (item, cursor: DBCoreCursor, advance: Function)=>void,\n coreTrans: DBCoreTransaction,\n coreTable: DBCoreTable): Promise\n{\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(\n openCursor(ctx, coreTable, coreTrans),\n combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n } else {\n const set = {};\n\n const union = (item: any, cursor: DBCoreCursor, advance) => {\n if (!filter || filter(cursor, advance, result=>cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\n\nfunction iterate(cursorPromise: Promise, filter, fn, valueMapper): Promise {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn);\n \n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(()=>{\n var c = ()=>cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val=>{cursor.stop(val);c=nop}, e => {cursor.fail(e);c = nop;}))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n","import { Collection as ICollection } from \"../../public/types/collection\";\nimport { Dexie } from \"../dexie\";\nimport { Table } from \"../table\";\nimport { IndexableType, IndexableTypeArrayReadonly } from \"../../public/types/indexable-type\";\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { iter, isPlainKeyRange, getIndexOrStore, addReplayFilter, addFilter, addMatchFilter } from \"./collection-helpers\";\nimport { rejection } from \"../../helpers/promise\";\nimport { combine } from \"../../functions/combine\";\nimport { extend, hasOwn, deepClone, keys, setByKeyPath, getByKeyPath } from \"../../functions/utils\";\nimport { ModifyError } from \"../../errors\";\nimport { hangsOnDeleteLargeKeyRange } from \"../../globals/constants\";\nimport { ThenShortcut } from \"../../public/types/then-shortcut\";\nimport { Transaction } from '../transaction';\nimport { DBCoreCursor, DBCoreTransaction, DBCoreRangeType, DBCoreMutateResponse, DBCoreKeyRange } from '../../public/types/dbcore';\n\n/** class Collection\n * \n * http://dexie.org/docs/Collection/Collection\n */\nexport class Collection implements ICollection {\n db: Dexie;\n _ctx: {\n table: Table;\n index?: string | null;\n isPrimKey?: boolean;\n range: DBCoreKeyRange;\n keysOnly: boolean;\n dir: \"next\" | \"prev\";\n unique: \"\" | \"unique\";\n algorithm?: Function | null;\n filter?: Function | null;\n replayFilter: Function | null;\n justLimit: boolean; // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: Function | null;\n offset: number,\n limit: number,\n error: any, // If set, any promise must be rejected with this error\n or: Collection,\n valueMapper: (any) => any\n }\n \n _ondirectionchange?: Function;\n\n _read(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike, cb?): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n\n _write(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n }\n\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n\n _iterate(\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction) : Promise\n {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n\n /** Collection.clone()\n * \n * http://dexie.org/docs/Collection/Collection.clone()\n * \n **/\n clone(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 /** Collection.raw()\n * \n * http://dexie.org/docs/Collection/Collection.raw()\n * \n **/\n raw() {\n this._ctx.valueMapper = null;\n return this;\n }\n\n /** Collection.each()\n * \n * http://dexie.org/docs/Collection/Collection.each()\n * \n **/\n each(fn: (obj, cursor: DBCoreCursor) => any): PromiseExtended {\n var ctx = this._ctx;\n\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n\n /** Collection.count()\n * \n * http://dexie.org/docs/Collection/Collection.count()\n * \n **/\n count(cb?) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(()=>count);\n }\n }).then(cb);\n }\n\n /** Collection.sortBy()\n * \n * http://dexie.org/docs/Collection/Collection.sortBy()\n * \n **/\n sortBy(keyPath: string): PromiseExtended;\n sortBy(keyPath: string, thenShortcut: ThenShortcut) : PromiseExtended;\n sortBy(keyPath: string, cb?: ThenShortcut) {\n const 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 /** Collection.toArray()\n * \n * http://dexie.org/docs/Collection/Collection.toArray()\n * \n **/\n toArray(cb?): PromiseExtended {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n const {valueMapper} = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({result}) => valueMapper ? result.map(valueMapper) : result);\n } else {\n // Getting array through a cursor.\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(()=>a);\n }\n }, cb);\n }\n\n /** Collection.offset()\n * \n * http://dexie.org/docs/Collection/Collection.offset()\n * \n **/\n offset(offset: number) : Collection{\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n\n /** Collection.limit()\n * \n * http://dexie.org/docs/Collection/Collection.limit()\n * \n **/\n limit(numRows: number) : Collection {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, () => {\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 /** Collection.until()\n * \n * http://dexie.org/docs/Collection/Collection.until()\n * \n **/\n until(filterFunction: (x) => boolean, bIncludeStopEntry?) {\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 /** Collection.first()\n * \n * http://dexie.org/docs/Collection/Collection.first()\n * \n **/\n first(cb?) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.last()\n * \n * http://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * http://dexie.org/docs/Collection/Collection.filter()\n * \n **/\n filter(filterFunction: (x) => boolean): Collection {\n /// function(val){return true/false}\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 /** Collection.and()\n * \n * http://dexie.org/docs/Collection/Collection.and()\n * \n **/\n and(filter: (x) => boolean) {\n return this.filter(filter);\n }\n\n /** Collection.or()\n * \n * http://dexie.org/docs/Collection/Collection.or()\n * \n **/\n or(indexName: string) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n\n /** Collection.reverse()\n * \n * http://dexie.org/docs/Collection/Collection.reverse()\n * \n **/\n reverse() {\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 /** Collection.desc()\n * \n * http://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * http://dexie.org/docs/Collection/Collection.eachKey()\n * \n **/\n eachKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n\n /** Collection.eachUniqueKey()\n * \n * http://dexie.org/docs/Collection/Collection.eachUniqueKey()\n * \n **/\n eachUniqueKey(cb?) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n\n /** Collection.eachPrimaryKey()\n * \n * http://dexie.org/docs/Collection/Collection.eachPrimaryKey()\n * \n **/\n eachPrimaryKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n\n /** Collection.keys()\n * \n * http://dexie.org/docs/Collection/Collection.keys()\n * \n **/\n keys(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 /** Collection.primaryKeys()\n * \n * http://dexie.org/docs/Collection/Collection.primaryKeys()\n * \n **/\n primaryKeys(cb?) : PromiseExtended {\n var ctx = this._ctx;\n if (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(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }});\n }).then(({result})=>result).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 /** Collection.uniqueKeys()\n * \n * http://dexie.org/docs/Collection/Collection.uniqueKeys()\n * \n **/\n uniqueKeys(cb?) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n\n /** Collection.firstKey()\n * \n * http://dexie.org/docs/Collection/Collection.firstKey()\n * \n **/\n firstKey(cb?) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.lastKey()\n * \n * http://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * http://dexie.org/docs/Collection/Collection.distinct()\n * \n **/\n distinct() {\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: DBCoreCursor) {\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 // Methods that mutate storage\n //\n\n /** Collection.modify()\n * \n * http://dexie.org/docs/Collection/Collection.modify()\n * \n **/\n modify(changes: { [keyPath: string]: any }) : PromiseExtended\n modify(changes: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean): PromiseExtended {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean\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 modifyer = changes;\n } else {\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], 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 }\n\n const coreTable = ctx.table.core;\n const {outbound, extractKey} = coreTable.schema.primaryKey;\n const limit = 'testmode' in Dexie ? 1 : 2000;\n const {cmp} = this.db.core;\n const totalFailures = [];\n let successCount = 0;\n const failedKeys: IndexableType[] = [];\n const applyMutateResult = (expectedCount: number, res: DBCoreMutateResponse) => {\n const {failures, numFailures} = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n }\n return this.clone().primaryKeys().then(keys => {\n\n const nextChunk = (offset: number) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({trans, keys: keys.slice(offset, offset + count)}).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i=0; i 0 &&\n coreTable.mutate({trans, type: 'add', values: addValues})\n .then(res => {\n for (let pos in res.failures) {\n // Remove from deleteKeys the key of the object that failed to change its primary key\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })\n ).then(res=>putValues.length > 0 &&\n coreTable.mutate({trans, type: 'put', keys: putKeys, values: putValues})\n .then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>deleteKeys.length > 0 &&\n coreTable.mutate({trans, type: 'delete', keys: deleteKeys})\n .then(res=>applyMutateResult(deleteKeys.length, res))\n ).then(()=>{\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n }\n\n return nextChunk(0).then(()=>{\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys as IndexableTypeArrayReadonly);\n\n return keys.length;\n });\n });\n\n });\n }\n\n /** Collection.delete()\n * \n * http://dexie.org/docs/Collection/Collection.delete()\n * \n **/\n delete() : PromiseExtended {\n var ctx = this._ctx,\n range = ctx.range;\n //deletingHook = ctx.table.hook.deleting.fire,\n //hasDeleteHook = deletingHook !== nop;\n if (isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === DBCoreRangeType.Any)) // 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(trans => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n const {primaryKey} = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({trans, query: {index: primaryKey, range: coreRange}}).then(count => {\n return ctx.table.core.mutate({trans, type: 'deleteRange', range: coreRange})\n .then(({failures, lastResult, results, numFailures}) => {\n if (numFailures) throw new ModifyError(\"Could not delete some values\",\n Object.keys(failures).map(pos => failures[pos]),\n count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n\n return this.modify((value, ctx) => ctx.value = null);\n }\n}\n\n\n","import { Dexie } from '../../classes/dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Collection } from './collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\nimport { mirror } from '../../functions/chaining-functions';\n\n/** Constructs a Collection instance. */\nexport interface CollectionConstructor {\n new(whereClause?: WhereClause | null, keyRangeGenerator?: () => DBCoreKeyRange): Collection;\n prototype: Collection;\n}\n\n/** Generates a Collection constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createCollectionConstructor(db: Dexie) {\n return makeClassConstructor(\n Collection.prototype,\n\n function Collection(\n this: Collection,\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange)\n {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\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: readingHook !== mirror ? readingHook : null\n };\n }\n );\n}\n","import { IndexableType } from '../public/types/indexable-type';\n\nexport function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\n\nexport function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n","import { WhereClause } from './where-clause';\nimport { Collection } from '../collection';\nimport { STRING_EXPECTED } from '../../globals/constants';\nimport { simpleCompare, simpleCompareReverse } from '../../functions/compare-functions';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange, DBCoreRangeType } from '../../public/types/dbcore';\n\nexport function fail(collectionOrWhereClause: Collection | WhereClause, err, T?) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\n\nexport function emptyCollection(whereClause: WhereClause) {\n return new whereClause.Collection (whereClause, () => rangeEqual(\"\")).limit(0);\n}\n\nexport function upperFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toUpperCase() :\n (s: string) => s.toLowerCase();\n}\n\nexport function lowerFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toLowerCase() :\n (s: string) => s.toUpperCase();\n}\n\nexport 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\nexport function addIgnoreCaseAlgorithm(whereClause: WhereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\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){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new whereClause.Collection (\n whereClause,\n ()=>createRange(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 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\n\nexport function createRange (lower: IndexableType, upper: IndexableType, lowerOpen?: boolean, upperOpen?: boolean): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Range,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\n\nexport function rangeEqual (value: IndexableType) : DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Equal,\n lower: value,\n upper: value\n };\n}\n","import { WhereClause as IWhereClause } from \"../../public/types/where-clause\";\nimport { Collection } from \"../collection\";\nimport { Table } from \"../table\";\nimport { IndexableType } from \"../../public/types/indexable-type\";\nimport { emptyCollection, fail, addIgnoreCaseAlgorithm, createRange, rangeEqual } from './where-clause-helpers';\nimport { INVALID_KEY_ARGUMENT, STRING_EXPECTED, maxString, minKey } from '../../globals/constants';\nimport { getArrayOf, NO_CHAR_ARRAY } from '../../functions/utils';\nimport { exceptions } from '../../errors';\nimport { Dexie } from '../dexie';\nimport { Collection as ICollection} from \"../../public/types/collection\";\n\n/** class WhereClause\n * \n * http://dexie.org/docs/WhereClause/WhereClause\n */\nexport class WhereClause implements IWhereClause {\n db: Dexie;\n _IDBKeyRange: typeof IDBKeyRange;\n _ctx: {\n table: Table;\n index: string;\n or: Collection;\n }\n _cmp: (a: IndexableType, b: IndexableType) => number;\n _ascending: (a: IndexableType, b: IndexableType) => number;\n _descending: (a: IndexableType, b: IndexableType) => number;\n _min: (a: IndexableType, b: IndexableType) => IndexableType;\n _max: (a: IndexableType, b: IndexableType) => IndexableType;\n\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n\n /** WhereClause.between()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.between()\n * \n **/\n between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean) {\n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\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.\n return new this.Collection(this, ()=>createRange(lower, upper, !includeLower, !includeUpper));\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n\n /** WhereClause.equals()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.above()\n * \n **/\n above(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n\n /** WhereClause.aboveOrEqual()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.aboveOrEqual()\n * \n **/\n aboveOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n\n /** WhereClause.below()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.below()\n * \n **/\n below(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n\n /** WhereClause.belowOrEqual()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.belowOrEqual()\n * \n **/\n belowOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n\n /** WhereClause.startsWith()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWith()\n * \n **/\n startsWith(str: string) {\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n\n /** WhereClause.startsWithIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWithIgnoreCase()\n * \n **/\n startsWithIgnoreCase(str: string) {\n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n\n /** WhereClause.equalsIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.equalsIgnoreCase()\n * \n **/\n equalsIgnoreCase(str: string) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n\n /** WhereClause.anyOfIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.anyOfIgnoreCase()\n * \n **/\n anyOfIgnoreCase(...values: string[]): Collection;\n anyOfIgnoreCase(values: string[]): Collection;\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n\n /** WhereClause.startsWithAnyOfIgnoreCase()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOfIgnoreCase()\n * \n **/\n startsWithAnyOfIgnoreCase(...values: string[]): Collection;\n startsWithAnyOfIgnoreCase(values: string[]): Collection;\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n\n /** WhereClause.anyOf()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.anyOf()\n * \n **/\n anyOf(...values: string[]): Collection;\n anyOf(values: string[]): Collection;\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const 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(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.notEqual()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.notEqual()\n * \n **/\n notEqual(value: IndexableType) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.noneOf()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.noneOf()\n * \n **/\n noneOf(...values: string[]): Collection;\n noneOf(values: string[]): Collection;\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this.Collection(this); // Return entire collection.\n try { set.sort(this._ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n const ranges = set.reduce(\n (res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]],\n null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.inAnyRange()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.inAnyRange()\n * \n **/\n inAnyRange(\n ranges: ReadonlyArray<{ 0: IndexableType, 1: IndexableType }>,\n options?: { includeLowers?: boolean, includeUppers?: boolean })\n {\n const cmp = this._cmp,\n ascending = this._ascending,\n descending = this._descending,\n min = this._min,\n max = this._max;\n\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(range =>\n range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(\n this,\n \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\",\n exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false; // Default to true\n const includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const 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)\n ranges.push(newRange);\n return ranges;\n }\n\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n\n // Join overlapping ranges\n let 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 let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n let checkKey = keyIsBeyondCurrentEntry;\n\n const c = new this.Collection(\n this,\n () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n\n c._ondirectionchange = 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((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++rangePos;\n if (rangePos === 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 (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][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(() => {\n if (sortDirection === ascending) cursor.continue(set[rangePos][0]);\n else cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.startsWithAnyOf()\n * \n * http://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOf()\n * \n **/\n startsWithAnyOf(...prefixes: string[]): Collection;\n startsWithAnyOf(prefixes: string[]): Collection;\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(s => typeof s === 'string')) {\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((str: string) => [str, str + maxString]));\n }\n\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { WhereClause } from './where-clause';\nimport { Table } from '../table';\nimport { Collection } from '../collection';\nimport { exceptions } from '../../errors';\n\nexport interface WhereClauseConstructor {\n new(table: Table, index?: string, orCollection?: Collection): WhereClause;\n prototype: WhereClause;\n}\n\n/** Generates a WhereClause constructor.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createWhereClauseConstructor(db: Dexie) {\n return makeClassConstructor(\n WhereClause.prototype,\n\n function WhereClause(this: WhereClause, table: Table, index?: string, orCollection?: Collection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n const indexedDB = db._deps.indexedDB;\n if (!indexedDB) throw new exceptions.MissingAPI(\"indexedDB API missing\");\n this._cmp = this._ascending = indexedDB.cmp.bind(indexedDB);\n this._descending = (a, b) => indexedDB.cmp(b, a);\n this._max = (a, b) => indexedDB.cmp(a,b) > 0 ? a : b;\n this._min = (a, b) => indexedDB.cmp(a,b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n }\n );\n}\n","import { maxString } from '../globals/constants';\n\nexport function safariMultiStoreFix(storeNames: string[]) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nexport function getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\nexport function getMaxKey (IdbKeyRange: typeof IDBKeyRange) {\n try {\n IdbKeyRange.only([[]]);\n return [[]];\n } catch (e) {\n return maxString;\n }\n}\n","import { wrap } from \"../helpers/promise\";\n\nexport function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nexport function eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nexport function 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,// 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\nexport function 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 ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\n\nexport function 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\nexport function BulkErrorHandlerCatchAll(errorList, done?, supportHooks?) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n}\n\n","import { Transaction as ITransaction } from '../../public/types/transaction';\nimport { DexiePromise, wrap, rejection } from \"../../helpers/promise\";\nimport { DbSchema } from '../../public/types/db-schema';\nimport { assert, hasOwn } from '../../functions/utils';\nimport { PSD, usePSD } from '../../helpers/promise';\nimport { Dexie } from '../dexie';\nimport { exceptions } from '../../errors';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { preventDefault } from '../../functions/event-wrappers';\nimport { newScope } from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { Table } from '../table';\n\n/** Transaction\n * \n * http://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n idbtrans: IDBTransaction;\n storeNames: string[];\n on: any;\n parent?: Transaction;\n schema: DbSchema;\n _memoizedTables: {[tableName: string]: Table};\n\n _reculock: number;\n _blockedFuncs: { 0: () => any, 1: any }[];\n _resolve: () => void;\n _reject: (Error) => void;\n _waitingFor: DexiePromise; // for waitFor()\n _waitingQueue: Function[]; // for waitFor()\n _spinCount: number; // Just for debugging waitFor()\n _completion: DexiePromise;\n\n //\n // Transaction internal methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _lock() {\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\n /** Transaction._unlock()\n * \n * Internal method.\n */\n _unlock() {\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 fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n }\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _locked() {\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\n /** Transaction.create()\n * \n * Internal method.\n * \n */\n create(idbtrans?: IDBTransaction) {\n if (!this.mode) return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\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); // Completion Promise must still be pending.\n\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode) as IDBTransaction;\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n });\n return this;\n }\n\n /** Transaction._promise()\n * \n * Internal method.\n */\n _promise(\n mode: IDBTransactionMode,\n fn: (resolve, reject, trans: Transaction) => PromiseLike | void,\n bWriteLock?: string | boolean): DexiePromise\n {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n\n /** Transaction._root()\n * \n * Internal method. Retrieves the root transaction in the tree of sub transactions.\n */\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n\n /** Transaction.waitFor()\n * \n * Internal method. Can be accessed from the public API through\n * Dexie.waitFor(): http://dexie.org/docs/Dexie/Dexie.waitFor()\n * \n **/\n waitFor(promiseLike: PromiseLike) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(() => promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n } \n\n /** Transaction.abort()\n * \n * http://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n this.active && this._reject(new exceptions.Abort());\n this.active = false;\n }\n\n /** Transaction.table()\n * \n * http://dexie.org/docs/Transaction/Transaction.table()\n */\n table(tableName: string) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\"); \n }\n\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Transaction } from './transaction';\nimport { DbSchema } from '../../public/types/db-schema';\nimport Events from '../../helpers/Events';\nimport Promise, { rejection } from '../../helpers/promise';\n\nexport interface TransactionConstructor {\n new (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parent?: Transaction) : T;\n prototype: T;\n}\n\n/** Generates a Transaction constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTransactionConstructor(db: Dexie) {\n return makeClassConstructor>(\n Transaction.prototype,\n function Transaction (\n this: Transaction,\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n \n });\n}\n","import { IndexSpec } from '../public/types/index-spec';\n\nexport function createIndexSpec(\n name: string,\n keyPath: string | string[],\n unique: boolean,\n multi: boolean,\n auto: boolean,\n compound: boolean,\n isPrimKey: boolean\n): IndexSpec {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n }\n}\n\nexport function nameFromKeyPath (keyPath?: string | string[]): string {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n","import { IndexSpec } from '../public/types/index-spec';\nimport { TableSchema } from '../public/types/table-schema';\nimport { createIndexSpec } from './index-spec';\nimport { arrayToObject } from '../functions/utils';\n\nexport function createTableSchema (\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n): TableSchema {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n","import { getByKeyPath } from '../functions/utils';\n\nexport function getKeyExtractor (keyPath: null | string | string[]) : (a: any) => any {\n if (keyPath == null) {\n return () => undefined;\n } else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nexport function getSinglePathKeyExtractor(keyPath: string) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n","import {\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreTable,\n} from \"../public/types/dbcore\";\n\nexport function getEffectiveKeys (\n primaryKey: DBCoreIndex,\n req: (Pick & {keys?: any[]}) | Pick)\n{\n //const {outbound} = primaryKey;\n if (req.type === 'delete') return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey)\n}\n\nexport function getExistingValues (table: DBCoreTable, req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest, effectiveKeys: any[]) {\n return req.type === 'add' ? Promise.resolve(new Array(req.values.length)) :\n table.getMany({trans: req.trans, keys: effectiveKeys});\n}\n","import {\n DBCore,\n DBCoreCursor,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryResponse,\n DBCoreRangeType,\n DBCoreSchema,\n DBCoreTableSchema,\n DBCoreTable,\n DBCoreMutateResponse,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { eventRejectHandler, preventDefault } from '../functions/event-wrappers';\nimport { wrap } from '../helpers/promise';\nimport { getMaxKey } from '../functions/quirks';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getEffectiveKeys } from './get-effective-keys';\n\nexport function arrayify(arrayLike: {length: number, [index: number]: T}): T[] {\n return [].slice.call(arrayLike);\n}\nexport function pick(obj: T, props: Prop[]): Pick {\n const result = {} as Pick;\n props.forEach(prop => result[prop] = obj[prop]);\n return result;\n}\n\nlet _id_counter = 0;\n\nexport function getKeyPathAlias(keyPath: null | string | string[]) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\n\nexport function createDBCore (\n db: IDBDatabase,\n indexedDB: IDBFactory,\n IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\n{\n const cmp = indexedDB.cmp.bind(indexedDB);\n \n function extractSchema(db: IDBDatabase, trans: IDBTransaction) : {schema: DBCoreSchema, hasGetAll: boolean} {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const {keyPath, autoIncrement} = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath: {[keyPathAlias: string]: DBCoreIndex} = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n } as DBCoreIndex,\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const {name, unique, multiEntry, keyPath} = index;\n const compound = isArray(keyPath);\n const result: DBCoreIndex = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath: null | string | string[]) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) // Bug with getAll() on Safari ver<604. See discussion following PR #579\n };\n }\n\n function makeIDBKeyRange (range: DBCoreKeyRange) : IDBKeyRange | null {\n if (range.type === DBCoreRangeType.Any) return null;\n if (range.type === DBCoreRangeType.Never) throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const {lower, upper, lowerOpen, upperOpen} = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null : //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)\n IdbKeyRange.upperBound(upper, !!upperOpen) : // below\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) : // above\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n\n function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {\n const tableName = tableSchema.name;\n\n function mutate ({trans, type, keys, values, range, wantResults}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error (\"Invalid operation type: \" + type);\n\n const {length} = keys || values || {length: 1}; // keys.length if keys. values.length if values. 1 if range.\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n // No items to write. Don't even bother!\n return resolve({numFailures: 0, failures: {}, results: [], lastResult: undefined});\n\n const results = wantResults && [...(keys ?\n keys : // keys already resolved in an earlier middleware. Don't re-resolve them.\n getEffectiveKeys(tableSchema.primaryKey, {type, keys, values}))];\n \n let req: IDBRequest & { _reqno?};\n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\n if (results) results[(event.target as any)._reqno] = undefined;\n failures[(event.target as any)._reqno] = event.target.error;\n };\n const setResult = ({target}) => {\n results[target._reqno] = target.result;\n }\n \n if (type === 'deleteRange') {\n // Here the argument is the range\n if (range.type === DBCoreRangeType.Never)\n return resolve({numFailures, failures, results, lastResult: undefined}); // Deleting the Never range shoulnt do anything.\n if (range.type === DBCoreRangeType.Any)\n req = store.clear(); // Deleting the Any range is equivalent to store.clear()\n else\n req = store.delete(makeIDBKeyRange(range));\n } else {\n // No matter add, put or delete - find out arrays of first and second arguments to it.\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n\n if (isAddOrPut) {\n for (let i=0; i {\n const lastResult = event.target.result;\n if (results) results[length-1] = lastResult;\n resolve({\n numFailures,\n failures,\n results,\n lastResult\n });\n };\n \n req.onerror = event => { // wrap() not needed. All paths calling outside will wrap!\n errorHandler(event);\n done(event);\n };\n \n req.onsuccess = done;\n });\n }\n \n function openCursor ({trans, values, query, reverse, unique}: DBCoreOpenCursorRequest): Promise\n {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n // source\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n // direction\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n // request\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n \n // iteration\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n\n const cursor = req.result as unknown as DBCoreCursor;\n if (!cursor) {\n resolve(null);\n return;\n }\n (cursor as any).___id = ++_id_counter;\n (cursor as any).done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey) _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = ()=>{throw new Error(\"Cursor not started\");}\n const doThrowCursorIsStopped = ()=>{throw new Error(\"Cursor not stopped\");}\n (cursor as any).trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function (this: DBCoreCursor) {\n // next() must work with \"this\" pointer in order to function correctly for ProxyCursors (derived objects)\n // without having to re-define next() on each child.\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n //console.log(\"Starting cursor\", (cursor as any).___id);\n const iterationPromise = new Promise((resolveIteration, rejectIteration) =>{\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n //console.log(\"Cursor stop\", cursor);\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n // Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()\n const guardedCallback = () => {\n if (req.result) {\n //console.log(\"Next result\", cursor);\n try {\n callback();\n } catch (err) {\n cursor.fail(err);\n }\n } else {\n (cursor as any).done = true;\n cursor.start = ()=>{throw new Error(\"Cursor behind last entry\");}\n cursor.stop();\n }\n }\n req.onsuccess = wrap(ev => {\n //cursor.continue = _cursorContinue;\n //cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n //cursor.advance = _cursorAdvance;\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject); \n });\n }\n \n function query (hasGetAll: boolean) {\n return (request: DBCoreQueryRequest) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {trans, values, limit, query} = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0) return resolve({result: []});\n if (hasGetAll) {\n const req = values ?\n (source as any).getAll(idbKeyRange, nonInfinitLimit) :\n (source as any).getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({result: event.target.result});\n req.onerror = eventRejectHandler(reject);\n } else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange)\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result as IDBCursorWithValue;\n if (!cursor) return resolve({result});\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit) return resolve({result});\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n \n return {\n name: tableName,\n schema: tableSchema,\n \n mutate,\n\n getMany ({trans, keys}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let valueCount = 0;\n let req: IDBRequest & {_pos?: number};\n \n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null) ++valueCount;\n if (++callbackCount === keyCount) resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n \n for (let i=0; i((resolve, reject) => {\n resolve = wrap (resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve((event.target as any).result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n\n query: query(hasGetAll),\n \n openCursor,\n\n count ({query, trans}) {\n const {index, range} = query;\n return new Promise((resolve, reject) => {\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve((ev.target as IDBRequest).result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n\n const {schema, hasGetAll} = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap: {[name: string]: DBCoreTable} = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n \n transaction: db.transaction.bind(db),\n\n table(name: string) {\n const result = tableMap[name];\n if (!result) throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n\n cmp,\n\n MIN_KEY: -Infinity,\n\n MAX_KEY: getMaxKey(IdbKeyRange),\n\n schema\n\n };\n}\n","import { Dexie } from './';\nimport { createDBCore } from '../../dbcore/dbcore-indexeddb';\nimport { DBCore } from '../../public/types/dbcore';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { DexieStacks, Middleware } from '../../public/types/middleware';\nimport { exceptions } from '../../errors';\n\nfunction createMiddlewareStack(\n stackImpl: {stack: string},\n middlewares: Middleware<{stack: string}>[]): TStack {\n return middlewares.reduce((down, {create}) => ({...down, ...create(down)}), stackImpl) as TStack;\n} \n\nfunction createMiddlewareStacks(\n middlewares: {[StackName in keyof DexieStacks]?: Middleware[]},\n idbdb: IDBDatabase,\n {IDBKeyRange, indexedDB}: DexieDOMDependencies,\n tmpTrans: IDBTransaction): {[StackName in keyof DexieStacks]?: DexieStacks[StackName]}\n{\n const dbcore = createMiddlewareStack(\n createDBCore(idbdb, indexedDB, IDBKeyRange, tmpTrans),\n middlewares.dbcore);\n \n // TODO: Create other stacks the same way as above. They might be dependant on the result\n // of creating dbcore stack.\n\n return {\n dbcore\n };\n}\n\nexport function generateMiddlewareStacks(db: Dexie, tmpTrans: IDBTransaction) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore!;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n","import { Dexie } from '../dexie';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { setProp, keys, slice, _global, isArray, shallowClone, isAsyncFunction, defineProperty } from '../../functions/utils';\nimport { Transaction } from '../transaction';\nimport { Version } from './version';\nimport Promise, { PSD, newScope, NativePromise, decrementExpectedAwaits, incrementExpectedAwaits } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { hasIEDeleteObjectStoreBug, isIEOrEdge } from '../../globals/constants';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { createIndexSpec, nameFromKeyPath } from '../../helpers/index-spec';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { generateMiddlewareStacks } from '../dexie/generate-middleware-stacks';\n\nexport function setApiOnPlace(db: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n if (!(tableName in obj)) {\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {\n get(this: Transaction) { return this.table(tableName); },\n set(value: any) {\n // Issue #1039\n // Let \"this.schema = dbschema;\" and other props in transaction constructor work even if there's a name collision with the table name.\n defineProperty(this, tableName, {value, writable: true, configurable: true, enumerable: true});\n }\n });\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\n\nexport function removeTablesApi(db: Dexie, objs: Object[]) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table) delete obj[key];\n }\n });\n}\n\nexport function lowerVersionFirst(a: Version, b: Version) {\n return a._cfg.version - b._cfg.version;\n}\n\nexport function runUpgraders(db: Dexie, oldVersion: number, idbUpgradeTrans: IDBTransaction, reject) {\n const globalSchema = db._dbSchema;\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n Promise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction);\n });\n}\n\nexport type UpgradeQueueItem = (idbtrans: IDBTransaction) => PromiseLike | void;\n\nexport function updateTablesAndIndexes(\n db: Dexie,\n oldVersion: number,\n trans: Transaction,\n idbUpgradeTrans: IDBTransaction)\n{\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 const queue: UpgradeQueueItem[] = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n\n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n\n globalSchema = db._dbSchema = newSchema;\n\n const diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n const store = idbUpgradeTrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(idx => addIndex(store, idx));\n // Update indexes\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n\n const contentUpgrade = version._cfg.contentUpgrade;\n\n if (contentUpgrade && version._cfg.version > oldVersion) {\n // Update db.core with new tables and indexes:\n generateMiddlewareStacks(db, idbUpgradeTrans);\n\n anyContentUpgraderHasRun = true;\n\n // Add to-be-deleted tables to contentUpgrade transaction\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n\n // Safe to affect Transaction.prototype globally in this moment,\n // because when this code runs, there may not be any other code\n // that can access any transaction instance, else than this particular\n // upgrader function.\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n\n // Support for native async await.\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n \n let returnValue: any;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n // contentUpgrade is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n Promise.resolve(returnValue) : promiseFollowed.then(()=>returnValue));\n }\n });\n queue.push(idbtrans => {\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.\n const newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n // Restore the final API\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\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) :\n Promise.resolve();\n }\n\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n}\n\nexport interface SchemaDiff {\n del: string[],\n add: [string, TableSchema][];\n change: TableSchemaDiff[];\n}\n\nexport interface TableSchemaDiff {\n name: string,\n recreate: boolean,\n del: string[],\n add: IndexSpec[],\n change: IndexSpec[]\n}\n\nexport function getSchemaDiff(oldSchema: DbSchema, newSchema: DbSchema): SchemaDiff {\n const diff: SchemaDiff = {\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 let table: string;\n for (table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n const 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 !isIEOrEdge // IE and non-chromium Edge has a bug reading spec of primary key\n ) \n { \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 const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName: string;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n 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\nexport function createTable(\n idbtrans: IDBTransaction,\n tableName: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n) {\n const store = idbtrans.db.createObjectStore(\n tableName,\n primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto }\n );\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\n\nexport function createMissingTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\n\nexport function deleteRemovedTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\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\nexport function addIndex(store: IDBObjectStore, idx: IndexSpec) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\n\nfunction buildGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(\n nameFromKeyPath(keyPath),\n keyPath || \"\",\n false,\n false,\n !!store.autoIncrement,\n keyPath && typeof keyPath !== \"string\",\n true\n );\n const indexes: IndexSpec[] = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(\n idbindex.name,\n keyPath,\n !!idbindex.unique,\n !!idbindex.multiEntry,\n false,\n keyPath && typeof keyPath !== \"string\",\n false\n );\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\n\nexport function readGlobalSchema(db: Dexie, idbdb: IDBDatabase, tmpTrans: IDBTransaction) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\n\nexport function adjustToExistingIndexNames(db: Dexie, schema: DbSchema, idbtrans: IDBTransaction) {\n // Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n const storeNames = idbtrans.db.objectStoreNames;\n\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n db._hasGetAll = false;\n }\n}\n\nexport function parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n return createIndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n indexNum === 0\n );\n });\n}\n","import { Version as IVersion } from '../../public/types/version';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { extend, keys } from '../../functions/utils';\nimport { Dexie } from '../dexie';\nimport { Transaction } from '../transaction';\nimport { removeTablesApi, setApiOnPlace, parseIndexSyntax } from './schema-helpers';\nimport { exceptions } from '../../errors';\nimport { createTableSchema } from '../../helpers/table-schema';\n\n/** class Version\n * \n * http://dexie.org/docs/Version/Version\n */\nexport class Version implements IVersion {\n db: Dexie;\n _cfg: {\n version: number,\n storesSource: { [tableName: string]: string | null },\n dbschema: DbSchema,\n tables: {},\n contentUpgrade: Function | null\n }\n\n _parseStoresSpec(stores: { [tableName: string]: string | null }, outSchema: DbSchema): any {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\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 indexes.forEach(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 });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n\n stores(stores: { [key: string]: string; }): IVersion {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n const storesSpec: { [key: string]: string; } = {};\n let dbschema = {};\n versions.forEach(version => { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n // Update the latest schema to this version\n db._dbSchema = dbschema;\n // Update APIs\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n\n upgrade(upgradeFunction: (trans: Transaction) => PromiseLike | void): Version {\n this._cfg.contentUpgrade = upgradeFunction;\n return this;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Version } from './version';\n\nexport interface VersionConstructor {\n new(versionNumber: number): Version;\n prototype: Version;\n}\n\n/** Generates a Version constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createVersionConstructor(db: Dexie) {\n return makeClassConstructor(\n Version.prototype,\n\n function Version(this: Version, versionNumber: number) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n\n}\n","import Promise from './promise';\nimport { Dexie } from '../classes/dexie/dexie';\nimport { Table } from '../public/types/table';\nimport { nop } from '../functions/chaining-functions';\nimport { PromiseExtended } from '../public/types/promise-extended';\nimport { DBNAMES_DB } from '../globals/constants';\n\nexport let databaseEnumerator: DatabaseEnumerator;\n\nexport interface DatabaseEnumerator {\n getDatabaseNames (): PromiseExtended;\n add (name: string): undefined | PromiseExtended;\n remove (name: string): undefined | PromiseExtended;\n}\n\nexport function DatabaseEnumerator (indexedDB: IDBFactory & {databases?: ()=>Promise<{name: string}[]>}) : DatabaseEnumerator {\n const hasDatabasesNative = indexedDB && typeof indexedDB.databases === 'function';\n let dbNamesTable: Table<{name: string}, string>;\n\n if (!hasDatabasesNative) {\n const db = new Dexie (DBNAMES_DB, {addons: []});\n db.version(1).stores({dbnames: 'name'});\n dbNamesTable = db.table<{name: string}, string>('dbnames');\n }\n\n return {\n getDatabaseNames () {\n return hasDatabasesNative\n ?\n // Use Promise.resolve() to wrap the native promise into a Dexie promise,\n // to keep PSD zone.\n Promise.resolve(indexedDB.databases()).then(infos => infos\n // Select name prop of infos:\n .map(info => info.name)\n // Filter out DBNAMES_DB as previous Dexie or browser version would not have included it in the result.\n .filter(name => name !== DBNAMES_DB)\n )\n :\n // Use dexie's manually maintained list of database names:\n dbNamesTable.toCollection().primaryKeys();\n },\n\n add (name: string) : PromiseExtended | undefined {\n return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.put({name}).catch(nop);\n },\n\n remove (name: string) : PromiseExtended | undefined {\n return !hasDatabasesNative && name !== DBNAMES_DB && dbNamesTable.delete(name).catch(nop);\n }\n };\n}\n\nexport function initDatabaseEnumerator(indexedDB: IDBFactory) {\n try {\n databaseEnumerator = DatabaseEnumerator(indexedDB);\n } catch (e) {}\n}\n\n","import { newScope } from '../../helpers/promise';\nimport { PSD } from '../../helpers/promise';\n\nexport function vip (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","import { Dexie } from './dexie';\nimport * as Debug from '../../helpers/debug';\nimport { rejection } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { eventRejectHandler, preventDefault } from '../../functions/event-wrappers';\nimport Promise, { wrap } from '../../helpers/promise';\nimport { connections } from '../../globals/constants';\nimport { runUpgraders, readGlobalSchema, adjustToExistingIndexNames } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { databaseEnumerator } from '../../helpers/database-enumerator';\nimport { vip } from './vip';\nimport { promisableChain, nop } from '../../functions/chaining-functions';\nimport { generateMiddlewareStacks } from './generate-middleware-stacks';\nimport { slice } from '../../functions/utils';\n\nexport function dexieOpen (db: Dexie) {\n const state = db._state;\n const {indexedDB} = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection (state.dbOpenError) :\n db);\n Debug.debug && (state.openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n \n // Function pointers to call when the core opening process completes.\n let resolveDbReady = state.dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction: (IDBTransaction | null) = null;\n \n return Promise.race([state.openCanceller, new Promise((resolve, reject) => {\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(\n \"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \"+\n \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\n const dbName = db.name;\n \n const req = state.autoSchema ?\n indexedDB.open(dbName) :\n 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 = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap (e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) { // 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 const 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(() => {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n db.idbdb = req.result;\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n \n req.onsuccess = wrap (() => {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n const idbdb = db.idbdb = req.result;\n\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0) try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema) readGlobalSchema(db, idbdb, tmpTrans);\n else adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n generateMiddlewareStacks(db, tmpTrans);\n } catch (e) {\n // Safari 8 may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n // BUGBUG: It will bail out anyway as of Dexie 3.\n // Should we support Safari 8 anymore? Believe all\n // Dexie users use the shim for that platform anyway?!\n // If removing Safari 8 support, go ahead and remove the safariMultiStoreFix() function\n // as well as absurd upgrade version quirk for Safari.\n }\n \n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n \n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n databaseEnumerator.add(dbName);\n\n resolve();\n\n }, reject);\n })]).then(() => {\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 state.onReadyBeingFired = [];\n return Promise.resolve(vip(db.on.ready.fire)).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(remainders)).then(fireRemainders)\n }\n });\n }).finally(()=>{\n state.onReadyBeingFired = null;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n state.isBeingOpened = false;\n return db;\n }).catch(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 state.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 state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n return rejection (state.dbOpenError);\n }).finally(()=>{\n state.openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n });\n}\n","import { isArray } from '../functions/utils';\n\nexport function awaitIterator (iterator: Iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext: (any)=>any) {\n return (val?) => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n","import { TransactionMode } from '../../public/types/transaction-mode';\nimport { exceptions } from '../../errors';\nimport { flatten, isAsyncFunction } from '../../functions/utils';\nimport { Dexie } from './dexie';\nimport { Transaction } from '../transaction';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise, {\n PSD,\n NativePromise,\n decrementExpectedAwaits,\n rejection,\n incrementExpectedAwaits\n} from '../../helpers/promise';\n\nexport function extractTransactionArgs(mode: TransactionMode, _tableArgs_, scopeFunc) {\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) 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 return [mode, tables, scopeFunc];\n}\n\nexport function enterTransactionScope(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n parentTransaction: Transaction | undefined,\n scopeFunc: ()=>PromiseLike | any\n) {\n return Promise.resolve().then(() => {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n const transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n const zoneProps = {\n trans: trans,\n transless: transless\n };\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 // Support for native async await.\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n // scopeFunc is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else 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 }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(() => returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(() => x);\n }).catch(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","import {\n DBCore,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryRequest,\n DBCoreRangeType,\n DBCoreOpenCursorRequest,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreTable,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getKeyPathAlias } from './dbcore-indexeddb';\nimport { Middleware } from '../public/types/middleware';\n\ninterface VirtualIndex extends DBCoreIndex {\n /** True if this index is virtual, i.e. represents a compound index internally,\n * but makes it act as as having a subset of its keyPaths.\n */\n isVirtual: boolean;\n\n /** Number of keypaths that this index comprises. Can be 0..N.\n * Note: This is the length of the *virtual index*, not the real index.\n */\n keyLength: number;\n\n /** Number of popped keypaths from the real index.\n */\n keyTail: number;\n}\n\n// Move into some util:\nexport function pad (a: any | any[], value: any, count: number) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i=0; i 0;\n const virtualIndex = {\n ...lowLevelIndex,\n isVirtual,\n isPrimaryKey: !isVirtual && lowLevelIndex.isPrimaryKey,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] : // This is a compound [a, b]. Add a virtual normal index a.\n keyPath.slice(0, keyLength - 1); // This is compound [a,b,c]. Add virtual compound [a,b].\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a,b) => a.keyTail - b.keyTail); // Shortest keyTail is the best one (represents real index)\n return virtualIndex;\n }\n \n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n \n function findBestIndex(keyPath: null | string | string[]): VirtualIndex {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n \n function translateRange (range: DBCoreKeyRange, keyTail: number): DBCoreKeyRange {\n return {\n type: range.type === DBCoreRangeType.Equal ?\n DBCoreRangeType.Range :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true, // doesn't matter true or false\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true // doesn't matter true or false\n };\n }\n \n function translateRequest (req: DBCoreQueryRequest): DBCoreQueryRequest;\n function translateRequest (req: DBCoreOpenCursorRequest): DBCoreOpenCursorRequest;\n function translateRequest (req: DBCoreCountRequest): DBCoreCountRequest {\n const index = req.query.index as VirtualIndex;\n return index.isVirtual ? {\n ...req,\n query: {\n index,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n \n const result: DBCoreTable = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n\n count(req) {\n return table.count(translateRequest(req));\n }, \n \n query(req) {\n return table.query(translateRequest(req));\n },\n \n openCursor(req) {\n const {keyTail, isVirtual, keyLength} = (req.query.index as VirtualIndex);\n if (!isVirtual) return table.openCursor(req);\n \n function createVirtualCursor(cursor: DBCoreCursor) : DBCoreCursor {\n function _continue (key?: any) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(pad(cursor.key, req.reverse ? down.MIN_KEY : down.MAX_KEY, keyTail)) :\n cursor.continue()\n }\n const virtualCursor = Object.create(cursor, {\n continue: {value: _continue},\n continuePrimaryKey: {\n value(key: any, primaryKey: any) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n key: {\n get() {\n const key = cursor.key as any[]; // A virtual cursor always operates on compound key\n return keyLength === 1 ?\n key[0] : // Cursor.key should not be an array.\n key.slice(0, keyLength); // Cursor.key should be first part of array.\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n \n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n }\n}\n\nexport const virtualIndexMiddleware : Middleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\n","import {\n DBCore,\n DBCoreTable,\n DBCoreMutateResponse,\n DBCoreDeleteRangeRequest,\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreTransaction,\n DBCoreKeyRange,\n} from \"../public/types/dbcore\";\nimport { nop } from '../functions/chaining-functions';\nimport { getObjectDiff, setByKeyPath } from '../functions/utils';\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys, getExistingValues } from '../dbcore/get-effective-keys';\nimport { Middleware } from '../public/types/middleware';\nimport { Transaction } from '../classes/transaction';\n\nexport const hooksMiddleware: Middleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore: DBCore) => ({\n ...downCore,\n table(tableName: string) {\n const downTable = downCore.table(tableName);\n const {primaryKey} = downTable.schema;\n \n const tableMiddleware: DBCoreTable = {\n ...downTable,\n mutate(req):Promise {\n const dxTrans = PSD.trans as Transaction;\n // Hooks can be transaction-bound. Need to grab them from transaction.table and not\n // db.table!\n const {deleting, creating, updating} = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>deleteRange(req), true);\n }\n // Any of the breaks above happened (no hooks) - do the default:\n return downTable.mutate(req);\n\n\n function addPutOrDelete(req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest): Promise {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys) throw new Error(\"Keys missing\");\n // Clone Request and set keys arg\n req = req.type === 'add' || req.type === 'put' ?\n {...req, keys, wantResults: true} : // Tell lower layer to deliver results. Hooks onsuccess needs it.\n {...req};\n if (req.type !== 'delete') req.values = [...req.values];\n if (req.keys) req.keys = [...req.keys];\n \n return getExistingValues(downTable, req, keys).then (existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n // delete operation\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n } else if (req.type === 'add' || existingValue === undefined) {\n // The add() or put() resulted in a create\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n } else {\n // The put() operation resulted in an update\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({failures, results, numFailures, lastResult}) => {\n for (let i=0; i {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n \n function deleteRange(req: DBCoreDeleteRangeRequest): Promise {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n \n function deleteNextChunk(trans: DBCoreTransaction, range: DBCoreKeyRange, limit: number) {\n // Query what keys in the DB within the given range\n return downTable.query({trans, values: false, query: {index: primaryKey, range}, limit})\n .then(({result}) => {\n // Given a set of keys, bulk delete those using the same procedure as in addPutOrDelete().\n // This will make sure that deleting hook is called.\n return addPutOrDelete({type: 'delete', keys: result, trans}).then(res => {\n if (res.numFailures > 0) return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return {failures: [], numFailures: 0, lastResult: undefined} as DBCoreMutateResponse;\n } else {\n return deleteNextChunk(trans, {...range, lower: result[result.length - 1], lowerOpen: true}, limit);\n }\n });\n })\n }\n }\n };\n //const {lock, lockableMiddleware} = LockableTableMiddleware(tableMiddleware);\n\n return tableMiddleware;\n },\n }) as DBCore\n};\n","// Import types from the public API\nimport { Dexie as IDexie } from \"../../public/types/dexie\";\nimport { DexieOptions, DexieConstructor } from \"../../public/types/dexie-constructor\";\nimport { DbEvents } from \"../../public/types/db-events\";\n//import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from \"../../public/types/table-schema\";\nimport { DbSchema } from '../../public/types/db-schema';\n\n// Internal imports\nimport { Table, TableConstructor, createTableConstructor } from \"../table\";\nimport { Collection, CollectionConstructor, createCollectionConstructor } from '../collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { WhereClauseConstructor, createWhereClauseConstructor } from '../where-clause/where-clause-constructor';\nimport { Transaction } from '../transaction';\nimport { TransactionConstructor, createTransactionConstructor } from '../transaction/transaction-constructor';\nimport { Version } from \"../version/version\";\nimport { VersionConstructor, createVersionConstructor } from '../version/version-constructor';\n\n// Other imports...\nimport { DexieEventSet } from '../../public/types/dexie-event-set';\nimport { DexieExceptionClasses } from '../../public/types/errors';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport Promise, { PSD } from '../../helpers/promise';\nimport { extend, override, keys, hasOwn } from '../../functions/utils';\nimport Events from '../../helpers/Events';\nimport { maxString, connections, READONLY, READWRITE } from '../../globals/constants';\nimport { getMaxKey } from '../../functions/quirks';\nimport { exceptions } from '../../errors';\nimport { lowerVersionFirst } from '../version/schema-helpers';\nimport { dexieOpen } from './dexie-open';\nimport { wrap } from '../../helpers/promise';\nimport { databaseEnumerator } from '../../helpers/database-enumerator';\nimport { eventRejectHandler } from '../../functions/event-wrappers';\nimport { extractTransactionArgs, enterTransactionScope } from './transaction-helpers';\nimport { TransactionMode } from '../../public/types/transaction-mode';\nimport { rejection } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { DBCore } from '../../public/types/dbcore';\nimport { Middleware, DexieStacks } from '../../public/types/middleware';\nimport { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware';\nimport { hooksMiddleware } from '../../hooks/hooks-middleware';\nimport { IndexableType } from '../../public';\n\nexport interface DbReadyState {\n dbOpenError: any;\n isBeingOpened: boolean;\n onReadyBeingFired: undefined | Function[];\n openComplete: boolean;\n dbReadyResolve: () => void;\n dbReadyPromise: Promise;\n cancelOpen: (reason?: Error) => void;\n openCanceller: Promise & { _stackHolder?: Error };\n autoSchema: boolean;\n vcFired?: boolean;\n}\n\nexport class Dexie implements IDexie {\n _options: DexieOptions;\n _state: DbReadyState;\n _versions: Version[];\n _storeNames: string[];\n _deps: DexieDOMDependencies;\n _allTables: { [name: string]: Table; };\n _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike, dbschema: { [tableName: string]: TableSchema; }, parentTransaction?: Transaction) => Transaction;\n _dbSchema: { [tableName: string]: TableSchema; };\n _hasGetAll?: boolean;\n _maxKey: IndexableType;\n _fireOnBlocked: (ev: Event) => void;\n _middlewares: {[StackName in keyof DexieStacks]?: Middleware[]} = {};\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n on: DbEvents;\n\n Table: TableConstructor;\n WhereClause: WhereClauseConstructor;\n Collection: CollectionConstructor;\n Version: VersionConstructor;\n Transaction: TransactionConstructor;\n\n constructor(name: string, options?: DexieOptions) {\n const deps = (Dexie as any as DexieConstructor).dependencies;\n this._options = options = {\n // Default Options\n addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n // Default DOM dependency implementations from static prop.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env.\n ...options\n };\n this._deps = {\n indexedDB: options.indexedDB as IDBFactory,\n IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange\n };\n const {\n addons,\n } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n const state: DbReadyState = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null as Promise,\n cancelOpen: nop,\n openCanceller: null as Promise,\n autoSchema: true\n };\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", { ready: [promisableChain, nop] }) as DbEvents;\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n (Dexie as any as DexieConstructor).vip(() => {\n const state = this._state;\n if (state.openComplete) {\n // Database already open. Call subscriber asap.\n if (!state.dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (state.onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n state.onReadyBeingFired.push(subscriber);\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 const db = this;\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 // Create derived classes bound to this instance of Dexie:\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n\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 this.on(\"versionchange\", 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)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.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 this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n\n this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange);\n\n this._createTransaction = (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parentTransaction?: Transaction) => new this.Transaction(mode, storeNames, dbschema, parentTransaction);\n\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n // Default middlewares:\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n\n // Call each addon:\n addons.forEach(addon => addon(this));\n }\n\n version(versionNumber: number): Version {\n if (isNaN(versionNumber) || versionNumber < 0.1) throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(\n v => v._cfg.version === versionNumber)[0];\n if (versionInstance) return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({}); // Derive earlier schemas by default.\n // Disable autoschema mode, as at least one version is specified.\n this._state.autoSchema = false;\n return versionInstance;\n }\n\n _whenReady(fn: () => Promise): Promise {\n return this._state.openComplete || PSD.letThrough ? fn() : new Promise((resolve, reject) => {\n if (!this._state.isBeingOpened) {\n if (!this._options.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n\n use({stack, create, level, name}: Middleware): this {\n if (name) this.unuse({stack, name}); // Be able to replace existing middleware.\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({stack, create, level: level == null ? 10 : level, name});\n middlewares.sort((a, b) => a.level - b.level);\n // Todo update db.core and db.tables...core ? Or should be expect this to have effect\n // only after next open()?\n return this;\n }\n\n unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this;\n unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this;\n unuse({stack, name, create}: {stack: keyof DexieStacks, name?: string, create?: Function}) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw =>\n create ? mw.create !== create : // Given middleware has a create method. Match that exactly.\n name ? mw.name !== name : // Given middleware spec \n false);\n }\n return this;\n }\n\n open() {\n return dexieOpen(this);\n }\n\n close(): void {\n const idx = connections.indexOf(this),\n state = this._state;\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this.idbdb = null;\n }\n this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\n\n // Reset dbReadyPromise promise:\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n\n delete(): Promise {\n const hasArguments = arguments.length > 0;\n const state = this._state;\n return new Promise((resolve, reject) => {\n const doDelete = () => {\n this.close();\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n databaseEnumerator.remove(this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n }\n\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n });\n }\n\n backendDB() {\n return this.idbdb;\n }\n\n isOpen() {\n return this.idbdb !== null;\n }\n\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n\n get tables () {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n\n transaction(): Promise {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n\n _transaction(mode: TransactionMode, tables: Array, scopeFunc: Function) {\n let parentTransaction = PSD.trans as Transaction | undefined;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n let idbMode: IDBTransactionMode,\n storeNames;\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n storeNames = tables.map(table => {\n var storeName = table instanceof this.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)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\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(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>this._whenReady(enterTransaction)) :\n this._whenReady (enterTransaction));\n }\n\n table(tableName: string): Table;\n table(tableName: string): ITable;\n table(tableName: string): Table {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return this._allTables[tableName];\n }\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, getObjectDiff, asap, _global } from '../../functions/utils';\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { DatabaseEnumerator, databaseEnumerator } from '../../helpers/database-enumerator';\nimport { PSD } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { newScope } from '../../helpers/promise';\nimport { rejection } from '../../helpers/promise';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { dexieStackFrameFilter, minKey, connections, DEXIE_VERSION } from '../../globals/constants';\nimport Events from '../../helpers/Events';\nimport { exceptions } from '../../errors';\nimport { errnames } from '../../errors';\nimport { getMaxKey } from '../../functions/quirks';\nimport { vip } from './vip';\n\n/* (Dexie) is an instance of DexieConstructor, as defined in public/types/dexie-constructor.d.ts\n* (new Dexie()) is an instance of Dexie, as defined in public/types/dexie.d.ts\n* \n* Why we're doing this?\n\n* Because we've choosen to define the public Dexie API using a DexieConstructor interface\n* rather than declaring a class. On that interface, all static props are defined.\n* In practice, class Dexie's constructor implements DexieConstructor and all member props\n* are defined in interface Dexie. We could say, it's a typescript limitation of not being\n* able to define a static interface that forces us to do the cast below.\n*/\nconst Dexie = _Dexie as any as DexieConstructor;\n\n//\n// Set all static methods and properties onto Dexie:\n// \nprops(Dexie, {\n\n // Dexie.BulkError = class BulkError {...};\n // Dexie.XXXError = class XXXError {...};\n ...fullNameExceptions,\n\n //\n // Static delete() method.\n //\n delete(databaseName: string) {\n const db = new Dexie(databaseName);\n return db.delete();\n },\n\n //\n // Static exists() method.\n //\n exists(name: string) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames(cb) {\n return databaseEnumerator ?\n databaseEnumerator.getDatabaseNames().then(cb) :\n Promise.resolve([]);\n },\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n\n ignoreTransaction(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 ?\n 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,\n\n async: function (generatorFn: Function) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n 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')\n 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: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n const promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\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: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive, // Deprecate?\n extend: extend, // Deprecate?\n props: props,\n override: override, // Deprecate?\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\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: new Dexie('',{addons:[]})._maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n //MultiModifyError: exceptions.Modify, // Obsolete!\n errnames: errnames,\n\n // Export other static classes\n //IndexSpec: IndexSpec, Obsolete!\n //TableSchema: TableSchema, Obsolete!\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 try {\n return {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n } catch (e) {\n return {indexedDB: null, IDBKeyRange: null};\n }\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('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\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 // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n Dexie: Dexie\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { Dexie } from './classes/dexie';\nimport { DexieConstructor } from './public/types/dexie-constructor';\nimport { DexiePromise } from './helpers/promise';\nimport { mapError } from './errors';\nimport * as Debug from './helpers/debug';\nimport { dexieStackFrameFilter } from './globals/constants';\nimport { initDatabaseEnumerator } from './helpers/database-enumerator';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\n\n// Init Database Enumerator (for Dexie.getDatabaseNames())\ninitDatabaseEnumerator((Dexie as any as DexieConstructor).dependencies.indexedDB);\n\n// Set rejectionMapper of DexiePromise so that it generally tries to map\n// DOMErrors and DOMExceptions to a DexieError instance with same name but with\n// async stack support and with a prototypal inheritance from DexieError and Error.\n// of Map DOMErrors and DOMExceptions to corresponding Dexie errors.\nDexiePromise.rejectionMapper = mapError;\n\n// Let the async stack filter focus on app code and filter away frames from dexie.min.js:\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport default Dexie;\n"],"names":["asap","props","Promise","keys","Table","Collection","WhereClause","Transaction","Version","Debug.debug","Debug.getErrorWithStack","Dexie","_Dexie","Debug.setDebug"],"mappings":";;;;;;;;;;;;;AA6BO,IAAI,QAAQ,GAAG,WAAW;IAC7B,QAAQ,GAAG,MAAM,CAAC,MAAM,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE;QAC7C,KAAK,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YACjD,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;YACjB,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;SAChF;QACD,OAAO,CAAC,CAAC;MACZ;IACD,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;EAC1C;AAED,AAUC;AAED,AAKC;AAED,AAEC;AAED,AAEC;AAED,AAQC;AAED,AA0BC;AAED,AAEC;AAED,AAUC;AAED,AAeC;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SAAS,CAAC,CAAC;AAMlF,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCE,QAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC,CAAC;;;;"} \ No newline at end of file diff --git a/test/bundle.js b/test/bundle.js new file mode 100644 index 000000000..16f0e27a6 --- /dev/null +++ b/test/bundle.js @@ -0,0 +1,10135 @@ +(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 = Dexie && Dexie.hasOwnProperty('default') ? Dexie['default'] : Dexie; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + + + + + + + + + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +// Custom QUnit config options. +QUnit.config.urlConfig.push(/*{ + id: "polyfillIE", // Remarked because has no effect anymore. Find out why. + label: "Include IE Polyfill", + tooltip: "Enabling this will include the idb-iegap polyfill that makes" + + " IE10&IE11 support multiEntry and compound indexes as well as compound" + + " primary keys" +}, { + id: "indexedDBShim", // Remarked because has no effect anymore. Need to find out why. Should invoke the shim if set! + label: "IndexedDBShim (UseWebSQL as backend)", + tooltip: "Enable this in Safari browsers without indexedDB support or" + + " with poor indexedDB support" +},*/ { + id: "dontoptimize", + label: "Dont optimize tests", + tooltip: "Always delete and recreate the DB between each test" +}, { + id: "longstacks", + label: "Long async stacks", + tooltip: "Set Dexie.debug=true, turning on long async stacks on all" + + " errors (Actually we use Dexie.debug='dexie' so that frames from" + + " dexie.js are also included)" +}); +Dexie.debug = window.location.search.indexOf('longstacks') !== -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') !== -1; +var ArrayBuffer$1 = window.ArrayBuffer; +function stringify(idbKey) { + var res = '' + (idbKey && idbKey.constructor && idbKey.constructor === ArrayBuffer$1 ? + new Uint8Array(idbKey) : idbKey); + return res; +} +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[stringify(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[stringify(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]; + var keysToDelete = Object.keys(items) + .filter(function (key) { return !initialItems[key]; }) + .map(function (key) { return items[key].key; }); + if (keysToDelete.length > 0) { + return db.table(tableName).bulkDelete(keysToDelete); + } + }); + })); + }); +} + +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 && Array.isArray(Dexie.maxKey); + case "multientry": + return result && (hasPolyfillIE || (!isIE && !isEdge)); // Should add Safari to + case "deleteobjectstoreafterread": + return result && (!isIE && !isEdge); + case "versionchange": + return result; + //return result && (!isIE && !isEdge); // Should add Safari to + case "binarykeys": + try { + return result && Array.isArray(Dexie.maxKey) && indexedDB.cmp(new Uint8Array([1]), new Uint8Array([1])) === 0; + } + catch (e) { + return false; + } + case "domevents": + return typeof window === 'object' && window.addEventListener; + default: + throw new Error("Unknown feature: " + feature); + } + }, true); +} +function spawnedTest(name, num, promiseGenerator) { + if (!promiseGenerator) { + promiseGenerator = num; + QUnit.test(name, function (assert) { + var done = assert.async(); + Dexie.spawn(promiseGenerator) + .catch(function (e) { return QUnit.ok(false, e.stack || e); }) + .then(done); + }); + } + else { + QUnit.test(name, num, function (assert) { + var done = assert.async(); + Dexie.spawn(promiseGenerator) + .catch(function (e) { return QUnit.ok(false, e.stack || e); }) + .then(done); + }); + } +} +function promisedTest(name, num, asyncFunction) { + if (!asyncFunction) { + asyncFunction = num; + QUnit.test(name, function (assert) { + var done = assert.async(); + Promise.resolve().then(asyncFunction) + .catch(function (e) { return QUnit.ok(false, e.stack || e); }) + .then(done); + }); + } + else { + QUnit.test(name, num, function (assert) { + var done = assert.async(); + Promise.resolve().then(asyncFunction) + .catch(function (e) { return QUnit.ok(false, e.stack || e); }) + .then(done); + }); + } +} + +var db = new Dexie("TestDBTable"); +db.version(1).stores({ + users: "++id,first,last,&username,*&email,*pets", + folks: "++,first,last", + schema: "" // Test issue #1039 +}); +var User = db.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String], +}); +var idOfFirstUser = 0; +var idOfLastUser = 0; +db.on("populate", function (trans) { + db.users.add({ first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }).then(function (id) { + idOfFirstUser = id; + }); + db.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).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +promisedTest("Issue #841 - put() ignores date changes", function () { return __awaiter(void 0, void 0, void 0, function () { + var date1, date2, first1, first2, id, obj; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db.folks.hook("updating", function (mods) { + QUnit.equal(mods.first, first2, "first value should be " + first2 + " but is " + mods.first); + QUnit.equal(!!mods.date, true, "date should be included in modifications"); + if (mods.date) { + QUnit.equal(mods.date.getTime(), date2.getTime(), "date should be " + date2 + " but is " + mods.date); + } + }); + date1 = new Date("2019-05-03"); + date2 = new Date("2020-01-01"); + first1 = "Foo1"; + first2 = "Foo2"; + QUnit.ok(date1.getTime() !== date2.getTime(), "Just verifying input data so that date1 !== date2"); + QUnit.ok(first1 != first2, "first1 different first2"); + return [4 /*yield*/, db.folks.add({ first: first1, last: "Bar", date: date1 })]; + case 1: + id = _a.sent(); + return [4 /*yield*/, db.folks.get(id)]; + case 2: + obj = _a.sent(); + QUnit.equal(obj.date.getTime(), date1.getTime(), "Date should first equal date1"); + QUnit.equal(obj.first, first1, "first should be '" + first1 + "'"); + obj.first = first2; + obj.date = date2; + return [4 /*yield*/, db.folks.put(obj, id)]; + case 3: + _a.sent(); + return [4 /*yield*/, db.folks.get(id)]; + case 4: + obj = _a.sent(); + QUnit.equal(obj.first, first2, "first should have been successfully updated to '" + first2 + "'"); + QUnit.equal(obj.date.getTime(), date2.getTime(), "Date should have been successfully updated to be date2"); + return [2 /*return*/]; + } + }); +}); }); +QUnit.asyncTest("get", 4, function () { + db.table("users").get(idOfFirstUser).then(function (obj) { + QUnit.equal(obj.first, "David", "Got the first object"); + return db.users.get(idOfLastUser); + }).then(function (obj) { + QUnit.equal(obj.first, "Karl", "Got the second object"); + return db.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.transaction("r", db.users, function () { + db.users.where("username").equals("kceder").first(function (user) { + QUnit.equal(user.first, "Karl", "where().equals()"); + }), db.users.where("id").above(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 1, "where().above()"); + }), db.users.where("id").aboveOrEqual(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 2, "where().aboveOrEqual()"); + }), db.users.where("id").below(idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().below().count()"); + }), db.users.where("id").below(idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().below().count() should be zero"); + }), db.users.where("id").belowOrEqual(idOfFirstUser).count(function (count) { + QUnit.ok(count == 1, "where().belowOrEqual()"); + }), db.users.where("id").between(idOfFirstUser, idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 1)"); + }), db.users.where("id").between(0, Infinity).count(function (count) { + QUnit.ok(count == 2, "where().between(0, Infinity)"); + }), db.users.where("id").between(idOfFirstUser, idOfFirstUser, true, true).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 1, true, true)"); + }), db.users.where("id").between(1, -1, true, true).count(function (count) { + QUnit.ok(count == 0, "where().between(1, -1, true, true)"); + }), db.users.where("id").between(idOfFirstUser, idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 2)"); + }), db.users.where("id").between(idOfFirstUser, idOfLastUser, true, true).count(function (count) { + QUnit.ok(count == 2, "where().between(1, 2, true, true)"); + }), db.users.where("id").between(idOfFirstUser, idOfLastUser, false, false).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 2, false, false)"); + }); + db.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.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.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.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.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.users.where("last").anyOf("Faadersköld").toArray(function (a) { + QUnit.equal(a.length, 1, "in() returned expected number of items"); + }); + if (supports("multiEntry")) { + db.users.where("email").equals("david@awarica.com").toArray(function (a) { + QUnit.equal(a.length, 1, "Finding items from array members. Expect to fail on IE10/IE11."); + }); + db.users.where("email").startsWith("da").distinct().toArray(function (a) { + 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.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.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.transaction("rw", db.users, function () { + // Modify first found user with a helloMessage + db.users.orderBy("first").reverse().limit(1).modify(function (user) { + user.helloMessage = "Hello " + user.first; + }); + // Check that the modification went fine: + db.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.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.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.transaction("rw", db.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db.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.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.users.put(user).then(function (id) { + QUnit.equal(id, currentId, "Still got same id because we update same object"); + }); + db.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.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.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.users.put(user).then(function (id) { + QUnit.equal(id, userId, "Still got same id because we update same object"); + return db.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.transaction("rw", db.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db.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.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", function () { + var highestKey, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.users.add({ username: "fsdkljfd", email: ["fjkljslk"] })]; + case 1: + highestKey = _a.sent(); + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + return [4 /*yield*/, db.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db.users.bulkAdd([ + { first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, + { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] } + ])]; + case 3: + result = _a.sent(); + QUnit.equal(result, highestKey + 2, "Result of bulkAdd() operation was equal to highestKey + 2"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkAdd-all-results", function () { + var dbBulkAddAll, highestKey, allKeys, expectedKeys, allKeys2, expectedKeys2, allKeys3, lastKey, lastKey, lastKey; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + dbBulkAddAll = new Dexie("TestDBTableBulkAddAllResults"); + dbBulkAddAll.version(1).stores({ + dudes: "++,first,last" + }); + return [4 /*yield*/, dbBulkAddAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 1: + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1", find: "bulkAddAll" }, + { first: "Åke2", last: "Persbrant2", find: "bulkAddAll" } + ], { allKeys: true })]; + case 2: + allKeys = _a.sent(); + expectedKeys = [highestKey + 1, highestKey + 2]; + deepEqual(allKeys, expectedKeys, "Result of bulkAdd(objects, { allKeys: true }) operation was equal to [highestKey + 1, highestKey + 2]"); + return [4 /*yield*/, dbBulkAddAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 3: + // should be able to get all keys with options object as third argument + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1", find: "bulkAddAll" }, + { first: "Åke2", last: "Persbrant2", find: "bulkAddAll" } + ], undefined, { allKeys: true })]; + case 4: + allKeys2 = _a.sent(); + expectedKeys2 = [highestKey + 1, highestKey + 2]; + deepEqual(allKeys2, expectedKeys2, "Result of bulkAdd(objects, undefined, { allKeys: true }) operation was equal to [highestKey + 1, highestKey + 2]"); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['sd5fs2df', 'dasfsd3fs7df'], { allKeys: true })]; + case 5: + allKeys3 = _a.sent(); + deepEqual(allKeys3, ['sd5fs2df', 'dasfsd3fs7df'], "Result of bulkAdd(objects, ['sd5fs2df', 'dasfsd3fs7df'], { allKeys: true }) operation was equal to ['sd5fs2df', 'dasfsd3fs7df']"); + return [4 /*yield*/, dbBulkAddAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 6: + // should return last key with 1 argument and options: { allKeys: false } + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], { allKeys: false })]; + case 7: + lastKey = _a.sent(); + QUnit.equal(lastKey, highestKey + 2, "Result of bulkAdd(objects, { allKeys: false }) operation was equal to highestKey + 2"); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false })]; + case 8: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'b33vn3fytn', "Result of bulkAdd(objects, ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false }) operation was equal to 'b33vn3fytn'"); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['dfgd2vdfh4d', 'ty1jxdbd9'])]; + case 9: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'ty1jxdbd9', "Result of bulkAdd(objects, ['dfgd2vdfh4d', 'ty1jxdbd9']) operation was equal to 'ty1jxdbd9'"); + return [4 /*yield*/, dbBulkAddAll.delete()]; + case 10: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkAdd-catching errors", function () { + var _a, newUsersX, e_1, _b, _c, newUsersY, e_2, _d, newUsersZ, _e; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: return [4 /*yield*/, db.transaction("rw", db.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"] }, + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] } + ]; + db.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.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-added"); + }); + })]; + case 1: + _f.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where("username").startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_f.sent(), 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"] }, + { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] } + ]; + _f.label = 3; + case 3: + _f.trys.push([3, 5, , 6]); + return [4 /*yield*/, db.transaction("rw", db.users, function () { + db.users.bulkAdd(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + })]; + case 4: + _f.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 6]; + case 5: + e_1 = _f.sent(); + QUnit.ok(true, "Got: " + e_1); + return [3 /*break*/, 6]; + case 6: + _b = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 7: + _b.apply(void 0, [_f.sent(), 0, "0 users! Good, means that previous transaction did not commit"]); + return [4 /*yield*/, db.users.bulkAdd(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + })]; + case 8: + _f.sent(); + _c = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 9: + _c.apply(void 0, [_f.sent(), 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"] }, + { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] } + ]; + _f.label = 10; + case 10: + _f.trys.push([10, 12, , 13]); + return [4 /*yield*/, db.users.bulkAdd(newUsersY)]; + case 11: + _f.sent(); + return [3 /*break*/, 13]; + case 12: + e_2 = _f.sent(); + QUnit.ok(true, "Got: " + e_2); + return [3 /*break*/, 13]; + case 13: + _d = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('yper').count()]; + case 14: + _d.apply(void 0, [_f.sent(), 3, "3 users! Good - means that previous operation catched (via try..yield..catch this time, and therefore committed"]); + 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"] }, + { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] } + ]; + return [4 /*yield*/, db.transaction('rw', db.users, function () { + var e_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, db.users.bulkAdd(newUsersZ)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + e_3 = _a.sent(); + throw e_3; + case 3: return [2 /*return*/]; + } + }); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('zper').count()]; + case 16: + _e.apply(void 0, [_f.sent(), 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"]); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkAdd-non-inbound-autoincrement", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, db.folks.bulkAdd([ + { first: "Foo", last: "Bar" }, + { first: "Foo", last: "Bar2" }, + { first: "Foo", last: "Bar3" }, + { first: "Foo", last: "Bar4" } + ])]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.folks.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_c.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db.folks.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_c.sent(), 1, "Shoudl be 1 Bar"]); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkAdd-catch sub transaction", function () { + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, db.transaction('rw', db.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"] }, + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] } + ]; + db.transaction('rw', db.users, function () { + db.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 1: + _b.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_b.sent(), 0, "0 users! Good, means that inner transaction did not commit"]); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkPut", function () { + var highestKey, existingFirstUserToReplace, result, ourAddedUsers, replacedDfahlander; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.users.add({ username: "fsdkljfd", email: ["fjkljslk"] })]; + case 1: + highestKey = _a.sent(); + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + return [4 /*yield*/, db.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db.users.get(idOfFirstUser)]; + case 3: + existingFirstUserToReplace = _a.sent(); + QUnit.equal(existingFirstUserToReplace.username, "dfahlander", "Existing user should be dfahlander"); + return [4 /*yield*/, db.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 4: + result = _a.sent(); + QUnit.equal(result, highestKey + 2, "Result of bulkPut() operation was equal to highestKey + 2"); + return [4 /*yield*/, db.users.where('username').startsWith("aper").toArray()]; + case 5: + ourAddedUsers = _a.sent(); + QUnit.equal(ourAddedUsers.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, db.users.get(idOfFirstUser)]; + case 6: + replacedDfahlander = _a.sent(); + QUnit.equal(replacedDfahlander.username, "aper2", "dfahlander Should now be aper2 instead"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkPut-all-results", function () { + var dbBulkPutAll, highestKey, allKeys, ourAddedUsers, replacedRecord, allKeys2, ourAddedUsers2, replacedRecord2, allKeys3, ourAddedUsers3, replacedRecord3, lastKey, lastKey, lastKey; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + dbBulkPutAll = new Dexie("TestDBTableBulkPutAllResults"); + dbBulkPutAll.version(1).stores({ + users: "++id,first,last,find", + mates: "++id,first,last,find", + dudes: "++,first,last,find", + }); + return [4 /*yield*/, dbBulkPutAll.users.add({ first: "fsdkljfd", last: "fjkljslk", find: "bulkPutAll" })]; + case 1: + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.users.bulkPut([ + { first: "Åke1", last: "Persbrant1", find: "bulkPutAll" }, + { id: highestKey, first: "Åke2", last: "Persbrant2", find: "bulkPutAll" }, + { first: "Åke3", last: "Persbrant3", find: "bulkPutAll" } + ], { allKeys: true })]; + case 2: + allKeys = _a.sent(); + deepEqual(allKeys, [highestKey + 1, highestKey, highestKey + 2], "Result of bulkAdd(objects, { allKeys: true }) operation was equal to [highestKey + 1, highestKey, highestKey + 2]"); + return [4 /*yield*/, dbBulkPutAll.users.where('find').startsWith("bulkPutAll").toArray()]; + case 3: + ourAddedUsers = _a.sent(); + QUnit.equal(ourAddedUsers.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, dbBulkPutAll.users.get(highestKey)]; + case 4: + replacedRecord = _a.sent(); + QUnit.equal(replacedRecord.last, "Persbrant2", "fjkljslk should now be Persbrant2 instead"); + return [4 /*yield*/, dbBulkPutAll.mates.add({ first: "fsdkljfd", last: "fjkljslk", find: "bulkPutAll" })]; + case 5: + // should be able to get all keys with options object as third argument (mates) + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.mates.bulkPut([ + { first: "Åke1", last: "Persbrant1", find: "bulkPutAll" }, + { id: highestKey, first: "Åke2", last: "Persbrant2", find: "bulkPutAll" }, + { first: "Åke3", last: "Persbrant3", find: "bulkPutAll" } + ], undefined, { allKeys: true })]; + case 6: + allKeys2 = _a.sent(); + deepEqual(allKeys2, [highestKey + 1, highestKey, highestKey + 2], "Result of bulkPut(objects, undefined, { allKeys: true }) operation was equal to [highestKey + 1, highestKey, highestKey + 2]"); + return [4 /*yield*/, dbBulkPutAll.mates.where('find').startsWith("bulkPutAll").toArray()]; + case 7: + ourAddedUsers2 = _a.sent(); + QUnit.equal(ourAddedUsers2.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, dbBulkPutAll.mates.get(highestKey)]; + case 8: + replacedRecord2 = _a.sent(); + QUnit.equal(replacedRecord2.last, "Persbrant2", "fjkljslk should now be Persbrant2 instead"); + return [4 /*yield*/, dbBulkPutAll.dudes.add({ first: "fsdkljfd", last: "fjkljslk", find: "bulkPutAll" })]; + case 9: + // should be able to get all keys with options object as third argument with keys array (dudes) + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkPut([ + { first: "Åke1", last: "Persbrant1", find: "bulkPutAll" }, + { id: highestKey, first: "Åke2", last: "Persbrant2", find: "bulkPutAll" }, + { first: "Åke3", last: "Persbrant3", find: "bulkPutAll" } + ], ['sd5fs2df', highestKey, 'dasfsd3fs7df'], { allKeys: true })]; + case 10: + allKeys3 = _a.sent(); + deepEqual(allKeys3, ['sd5fs2df', highestKey, 'dasfsd3fs7df'], "Result of bulkPut(objects, ['sd5fs2df', highestKey, 'dasfsd3fs7df'], { allKeys: true }) operation was equal to ['sd5fs2df', highestKey, 'dasfsd3fs7df']"); + return [4 /*yield*/, dbBulkPutAll.dudes.where('find').startsWith("bulkPutAll").toArray()]; + case 11: + ourAddedUsers3 = _a.sent(); + QUnit.equal(ourAddedUsers3.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, dbBulkPutAll.dudes.get(highestKey)]; + case 12: + replacedRecord3 = _a.sent(); + QUnit.equal(replacedRecord3.last, "Persbrant2", "fjkljslk should now be Persbrant2 instead"); + return [4 /*yield*/, dbBulkPutAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 13: + // should return last key with 1 argument and options: { allKeys: false } + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], { allKeys: false })]; + case 14: + lastKey = _a.sent(); + QUnit.equal(lastKey, highestKey + 2, "Result of bulkAdd(objects, { allKeys: false }) operation was equal to highestKey + 2"); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false })]; + case 15: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'b33vn3fytn', "Result of bulkAdd(objects, ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false }) operation was equal to 'b33vn3fytn'"); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['dfgd2vdfh4d', 'ty1jxdbd9'])]; + case 16: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'ty1jxdbd9', "Result of bulkAdd(objects, ['dfgd2vdfh4d', 'ty1jxdbd9']) operation was equal to 'ty1jxdbd9'"); + return [4 /*yield*/, dbBulkPutAll.delete()]; + case 17: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkPut with overlapping objects", function () { + var theOne; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.users.bulkPut([{ + id: "sdjls83", + first: "Daveious" + }, { + id: "sdjls83", + last: "Olvono" + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db.users.get("sdjls83")]; + case 2: + theOne = _a.sent(); + QUnit.equal(theOne.last, "Olvono", "Last item is the one inserted"); + QUnit.ok(theOne.first === undefined, "Object doesnt have a first property"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkPut-catching errors", function () { + var _a, newUsersX, e_4, _b, _c, newUsersY, e_5, _d, newUsersZ, _e; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: return [4 /*yield*/, db.transaction("rw", db.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"] }, + { id: idOfFirstUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, + { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] } + ]; + db.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.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-putted"); + }); + })]; + case 1: + _f.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where("username").startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_f.sent(), 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"] }, + { id: idOfFirstUser, first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, + { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] } + ]; + _f.label = 3; + case 3: + _f.trys.push([3, 5, , 6]); + return [4 /*yield*/, db.transaction("rw", db.users, function () { + db.users.bulkPut(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + })]; + case 4: + _f.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 6]; + case 5: + e_4 = _f.sent(); + QUnit.ok(true, "Got: " + e_4); + return [3 /*break*/, 6]; + case 6: + _b = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 7: + _b.apply(void 0, [_f.sent(), 0, "0 users! Good, means that previous transaction did not commit"]); + return [4 /*yield*/, db.users.bulkPut(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + })]; + case 8: + _f.sent(); + _c = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 9: + _c.apply(void 0, [_f.sent(), 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"] }, + { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, + { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] } + ]; + _f.label = 10; + case 10: + _f.trys.push([10, 12, , 13]); + return [4 /*yield*/, db.users.bulkPut(newUsersY)]; + case 11: + _f.sent(); + return [3 /*break*/, 13]; + case 12: + e_5 = _f.sent(); + QUnit.ok(true, "Got: " + e_5); + return [3 /*break*/, 13]; + case 13: + _d = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('yper').count()]; + case 14: + _d.apply(void 0, [_f.sent(), 3, + "Should count to 3 users because previous previous operation catched (via try..yield..catch this time, and therefore should have been committed"]); + 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"] }, + { id: idOfLastUser, first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, + { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] } + ]; + return [4 /*yield*/, db.transaction('rw', db.users, function () { + var e_6; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, db.users.bulkPut(newUsersZ)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + e_6 = _a.sent(); + throw e_6; + case 3: return [2 /*return*/]; + } + }); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('zper').count()]; + case 16: + _e.apply(void 0, [_f.sent(), 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"]); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkPut-non-inbound-autoincrement", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, db.folks.bulkPut([ + { first: "Foo", last: "Bar" }, + { first: "Foo", last: "Bar2" }, + { first: "Foo", last: "Bar3" }, + { first: "Foo", last: "Bar4" } + ])]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.folks.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_c.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db.folks.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_c.sent(), 1, "Should be 1 Bar"]); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkPut - mixed inbound autoIncrement", function () { + var lastId, _a, _b, newLastId, _c, _d, foo2s; + return __generator(this, function (_e) { + switch (_e.label) { + case 0: return [4 /*yield*/, db.users.bulkPut([ + { first: "Foo", last: "Bar" }, + { first: "Foo", last: "Bar2" }, + { first: "Foo", last: "Bar3" }, + { first: "Foo", last: "Bar4" } + ])]; + case 1: + lastId = _e.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_e.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db.users.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_e.sent(), 1, "Should be 1 Bar"]); + return [4 /*yield*/, db.users.bulkPut([ + { id: lastId - 3, first: "Foo2", last: "BarA" }, + { first: "Foo2", last: "BarB" }, + { id: lastId - 1, first: "Foo2", last: "BarC" }, + { first: "Foo2", last: "BarD" } // Will create + ])]; + case 4: + newLastId = _e.sent(); + QUnit.equal(newLastId, lastId + 2, "Should have incremented last ID twice now"); + _c = QUnit.equal; + return [4 /*yield*/, db.users.where('first').equals('Foo').count()]; + case 5: + _c.apply(void 0, [_e.sent(), 2, "Should be 2 Foos now"]); + _d = QUnit.equal; + return [4 /*yield*/, db.users.where('first').equals('Foo2').count()]; + case 6: + _d.apply(void 0, [_e.sent(), 4, "Should be 4 Foo2s now"]); + return [4 /*yield*/, db.users.where('first').equals('Foo2').toArray()]; + case 7: + foo2s = _e.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)"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkPut-catch sub transaction", function () { + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, db.transaction('rw', db.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"] }, + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] } + ]; + db.transaction('rw', db.users, function () { + db.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 1: + _b.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_b.sent(), 0, "0 users! Good, means that inner transaction did not commit"]); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkDelete", function () { + var userKeys, userCount; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.users.orderBy('id').keys()]; + case 1: + userKeys = _a.sent(); + QUnit.ok(userKeys.length > 0, "User keys found: " + userKeys.join(',')); + return [4 /*yield*/, db.users.bulkDelete(userKeys)]; + case 2: + _a.sent(); + return [4 /*yield*/, db.users.count()]; + case 3: + userCount = _a.sent(); + QUnit.equal(userCount, 0, "Should be no users there now"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkDelete - nonexisting keys", function () { + var userKeys, _a, userCount; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["nonexisting1", "nonexisting2"]; + return [4 /*yield*/, db.users.orderBy(':id').lastKey()]; + case 1: + userKeys = _a.concat([_b.sent()]); + return [4 /*yield*/, db.users.bulkDelete(userKeys)]; + case 2: + _b.sent(); + return [4 /*yield*/, db.users.count()]; + case 3: + userCount = _b.sent(); + QUnit.equal(userCount, 1, "Should be one user there now. (the other should have been deleted)"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("bulkDelete-faulty-key", function () { + var userKeys; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + userKeys = [{ faulty: "ohyes" }]; + return [4 /*yield*/, db.users.bulkDelete(userKeys).then(function () { + QUnit.ok(false, "Should not succeed"); + }).catch('DataError', function (e) { + QUnit.ok(true, "Should get error: " + e); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +QUnit.asyncTest("delete", function () { + // Without transaction + db.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }).then(function () { + db.users.delete(1).then(function () { + db.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.transaction("rw", db.users, function () { + db.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }); + db.users.delete(idOfFirstUser); + db.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.users.count().then(function (count) { + numUsers = count; + QUnit.ok(true, "Number of users before delete: " + count); + }).then(function () { + return db.users.delete("nonexisting key"); + }).then(function () { + QUnit.ok(true, "Success even though nothing was deleted"); + }).then(function () { + return db.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.transaction("rw", "users", function () { + db.users.count(function (count) { + QUnit.equal(count, 2, "There are 2 items in database before clearing it"); + }); + db.users.clear(); + db.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", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.transaction('r', 'users', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.users.bulkAdd([{ first: "Foo", last: "Bar" }])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('ReadOnlyError', function (e) { + QUnit.ok(true, "Got ReadOnlyError: " + e.stack); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("failNotIncludedStore", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.transaction('rw', 'folks', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.users.bulkAdd([{ first: "Foo", last: "Bar" }])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('NotFoundError', function (e) { + QUnit.ok(true, "Got NotFoundError: " + e.stack); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +QUnit.asyncTest("failNotIncludedStoreTrans", function () { + db.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); +}); +// Must use this rather than QUnit's deepEqual() because that one fails on Safari when run via karma-browserstack-launcher +function deepEqual(a, b, description) { + QUnit.equal(JSON.stringify(a, null, 2), JSON.stringify(b, null, 2), description); +} +promisedTest("bulkGet()", function () { return __awaiter(void 0, void 0, void 0, function () { + var bulkData, i, keys, retrieved, _a, u1, u2, u3, u4; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + bulkData = []; + for (i = 0; i < 400; ++i) { + bulkData.push({ id: i, first: "Foo" + i, last: "Bar" + i }); + } + QUnit.ok("Putting " + bulkData.length + " users into the table"); + return [4 /*yield*/, db.users.bulkPut(bulkData)]; + case 1: + _b.sent(); + QUnit.ok("Done putting users. Now getting them using bulkGet()"); + keys = bulkData.map(function (_a) { + var id = _a.id; + return id; + }); + return [4 /*yield*/, db.users.bulkGet(keys)]; + case 2: + retrieved = _b.sent(); + deepEqual(retrieved, bulkData, "Put and retrieved should be the same"); + QUnit.ok("Now validating that is should be possible to request nonexisting keys but yet get all results in the order of the given keys"); + return [4 /*yield*/, db.users.bulkGet(["x", "y", 100, "z"])]; + case 3: + _a = _b.sent(), u1 = _a[0], u2 = _a[1], u3 = _a[2], u4 = _a[3]; + QUnit.ok(u1 === undefined, "First result should be undefined, as there where no object with that key"); + QUnit.ok(u2 === undefined, "Second objects -''-"); + QUnit.ok(u3 && u3.first === 'Foo100', "Third should be Foo100"); + QUnit.ok(u4 === undefined, "Forth should be undefined"); + return [2 /*return*/]; + } + }); +}); }); + +var db$1 = new Dexie("TestDBCollection"); +db$1.version(1).stores({ users: "id,first,last,&username,*&email,*pets" }); +var User$1 = db$1.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String], +}); +db$1.on("populate", function () { + db$1.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$1.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$1).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +spawnedTest("and with values", function () { + var array; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$1.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]) + .and(function (user) { return user.username === "dfahlander"; }) + .toArray()]; + case 1: + array = _a.sent(); + QUnit.equal(array.length, 1, "Should find one user with given criteria"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("and with keys", function () { + var keys; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$1.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]) + .and(function (user) { return user.username === "dfahlander"; }) + .keys()]; + case 1: + keys = _a.sent(); + QUnit.equal(keys.length, 1, "Should find one user with given criteria"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("and with delete", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$1.users.orderBy('username') + .and(function (u) { return QUnit.ok(!!u, "User should exist here"); }) + .delete()]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +QUnit.asyncTest("each", 3, function () { + var array = []; + db$1.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$1.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$1.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$1.transaction("r", db$1.users, function () { + db$1.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$1.users.orderBy("last").limit(10).toArray(function (a) { + QUnit.equal(a.length, 2, "Array length is 2"); + }); + db$1.users.orderBy("last").limit(0).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$1.users.orderBy("last").limit(-1).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$1.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$1.transaction("rw", db$1.users, function () { + for (var i = 0; i < 10; ++i) { + db$1.users.add({ id: 3 + i, first: "First" + i, last: "Last" + i, username: "user" + i, email: ["user" + i + "@abc.se"] }); + } + // Using algorithm + count() + db$1.users.where("first").startsWithIgnoreCase("first").count(function (count) { + QUnit.equal(count, 10, "Counting all 10"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").limit(5).count(function (count) { + QUnit.equal(count, 5, "algorithm + count(): limit(5).count()"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).count()"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "algorithm + count(): offset(6).limit(4)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).limit(4)"); + }); + db$1.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$1.users.where("first").startsWithIgnoreCase("first").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "algorithm + toArray(): limit(5)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "algorithm + toArray(): offset(6).limit(4)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7).limit(4)"); + }); + db$1.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$1.users.where("first").startsWith("First").count(function (count) { + QUnit.equal(count, 10, "IDBKeyRange + count() - count all 10"); + }); + db$1.users.where("first").startsWith("First").limit(5).count(function (count) { + QUnit.equal(count, 5, "IDBKeyRange + count(): limit(5)"); + }); + db$1.users.where("first").startsWith("First").offset(7).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7)"); + }); + db$1.users.where("first").startsWith("First").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "IDBKeyRange + count(): offset(6)"); + }); + db$1.users.where("first").startsWith("First").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7).limit(4)"); + }); + db$1.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$1.users.where("first").startsWith("First").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "IDBKeyRange + toArray(): limit(5)"); + }); + db$1.users.where("first").startsWith("First").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7)"); + }); + db$1.users.where("first").startsWith("First").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "IDBKeyRange + toArray(): offset(6).limit(4)"); + }); + db$1.users.where("first").startsWith("First").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7).limit(4)"); + }); + db$1.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$1.users.orderBy("last").first(function (karlCeder) { + QUnit.equal(karlCeder.first, "Karl", "Got Karl"); + }).finally(QUnit.start); +}); +QUnit.asyncTest("last", function () { + db$1.users.orderBy("last").last(function (david) { + QUnit.equal(david.first, "David", "Got David"); + }).finally(QUnit.start); +}); +QUnit.asyncTest("and", 2, function () { + db$1.transaction("r", db$1.users, function () { + db$1.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$1.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$1.transaction("r", db$1.users, function () { + db$1.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$1.transaction("r", db$1.users, function () { + db$1.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$1.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$1.transaction("rw", db$1.users, function () { + var currentTime = new Date(); + db$1.users.toCollection().modify({ + lastUpdated: currentTime + }).then(function (count) { + QUnit.equal(count, 2, "Promise supplied the number of modifications made"); + }); + db$1.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$1.transaction("rw", db$1.users, function () { + var currentTime = new Date(); + db$1.users.toCollection().modify(function (user) { + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$1.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$1.transaction("rw", db$1.users, function () { + var currentTime = new Date(); + db$1.users.toCollection().modify(function (user) { + user.id = 1; + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$1.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); +}); +promisedTest("modify-primary-key", function () { return __awaiter(void 0, void 0, void 0, function () { + var res, user88; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$1.users.add({ id: 87, first: "Olle" })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$1.users.where({ id: 87 }).modify(function (user) { return user.id = 88; })]; + case 2: + res = _a.sent(); + QUnit.ok(res, "Successfully modified the primary key of a user"); + return [4 /*yield*/, db$1.users.get(88)]; + case 3: + user88 = _a.sent(); + QUnit.ok(!!user88, "Should be able to retrieve user 88 using db.users.get(88)"); + QUnit.equal(user88.first, "Olle", "Retrieved user should be David"); + return [2 /*return*/]; + } + }); +}); }); +// +// Issue #594 (A Safari issue) +// +promisedTest("modify-with-where(issue-594)", function () { return __awaiter(void 0, void 0, void 0, function () { + var numDavids, numModifications, davids; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db$1.users.add({ id: 3, first: "David", last: "Fahlander2", username: "dfahlander2", email: ["david2@awarica.com"], pets: [] }); + db$1.users.add({ id: 4, first: "David", last: "Fahlander3", username: "dfahlander3", email: ["david3@awarica.com"], pets: [] }); + return [4 /*yield*/, db$1.users.where('first').equals("David").toArray()]; + case 1: + numDavids = (_a.sent()).length; + QUnit.equal(numDavids, 3, "There should be 3 Davids"); + return [4 /*yield*/, db$1.users.where('first').equals("David").modify(function (object) { object.anotherProperty = 'test'; })]; + case 2: + numModifications = _a.sent(); + QUnit.equal(numModifications, 3, "There should have been 3 modifications"); + return [4 /*yield*/, db$1.users.where({ first: 'David' }).toArray()]; + case 3: + davids = _a.sent(); + QUnit.ok(davids.every(function (david) { return david.anotherProperty === 'test'; }), "All Davids where modified indeed"); + return [2 /*return*/]; + } + }); +}); }); +QUnit.asyncTest("delete", 2, function () { + db$1.users.orderBy("id").delete().then(function (count) { + QUnit.equal(count, 2, "All two records deleted"); + return db$1.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$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$1.users.where("first").equalsIgnoreCase("david").delete().then(function (deleteCount) { + QUnit.equal(deleteCount, 2, "Two items deleted (Both davids)"); + }); + db$1.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$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$1.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$1.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", 3, function () { + db$1.users.orderBy("first").keys(function (a) { + QUnit.equal(a.length, 2, "There should be two results"); + 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", 7, function () { + db$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "David", last: "Helenius", username: "dahel" }); + db$1.users.orderBy("first").keys(function (a) { + QUnit.equal(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$1.users.orderBy("first").uniqueKeys(function (a) { + QUnit.equal(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", 3, function () { + db$1.users.orderBy("last").primaryKeys(function (a) { + QUnit.equal(a.length, 2, "There should be two results"); + 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", 3, function () { + db$1.users.orderBy("first").primaryKeys(function (a) { + QUnit.equal(a.length, 2, "There should be two results"); + 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$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "Ylva", last: "Fahlander", username: "yfahlander" }); + var a = []; + db$1.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$1.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$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "Apan", last: "Japan", username: "apanjapan" }); + db$1.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$1.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$1.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 }); + } + var seed = 1; + function pseudoRandom() { + var x = Math.sin(seed++) * 10000; + return x - Math.floor(x); + } + function randomString(count) { + var ms = []; + for (var i = 0; i < count; ++i) { + ms.push(String.fromCharCode(32 + Math.floor(pseudoRandom() * 95))); + } + 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$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "Apa1", username: "apa1" }); + db$1.users.add({ id: 4, first: "Apa2", username: "apa2" }); + db$1.users.add({ id: 5, first: "Apa3", username: "apa3" }); + // Checking that it stops immediately when first item is the stop item: + db$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.transaction('r', db$1.users, function () { + db$1.users.each(function (user) { + db$1.users.where('id').equals(user.id).first(function (usr) { + return db$1.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 async = Dexie.async; +var db$2 = new Dexie("TestDBWhereClause"); +db$2.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', + chaps: "++id,[name+number]", + multiMulti: "id,*tags,*categories" +}); +var Folder = db$2.folders.defineClass({ + id: Number, + path: String, + description: String +}); +var File = db$2.files.defineClass({ + id: Number, + filename: String, + extension: String, + folderId: Number +}); +File.prototype.getFullPath = function () { + var file = this; + return db$2.folders.get(this.folderId, function (folder) { + return folder.path + "/" + file.filename + (file.extension || ""); + }); +}; +Folder.prototype.getFiles = function () { + return db$2.files.where('folderId').equals(this.id).toArray(); +}; +var Chart = db$2.chart.defineClass({ + patno: Number, + row: Number, + col: Number, + sym: Number +}); +Chart.prototype.save = function () { + return db$2.chart.put(this); +}; +var firstFolderId = 0; +db$2.on("populate", function () { + var folders = db$2.table("folders"); + var files = db$2.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) { + files.add({ filename: "Hello", folderId: id }).then(function (fileId) { + + }); + files.add({ filename: "hello", extension: ".exe", folderId: id }); + }); + folders.add({ path: "/usr/local/src" }).then(function (id) { + 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) { + return files.add({ filename: "hello-there", extension: ".exe", folderId: id }); + }).then(function (id) { + + }); +}); +QUnit.module("WhereClause", { + setup: function () { + QUnit.stop(); + resetDatabase(db$2).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +spawnedTest('Issue#31 Compound Index with anyOf', function () { + var items; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports('compound')) + return [2 /*return*/, QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")]; + return [4 /*yield*/, db$2.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 1: + _a.sent(); + return [4 /*yield*/, db$2.people + .where('[name+number]') + .anyOf([[-2, 0], [-3, 0]]) // https://github.com/dfahlander/Dexie.js/issues/31 + .toArray()]; + case 2: + items = _a.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"); + return [2 /*return*/]; + } + }); +}); +QUnit.asyncTest("startsWithAnyOf()", function () { + function runTheTests(mippler) { + /// + // + // Basic Flow: + // + return mippler(db$2.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$2.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$2.folders.where('path').startsWithAnyOf([])).count(), // Empty + mippler(db$2.folders.where('path').startsWithAnyOf('/var', '/var', '/var')).count(), // Duplicates + mippler(db$2.folders.where('path').startsWithAnyOf('')).count(), // Empty string should match all + mippler(db$2.folders).count(), mippler(db$2.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$2.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$2.transaction('r', db$2.folders, db$2.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$2.transaction("r", db$2.files, db$2.folders, function () { + db$2.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$2.files.put({ id: 9000, filename: "new file 1", folderId: firstFolderId }); + db$2.files.put({ id: 10000, filename: "new file 2", folderId: firstFolderId }); + db$2.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$2.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$2.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$2.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$2.transaction("rw", db$2.files, function () { + fileArray.forEach(function (file) { + db$2.files.add(file); + }); + db$2.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$2.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$2.transaction("rw", db$2.files, function () { + fileArray.forEach(function (file) { + db$2.files.add(file); + }); + db$2.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$2.transaction("rw", db$2.files, function () { + db$2.files.clear(); + db$2.files.add({ filename: "Hello-there-", folderId: 1 }); + db$2.files.add({ filename: "hello-there-", folderId: 1 }); + db$2.files.add({ filename: "hello-there-everyone", folderId: 1 }); + db$2.files.add({ filename: "hello-there-everyone-of-you!", folderId: 1 }); + // Ascending + db$2.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$2.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$2.transaction("r", db$2.folders, function () { + db$2.folders.count(function (count) { + QUnit.ok(true, "Number of folders in database: " + count); + db$2.folders.where("path").startsWithIgnoreCase("/").toArray(function (a) { + QUnit.equal(a.length, count, "Got all folder objects because all of them starts with '/'"); + }); + }); + db$2.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$2.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$2.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$2.transaction("r", db$2.files, function () { + db$2.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$2.transaction('rw', db$2.people, function () { + db$2.people.add({ name: "Santaclaus", number: 123 }); + db$2.people.add({ name: "Santaclaus", number: 124 }); + db$2.people.add({ name: "Santaclaus2", number: 1 }); + return db$2.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$2.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$2.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$2.transaction("rw", db$2.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$2.chart.bulkAdd(chart); + }).then(function () { + var grid = [], x1 = 91, x2 = 130; + return db$2.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$2.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$2.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$2.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$2.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$2.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$2.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$2.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$2.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$2.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$2.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$2.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$2.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$2.transaction('rw', db$2.friends, function () { + db$2.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$2.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$2.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$2.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$2.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$2.transaction('r', db$2.folders, db$2.files, function () { + db$2.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$2.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$2.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$2.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$2.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$2.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$2.folders.where('path').startsWithAnyOfIgnoreCase([])).count(), // Empty + mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase('/var', '/var', '/var')).count(), // Duplicates + mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase('')).count(), // Empty string should match all + mippler(db$2.folders).count(), mippler(db$2.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$2.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$2.transaction('r', db$2.folders, db$2.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); +}); +promisedTest("where({key: value})", function () { return __awaiter(void 0, void 0, void 0, function () { + var readme, noResult, ullaBella1, ullaBella2, ullaBella3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$2.files.where({ filename: "README" }).first()]; + case 1: + readme = _a.sent(); + QUnit.ok(readme, 'Should get a result for db.files.get({filename: "README"});'); + QUnit.equal(readme.extension, ".TXT", "Should get README.TXT"); + return [4 /*yield*/, db$2.files.get({ filename: "README", extension: ".TXT" })]; + case 2: + readme = _a.sent(); + QUnit.ok(readme, 'Should get a result for db.files.get({filename: "README", extension: ".TXT"});'); + return [4 /*yield*/, db$2.files.get({ filename: "apa", extension: "otto" })]; + case 3: + noResult = _a.sent(); + QUnit.ok(!noResult, "Should not get a result when querying non-existing stuff"); + // Friends have single indexes on "name" and "age" + return [4 /*yield*/, db$2.friends.add({ name: "Ulla Bella", number: 888, age: 88 })]; + case 4: + // Friends have single indexes on "name" and "age" + _a.sent(); + // People have compound index for [name, number] + return [4 /*yield*/, db$2.chaps.add({ name: "Ulla Bella", number: 888, age: 88 })]; + case 5: + // People have compound index for [name, number] + _a.sent(); + // Folders haven't indexed any of "name", "number" or "age" + return [4 /*yield*/, db$2.folders.add({ name: "Ulla Bella", number: 888, age: 88 })]; + case 6: + // Folders haven't indexed any of "name", "number" or "age" + _a.sent(); + return [4 /*yield*/, db$2.friends.get({ name: "Ulla Bella", number: 888 })]; + case 7: + ullaBella1 = _a.sent(); + QUnit.ok(!!ullaBella1, "Should be able to query multiple columns even when only one of them is indexed"); + return [4 /*yield*/, db$2.chaps.get({ name: "Ulla Bella", number: 888 })]; + case 8: + ullaBella2 = _a.sent(); + QUnit.ok(!!ullaBella2, "Should be able to query multiple columns. This time utilizing compound index."); + return [4 /*yield*/, db$2.chaps.get({ number: 888, name: "Ulla Bella" })]; + case 9: + ullaBella3 = _a.sent(); + QUnit.ok(!!ullaBella3, "Should be able to utilize compound index no matter the order of criterias."); + return [4 /*yield*/, db$2.folders.get({ name: "Ulla Bella", number: 888 }).then(function (ulla) { + QUnit.ok(false, "Should not get Ulla Bella when no index was found"); + }).catch('SchemaError', function (e) { + QUnit.ok(true, "Got SchemaError because we're not utilizing any index at all: " + e); + })]; + case 10: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("orderBy(['idx1','idx2'])", function () { return __awaiter(void 0, void 0, void 0, function () { + var files; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("compound")) { + QUnit.ok(true, "Browser does not support compound indexes. Ignoring test."); + return [2 /*return*/]; + } + db$2.files.add({ filename: "hello", extension: ".bat" }); + return [4 /*yield*/, db$2.files.orderBy(["filename", "extension"]).toArray()]; + case 1: + files = _a.sent(); + QUnit.equal(files.length, 5, "Should be 5 files in total that has both filename and extension"); + QUnit.equal(files.map(function (f) { return f.filename + f.extension; }).join(','), "README.TXT,hello.bat,hello.exe,hello-there.exe,world.js", 'Files should be ordered according to the orderBy query'); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Issue #696 - Query on multiple multi-entry indexes doesn't seem to work", function () { return __awaiter(void 0, void 0, void 0, function () { + var cat_a, cat_a_tag_a; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("multientry")) { + QUnit.ok(true, "No support for multiEntry in browser. Skippping."); + return [2 /*return*/]; + } + return [4 /*yield*/, db$2.multiMulti.bulkAdd([ + { id: 1, name: "Foo", age: 42, categories: ['cat_a', 'cat_b'], tags: ['tag_a', 'tag_b'] }, + { id: 2, name: "Bar", age: 32, categories: ['cat_b', 'cat_c'], tags: ['tag_b', 'tag_c'] } + ])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$2.multiMulti.where({ categories: 'cat_a' }).distinct().toArray()]; + case 2: + cat_a = _a.sent(); + QUnit.equal(cat_a.length, 1, "Should get one item"); + return [4 /*yield*/, db$2.multiMulti.where({ 'categories': 'cat_a', 'tags': 'tag_a' }) + .distinct() + .toArray()]; + case 3: + cat_a_tag_a = _a.sent(); + QUnit.equal(cat_a_tag_a.length, 1, "Should get one item here as well"); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Virtual Index", function () { return __awaiter(void 0, void 0, void 0, function () { + var davids, daves; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports('compound')) + return [2 /*return*/, QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")]; + return [4 /*yield*/, db$2.chaps.bulkAdd([{ + name: "David", + number: 2 + }, { + name: "David", + number: 3 + }, { + name: "David", + number: 1 + }, { + name: "Mambo", + number: 5 + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$2.chaps.where({ name: "David" }).toArray()]; + case 2: + davids = _a.sent(); + QUnit.equal(davids.length, 3, "There should be 3 Davids in the result"); + return [4 /*yield*/, db$2.chaps.where('name').equalsIgnoreCase('david').toArray()]; + case 3: + daves = _a.sent(); + QUnit.equal(JSON.stringify(daves.map(function (_a) { + var name = _a.name, number = _a.number; + return ({ name: name, number: number }); + }), null, 2), JSON.stringify([ + { name: "David", number: 1 }, + { name: "David", number: 2 }, + { name: "David", number: 3 } + ], null, 2), "equalsIgnoreCase() should work with virtual indexes"); + return [2 /*return*/]; + } + }); +}); }); + +var db$3 = new Dexie("TestDBTrans"); +db$3.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" +}); +QUnit.module("transaction", { + setup: function () { + QUnit.stop(); + resetDatabase(db$3).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +var NativePromise = window.Promise; +QUnit.asyncTest("Transaction should work when returning native Promise in transaction scope", function () { + if (!NativePromise) { + QUnit.ok(true, "Current Browser doesn't have a native Promise"); + return QUnit.start(); + } + db$3.transaction('rw', db$3.users, function (trans) { + QUnit.ok(Dexie.currentTransaction === trans, "First argument to transaction callback should be the transaction instance itself"); + return NativePromise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + }).then(function () { + return db$3.users.add({ username: "barfoo" }); // Will only work on Chrome, Opera and Edge as of Oktober 6, 2016. + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + return db$3.users.count(); + }); + }).then(function (count) { + QUnit.ok(true, "User count: " + count + ". REJOICE! YOUR BROWSER'S INDEXEDDB PLAYS BALL WITH PROMISES!"); + }).catch('TransactionInactiveError', function (e) { + QUnit.ok(true, "Your browser has native incompatibility between native Promise and IndexedDB. This is why we still avoid returning native promises."); + }).catch(function (e) { + QUnit.ok(false, "Failed: " + (e.stack || e)); + }).finally(QUnit.start); +}); +QUnit.asyncTest("empty transaction block", function () { + db$3.transaction('rw', db$3.users, db$3.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$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "arne" }); + return db$3.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$3.pets.add({ kind: "dog" }).then(function () { + return db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "arne" }); + return db$3.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$3.transaction('rw', db$3.users, function () { + db$3.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$3.transaction('r', db$3.users, function () { + db$3.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$3.transaction('rw', db$3.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$3.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$3.transaction('rw', db$3.users, function () { + // First make an operation so that transaction is internally created (this is the thing differing from the previous test case + return db$3.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$3.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$3.transaction('rw', db$3.users, db$3.pets, db$3.petsPerUser, function () { + QUnit.ok(parentTrans._reculock > 0, "Parent transaction is locked"); + db$3.users.add(user); + pets.forEach(function (pet) { + db$3.pets.add(pet).then(function (petId) { + return db$3.petsPerUser.add({ user: user.username, pet: petId }); + }); + }); + }).then(function () { + return db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: user.username + "2" }); + return "hello..."; + }); + }); + } + db$3.transaction('rw', db$3.users, db$3.pets, db$3.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$3.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$3.users.get("someoneelse", function (someone) { + QUnit.ok(!someone, "Someoneelse not yet added"); + }); + db$3.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$3.users.count(function (count) { + QUnit.equal(count, 5, "There are five users in db"); + }); + db$3.pets.count(function (count) { + QUnit.equal(count, 3, "There are three pets in db"); + }); + db$3.petsPerUser.count(function (count) { + 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$3.transaction('rw', db$3.users, function () { + // Do an add operation + db$3.users.add({ username: "sune" }); //.then(function () { + // Start an inner transaction + db$3.transaction('rw', db$3.users, function () { + // Do an add-operation that will result in ConstraintError: + db$3.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$3.transaction('rw', db$3.users, db$3.pets, db$3.petsPerUser, function () { + db$3.users.add({ username: "ojsan" }); + db$3.transaction('rw', db$3.users, db$3.pets, function () { + db$3.users.add({ username: "ojsan2" }); + db$3.users.toCollection().delete(); + db$3.transaction('r', db$3.users, function () { + db$3.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$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "bertil" }); + db$3.transaction('rw', db$3.users, db$3.pets, function () { + db$3.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$3.transaction('r', db$3.users, db$3.pets, function () { + db$3.users.toArray(); + db$3.transaction('rw', db$3.users, db$3.pets, function () { + db$3.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$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "bertil" }); + db$3.transaction('rw!', db$3.users, db$3.pets, function () { + db$3.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$3.transaction('r', db$3.users, db$3.pets, function () { + db$3.users.toArray(); + db$3.transaction('rw!', db$3.users, db$3.pets, function () { + db$3.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$3.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$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "bertil" }); + db$3.transaction('rw?', db$3.users, db$3.pets, function () { + db$3.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$3.transaction('r', db$3.users, db$3.pets, function () { + db$3.users.toArray(); + db$3.transaction('rw?', db$3.users, db$3.pets, function () { + db$3.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$3.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$3.transaction('rw', db$3.users, db$3.pets, db$3.petsPerUser, function () { + db$3.users.add({ username: "ojsan" }); + db$3.transaction('rw?', db$3.users, db$3.pets, function () { + db$3.users.add({ username: "ojsan2" }); + db$3.users.toCollection().delete(); + db$3.transaction('r?', db$3.users, function () { + db$3.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$3.transaction('rw', db$3.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$3.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$3.transaction('rw', db$3.users, db$3.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + QUnit.ok(true, "Now adding Gunnar in parent transaction"); + db$3.users.add({ username: "Gunnar" }).then(function () { + QUnit.ok(true, "First add on parent transaction finished. Now adding another object in parent transaction."); + db$3.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$3.transaction('rw', db$3.users, function () { + QUnit.ok(true, "Entered sub transaction"); + return db$3.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$3.transaction('rw', db$3.users, db$3.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + var trans = Dexie.currentTransaction; + return db$3.transaction('rw', db$3.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$3.users.add({ username: "Gunnar" }); + return db$3.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$3.transaction('rw', db$3.users, db$3.pets, function () { + console.log("Entering small child"); + return db$3.users.add({ + 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$3.transaction('rw', db$3.users, db$3.pets, function () { + console.log("Entering middle child"); + return db$3.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$3.transaction('rw', db$3.users, db$3.pets, function () { + console.log("Entering root transaction"); + return db$3.transaction('rw', db$3.users, db$3.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$3.transaction('rw', db$3.pets, function () { + var rootLevelTransaction = Dexie.currentTransaction; + QUnit.ok(true, "Entered root transaction scope"); + return db$3.transaction('rw', db$3.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$3.transaction('rw', db$3.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$3.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$3.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$3.transaction('rw', db$3.pets, function () { + var innermostTransaction2 = Dexie.currentTransaction; + QUnit.ok(innermostTransaction2.parent == level2Transaction, "Another 3rd level transaction has parent set to our level2 transaction"); + return db$3.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$3.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$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "erictheviking", color: "blue" }).then(function () { + db$3.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$3.users.put({ username: "erictheviking", color: "red" }); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); +}); +QUnit.asyncTest("Dexie.currentTransaction in CRUD hooks", 83 /* If fails on num assertions, it's ok to change to expected if all looks fine */, 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$3.users.hook.creating.subscribe(onCreating); + db$3.users.hook.reading.subscribe(onReading); + db$3.users.hook.updating.subscribe(onUpdating); + db$3.users.hook.deleting.subscribe(onDeleting); + function doTheTests() { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.users.add({ username: "monkey1" })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.users.add({ username: "monkey1" }).catch(function (ex) { + QUnit.ok(true, "Should fail adding a second monkey1"); + })]; + case 2: + _a.sent(); // Trigger creating.onerror + // Test bulkAdd as well: + QUnit.ok(true, "Testing bulkAdd"); + return [4 /*yield*/, db$3.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); + })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.users.where("username").equals("monkey1").modify({ + name: "Monkey 1" + })]; + case 4: + _a.sent(); + return [4 /*yield*/, db$3.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 to an already existing primary key"); + })]; + case 5: + _a.sent(); + QUnit.ok(true, "Will now be modifying primary key of monkey1..."); + return [4 /*yield*/, db$3.users.where("username").equals("monkey1").modify(function (user) { + user.username = "monkey88"; // trigger updating.onerror + }).then(function (res) { + QUnit.ok(true, "Should succeed modifying primary key to non-existing primary key, resulting in deletion and creation: " + res); + }).catch(function (ex) { + QUnit.ok(false, "Should succeed modifying primary key to non-existing primary key, resulting in deletion and creation: " + ex); + })]; + case 6: + _a.sent(); + QUnit.ok(true, "Will now modify monkey88 back to monkey1 again..."); + return [4 /*yield*/, db$3.users.where({ username: "monkey88" }).modify({ username: "monkey1" })]; + case 7: + _a.sent(); + return [4 /*yield*/, db$3.users.toArray()]; + case 8: + _a.sent(); + return [4 /*yield*/, db$3.users.delete("monkey2")]; + case 9: + _a.sent(); + return [4 /*yield*/, db$3.users.delete("monkey1")]; + case 10: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + } + + doTheTests().then(function () { + var _this = this; + QUnit.ok(true, "Now in an explicit transaction block..."); + return db$3.transaction('rw', db$3.users, function () { return __awaiter(_this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, doTheTests()]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + }).catch(function (ex) { + QUnit.ok(false, ex); + }).then(function () { + db$3.users.hook.creating.unsubscribe(onCreating); + db$3.users.hook.reading.unsubscribe(onReading); + db$3.users.hook.updating.unsubscribe(onUpdating); + db$3.users.hook.deleting.unsubscribe(onDeleting); + QUnit.start(); + }); +}); +function sleep(ms) { + return new Promise(function (resolve) { return setTimeout(resolve, ms); }); +} +promisedTest("waitFor()", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.transaction('rw', db$3.users, function (trans) { return __awaiter(void 0, void 0, void 0, function () { + var result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + // Wait for a promise: + return [4 /*yield*/, trans.waitFor(sleep(100))]; + case 1: + // Wait for a promise: + _a.sent(); + // Do an operation on transaction + return [4 /*yield*/, trans.users.put({ username: "testingtesting" })]; + case 2: + // Do an operation on transaction + _a.sent(); + return [4 /*yield*/, trans.waitFor(sleep(100))]; + case 3: + _a.sent(); + return [4 /*yield*/, trans.users.get("testingtesting")]; + case 4: + result = _a.sent(); + QUnit.ok(result && result.username === "testingtesting", "Should be able to continue transaction after waiting for non-indexedDB promise"); + QUnit.ok(true, "Waiting spin count:" + trans._spinCount); + // With timeout + return [4 /*yield*/, Dexie.waitFor(sleep(2000), 10) // Timeout of 10 ms. + .then(function () { return QUnit.ok(false, "Should have timed out!"); }) + .catch('TimeoutError', function (ex) { return QUnit.ok(true, "Timed out as expected"); })]; + case 5: + // With timeout + _a.sent(); + // Wait for function + return [4 /*yield*/, Dexie.waitFor(function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(Dexie.currentTransaction === null, "We should not be in the transaction zone here because transaction can be in a temporary inactive state here"); + return [4 /*yield*/, sleep(10)]; + case 1: + _a.sent(); + QUnit.ok(true, "Slept 10 ms"); + // Let's test if we can access the transaction from here. + // The transaction should be alive indeed but not in an active state. + return [4 /*yield*/, trans.users.count().then(function () { + // This happens on IE11 + QUnit.ok(true, "Could access transaction within the wait callback. Nice for you, but you were just lucky!"); + }).catch(function (ex) { + // This happens on Firefox and Chrome + QUnit.ok(true, "Could NOT access transaction within the wait callback. As expected. Error: " + ex); + })]; + case 2: + // Let's test if we can access the transaction from here. + // The transaction should be alive indeed but not in an active state. + _a.sent(); + QUnit.ok(Dexie.currentTransaction === null, "We should not be in the transaction zone here because transaction can be in inactive state here"); + return [2 /*return*/]; + } + }); + }); })]; + case 6: + // Wait for function + _a.sent(); + return [4 /*yield*/, trans.users.get("testingtesting")]; + case 7: + result = _a.sent(); + QUnit.ok(result && result.username === "testingtesting", "Should still be able to operate on the transaction"); + QUnit.ok(true, "Waiting spin count:" + trans._spinCount); + QUnit.ok(Dexie.currentTransaction === trans, "Zone info should still be correct"); + // Subtransaction + return [4 /*yield*/, db$3.transaction('r', db$3.users, function (subTrans) { + var count; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(subTrans !== trans, "Should be in a sub transaction"); + QUnit.ok(Dexie.currentTransaction === subTrans, "Should be in a sub transaction"); + return [4 /*yield*/, trans.users.count()]; + case 1: + count = _a.sent(); + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + return [4 /*yield*/, subTrans.waitFor(sleep(10))]; + case 2: + _a.sent(); + QUnit.ok(true, "Should be able to call waitFor() on sub transaction"); + return [4 /*yield*/, trans.users.count()]; + case 3: + count = _a.sent(); + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + return [2 /*return*/]; + } + }); + })]; + case 8: + // Subtransaction + _a.sent(); + // Calling waitFor multiple times in parallell + return [4 /*yield*/, Promise.all([ + trans.waitFor(sleep(10)), + trans.waitFor(sleep(10)), + trans.waitFor(sleep(10)) + ])]; + case 9: + // Calling waitFor multiple times in parallell + _a.sent(); + QUnit.ok(true, "Could wait for several tasks in parallell"); + return [4 /*yield*/, trans.users.get("testingtesting")]; + case 10: + result = _a.sent(); + QUnit.ok(result && result.username === "testingtesting", "Should still be able to operate on the transaction"); + return [2 /*return*/]; + } + }); + }); }).then(function () { return QUnit.ok(true, "Transaction committed"); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Dexie.waitFor() outside transaction", function () { return __awaiter(void 0, void 0, void 0, function () { + var result, codeExecuted; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie.waitFor(sleep(10).then(function () { return true; }))]; + case 1: + result = _a.sent(); + QUnit.ok(result, "Could call waitFor outside a transaction as well"); + codeExecuted = false; + return [4 /*yield*/, Dexie.waitFor(function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, sleep(10)]; + case 1: + _a.sent(); + codeExecuted = true; + return [2 /*return*/]; + } + }); + }); })]; + case 2: + _a.sent(); + QUnit.ok(codeExecuted, "Could call waitFor(function) outside a transation as well"); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Dexie.waitFor() TransactionInactiveError", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.transaction('r', db$3.users, function () { return __awaiter(void 0, void 0, void 0, function () { + var err_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, sleep(100)]; + case 1: + _a.sent(); // Force transaction to become inactive + _a.label = 2; + case 2: + _a.trys.push([2, 4, , 5]); + return [4 /*yield*/, Dexie.waitFor(sleep(10))]; + case 3: + _a.sent(); + QUnit.ok(false, 'After sleeping, transaction just cannot be alive.'); + return [3 /*break*/, 5]; + case 4: + err_1 = _a.sent(); + QUnit.ok(err_1.name == 'TransactionInactiveError' || err_1.name == 'InvalidStateError', "Got TransactionInactiveError or InvalidStateError as expected"); + return [3 /*break*/, 5]; + case 5: return [2 /*return*/]; + } + }); + }); }).then(function () { + QUnit.ok(false, 'The transaction should not possibly succeed even though catching, because it was too late.'); + }).catch('PrematureCommitError', function (err) { + QUnit.ok(true, 'Got PrematureCommitError as expected'); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Promise.follow() should omit promises spawned under Dexie.ignoreTransaction()", function () { return __awaiter(void 0, void 0, void 0, function () { + var resolve, reject, p, log; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + p = new Promise(function (res, rej) { resolve = res; reject = rej; }); + log = []; + return [4 /*yield*/, db$3.transaction('r', db$3.users, function () { + // Since we do not return a promise here, + // Promise.follow() will be used for awaitint all tasks. + // However, tasks spawned under Dexie.ignoreTransacion() should not be included in promises to wait for. + Dexie.ignoreTransaction(function () { + return new Dexie.Promise(function (resolve) { return setTimeout(resolve, 50); }).then(function () { + return db$3.pets.put({ kind: "dog" }); + }).then(function () { + return db$3.pets.count(); + }).then(function (numPets) { + QUnit.ok(true, "num pets: " + numPets); + log.push("inner-task-done"); + }).then(resolve, reject); + }); + // The following promise should be awaited for though (because new Promise is spawned from withing a zone or sub-zone to current transaction.) + new Dexie.Promise(function (resolve) { return setTimeout(resolve, 25); }).then(function () { + //return db.users.get(1); + }).then(function () { + QUnit.ok(true, "followed promise done"); + log.push("spawned-promise-done"); + }).catch(function (e) { + QUnit.ok(false, e); + }); + })]; + case 1: + _a.sent(); + log.push("outer-task-done"); + QUnit.ok(true, "transaction done"); + return [4 /*yield*/, p]; + case 2: + _a.sent(); + QUnit.equal(log.join(','), "spawned-promise-done,outer-task-done,inner-task-done", "outer-task-done should have happened before inner-task-done"); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("db.transaction() should not wait for non-awaited new top-level transactions to commit", function () { return __awaiter(void 0, void 0, void 0, function () { + var resolve, reject, p, log; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + p = new Promise(function (res, rej) { resolve = res; reject = rej; }); + log = []; + return [4 /*yield*/, db$3.transaction('r', db$3.users, function () { + // Since we do not return a promise here, + // Promise.follow() will be used for awaitint all tasks. + // However, if we spawn a new top-level transaction. It should be omitted and not waited for: + db$3.transaction('rw!', db$3.pets, function () { + return db$3.pets.put({ kind: "dog" }).then(function () { + return db$3.pets.count(); + }).then(function (numPets) { + QUnit.ok(true, "num pets: " + numPets); + }).then(function () { + return Dexie.waitFor(sleep(50)); // In IE, it sometimes happens that outer transaction is slow to commit (even though it doesnt to anything) + }).then(function () { + log.push("inner-transaction-done"); + }).then(resolve, reject); + }); + })]; + case 1: + _a.sent(); + log.push("outer-transaction-done"); + QUnit.ok(true, "transaction done"); + return [4 /*yield*/, p]; + case 2: + _a.sent(); + QUnit.equal(log.join(','), "outer-transaction-done,inner-transaction-done", "outer-transaction-done should have happened before inner-transaction-done"); + return [2 /*return*/]; + } + }); +}); }); + +var async$1 = 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$1(function (promise, ms) { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.race([promise, new Promise(function (resolve, reject) { return setTimeout(function () { return reject("timeout"); }, ms); })])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("multiple db should not block each other", function () { + var db1, db2, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("versionchange")) { + QUnit.ok(true, "SKIPPED - versionchange UNSUPPORTED"); + return [2 /*return*/]; + } + db1 = new Dexie("TestDB"), db2 = new Dexie("TestDB"); + db1.version(1).stores({ + foo: 'bar' + }); + db2.version(1).stores({ + foo: 'bar' + }); + return [4 /*yield*/, db1.open()]; + case 1: + _a.sent(); + QUnit.ok(true, "db1 should open"); + return [4 /*yield*/, db2.open()]; + case 2: + _a.sent(); + QUnit.ok(true, "db2 should open"); + _a.label = 3; + case 3: + _a.trys.push([3, 5, , 6]); + return [4 /*yield*/, timeout(db1.delete(), 1500)]; + case 4: + _a.sent(); + QUnit.ok(true, "Succeeded to delete db1 while db2 was open"); + return [3 /*break*/, 6]; + case 5: + e_1 = _a.sent(); + db1.close(); + db2.close(); + QUnit.ok(false, "Could not delete db1 - " + e_1); + return [3 /*break*/, 6]; + case 6: return [2 /*return*/]; + } + }); +}); +spawnedTest("Using db on node should be rejected with MissingAPIError", function () { + var db, e_2, e_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie('TestDB', { + indexedDB: undefined, + IDBKeyRange: undefined + }); + db.version(1).stores({ foo: 'bar' }); + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, db.foo.toArray()]; + case 2: + _a.sent(); + QUnit.ok(false, "Should not get any result because API is missing."); + return [3 /*break*/, 4]; + case 3: + e_2 = _a.sent(); + QUnit.ok(e_2 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + e_2.name); + return [3 /*break*/, 4]; + case 4: + _a.trys.push([4, 6, , 7]); + return [4 /*yield*/, db.open()]; + case 5: + _a.sent(); + return [3 /*break*/, 7]; + case 6: + e_3 = _a.sent(); + QUnit.ok(e_3 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + e_3.name); + return [3 /*break*/, 7]; + case 7: return [2 /*return*/]; + } + }); +}); +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", 13, 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"); + }).then(function (names) { + return Dexie.exists("nonexistingDB"); + }).then(function (exists) { + QUnit.ok(!exists, "'nonexistingDB' should not exist indeed"); + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.ok(!names.indexOf("nonexistingDB") !== -1, "nonexistingDB must not have been recorded when calling Dexie.exists()"); + }).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 if (!self.Promise) self.Promise = Dexie.Promise;\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 // Verify we workaround Safari issues with getAll() in workers\n // ... as discussed in PR #579.\n return db.table1.toArray();\n }).then(function(){\n ok(true, \"Could all toArray() on a table (verified workaround for Safari 10.1 issue with getAll())\");\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, function () { + var db; + return __generator(this, function (_a) { + switch (_a.label) { + 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)); + }); + return [4 /*yield*/, db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +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); +}); +promisedTest("#392 db.on('ready') don't fire if subscribed while waiting other promise-returning subscriber", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, first, second, third; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie('TestDB'); + db.version(1).stores({ foobar: 'id' }); + first = false, second = false, third = false; + // first is registered before open + db.on('ready', function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + first = true; + // second is registered while first is executing + db.on('ready', function () { + second = true; + }); + return [2 /*return*/]; + }); + }); }); + return [4 /*yield*/, db.open()]; + case 1: + _a.sent(); + db.on('ready', function () { return third = true; }); + return [4 /*yield*/, Dexie.Promise.resolve()]; + case 2: + _a.sent(); + QUnit.ok(first, "First subscriber should have been called"); + QUnit.ok(second, "Second subscriber should have been called"); + QUnit.ok(third, "Third subscriber should have been called"); + return [2 /*return*/]; + } + }); +}); }); + +var db$4 = new Dexie("TestYieldDb"); +var async$2 = Dexie.async; +var spawn = Dexie.spawn; +db$4.version(1).stores({ + friends: '++id,name,*groups', + pets: '++id,name' +}); +QUnit.module("yield", { + setup: function () { + QUnit.stop(); + resetDatabase(db$4).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +QUnit.asyncTest("db.transaction() with yield", async$2(function () { + var finallyWasReached, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + finallyWasReached = false; + _a.label = 1; + case 1: + _a.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, db$4.transaction('rw', 'friends', 'pets', function () { + var catId, dogId, gurra, gurrasPets; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$4.pets.add({ name: "Tito", kind: "cat" })]; + case 1: + catId = _a.sent(); + return [4 /*yield*/, db$4.pets.add({ name: "Josephina", kind: "dog" })]; + case 2: + dogId = _a.sent(); + // Add a friend who owns the pets + db$4.friends.add({ name: "Gurra G", pets: [catId, dogId] }); + return [4 /*yield*/, db$4.friends.where('name').equals("Gurra G").first()]; + case 3: + gurra = _a.sent(); + QUnit.ok(!!gurra, "Gurra could be found with yield"); + return [4 /*yield*/, db$4.pets.where('id').anyOf(gurra.pets).toArray()]; + case 4: + gurrasPets = _a.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"); + return [2 /*return*/]; + } + }); + })]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: + e_1 = _a.sent(); + QUnit.ok(false, "Caught error: " + e_1); + return [3 /*break*/, 5]; + case 4: + finallyWasReached = true; + return [7 /*endfinally*/]; + case 5: + QUnit.ok(finallyWasReached, "finally was reached"); + QUnit.start(); + return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Catching indexedDB error event", 2, async$2(function () { + var e_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 4]; + case 3: + e_2 = _a.sent(); + QUnit.equal(e_2.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + return [3 /*break*/, 4]; + case 4: + QUnit.start(); + return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Catching error prevents transaction from aborting", 5, async$2(function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0, , 4, 5]); + return [4 /*yield*/, db$4.transaction('rw', 'pets', function () { + var e_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 4]; + case 3: + e_3 = _a.sent(); + QUnit.equal(e_3.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + })]; + case 1: + _c.sent(); + QUnit.ok(true, "Should come here - transaction committed because we caught the error"); + _a = QUnit.ok; + return [4 /*yield*/, db$4.pets.get(1)]; + case 2: + _a.apply(void 0, [(_c.sent()), "A pet with ID 1 exists in DB"]); + _b = QUnit.equal; + return [4 /*yield*/, db$4.pets.get(1)]; + case 3: + _b.apply(void 0, [(_c.sent()).name, "Tidi", "It was Tidi in the first position"]); + return [3 /*break*/, 5]; + case 4: + QUnit.start(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Transaction not committing when not catching error event", 4, async$2(function () { + var e_4, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, 4, 5]); + return [4 /*yield*/, db$4.transaction('rw', 'pets', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [2 /*return*/]; + } + }); + })]; + case 1: + _b.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 5]; + case 2: + e_4 = _b.sent(); + QUnit.ok(true, "Transaction should fail"); + QUnit.equal(e_4.name, "ConstraintError", "Error caught was a ConstraintError!"); + _a = QUnit.equal; + return [4 /*yield*/, db$4.pets.count()]; + case 3: + _a.apply(void 0, [(_b.sent()), 0, "Pets table should still be empty because transaction failed"]); + return [3 /*break*/, 5]; + case 4: + QUnit.start(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Should allow yielding a non-promise", async$2(function () { + var x, e_5; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, 3]; + case 1: + x = _a.sent(); + QUnit.equal(x, 3, "Could yield a non-promise"); + return [3 /*break*/, 4]; + case 2: + e_5 = _a.sent(); + QUnit.ok(false, "Yielding a non-Thenable wasn't be allowed"); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Should allow yielding an array with a mix of values and thenables", async$2(function () { + var results, e_6; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, [1, 2, Dexie.Promise.resolve(3)]]; + case 1: + results = _a.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 [3 /*break*/, 4]; + case 2: + e_6 = _a.sent(); + QUnit.ok(false, "Got exception when trying to do yield an array of mixed values/promises"); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Should allow yielding an array of non-promises only", async$2(function () { + var results, e_7; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, [1, 2, 3]]; + case 1: + results = _a.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 [3 /*break*/, 4]; + case 2: + e_7 = _a.sent(); + QUnit.ok(false, e_7); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Should allow yielding an empty array", async$2(function () { + var results, e_8; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, []]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 0, "Yielded array is of size 0"); + return [3 /*break*/, 4]; + case 2: + e_8 = _a.sent(); + QUnit.ok(false, e_8); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Should allow yielding an array of different kind of any kind of promise", function () { + spawn(function () { + var results; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, [Promise.resolve(1), Dexie.Promise.resolve(2), Promise.resolve(3)]]; + case 1: + results = _a.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 [2 /*return*/, 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("Throw after yield 1", function () { + spawn(function () { + var e_9; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, Promise.resolve(3)]; + case 1: + _a.sent(); + QUnit.ok(true, "yielded a value"); + throw "error"; + case 2: + e_9 = _a.sent(); + QUnit.ok(e_9 === "error", "Catched exception: " + e_9); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 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("Throw after yield 2", function () { + Promise.resolve(spawn(function () { + var e_10; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, 3]; + case 1: + _a.sent(); + QUnit.ok(true, "yielded a value"); + throw "error"; + case 2: + e_10 = _a.sent(); + QUnit.ok(e_10 === "error", "Catched exception: " + e_10); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 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("Throw before yield", function () { + Promise.resolve(spawn(function () { + return __generator(this, function (_a) { + try { + throw "error"; + } + catch (e) { + QUnit.ok(e === "error", "Catched exception: " + e); + } + return [2 /*return*/, 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(function () { + var e_11; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, new Promise(function (resolve, reject) { reject("fault fault!"); })]; + case 1: + _a.sent(); + QUnit.ok(false, "Shouldn't come here"); + return [3 /*break*/, 3]; + case 2: + e_11 = _a.sent(); + QUnit.ok(e_11 === "fault fault!", "Catched exception: " + e_11); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 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 in an array", function () { + spawn(function () { + var e_12; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, [1, 2, new Promise(function (resolve, reject) { reject("fault fault!"); }), 4]]; + case 1: + _a.sent(); + QUnit.ok(false, "Shouldn't come here"); + return [3 /*break*/, 3]; + case 2: + e_12 = _a.sent(); + QUnit.ok(e_12 === "fault fault!", "Catched exception: " + e_12); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 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("Should allow returning a promise", function () { + spawn(function () { + return __generator(this, function (_a) { + return [2 /*return*/, Promise.resolve(3)]; + }); + }).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(function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve(3)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }).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(function () { + var x, y; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, [1, 2, Promise.resolve(3)]]; + case 1: + x = _a.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(); + return [2 /*return*/]; + } + }); +})); +QUnit.asyncTest("Calling sub async function", async$2(function () { + var addFriend, deleteFriends, foo, bar, numDeleted, e_13; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + addFriend = async$2(function addFriend(friend) { + var friendId; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$4.friends.add(friend)]; + case 1: + friendId = _a.sent(); + return [4 /*yield*/, db$4.friends.get(friendId)]; + case 2: return [2 /*return*/, _a.sent()]; + } + }); + }); + deleteFriends = async$2(function deleteFriends() { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$4.friends.where('name').anyOf("Foo", "Bar").delete()]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); + _a.label = 1; + case 1: + _a.trys.push([1, 5, 6, 7]); + return [4 /*yield*/, addFriend({ name: "Foo" })]; + case 2: + foo = _a.sent(); + return [4 /*yield*/, addFriend({ name: "Bar" })]; + case 3: + bar = _a.sent(); + QUnit.ok(foo.name == "Foo", "Foo got its name"); + QUnit.ok(bar.name == "Bar", "Bar got its name"); + return [4 /*yield*/, deleteFriends()]; + case 4: + numDeleted = _a.sent(); + QUnit.ok(true, numDeleted + " friends successfully deleted"); + return [3 /*break*/, 7]; + case 5: + e_13 = _a.sent(); + QUnit.ok(false, e_13); + return [3 /*break*/, 7]; + case 6: + QUnit.start(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); +})); + +var keys = Object.keys; +var isArray = Array.isArray; +var _global = typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; +if (typeof Promise !== 'undefined' && !_global.Promise) { + // In jsdom, this it can be the case that Promise is not put on the global object. + // If so, we need to patch the global object for the rest of the code to work as expected. + // Other dexie code expects Promise to be on the global object (like normal browser environments) + _global.Promise = Promise; +} +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]); + }); +} +var defineProperty = Object.defineProperty; +function setProp(obj, prop, functionOrGetSet, options) { + 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); + var proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); +} + + + + + +/** 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 tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } + catch (ex) { + onerror && onerror(ex); + } +} + + + + +var concat = [].concat; +function flatten(a) { + return concat.apply([], a); +} +//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm +var intrinsicTypeNames = "Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set" + .split(',').concat(flatten([8, 16, 32, 64].map(function (num) { return ["Int", "Uint", "Float"].map(function (t) { return t + num + "Array"; }); }))).filter(function (t) { return _global[t]; }); +var intrinsicTypes = intrinsicTypeNames.map(function (t) { return _global[t]; }); +var intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, function (x) { return [x, true]; }); + + + + +// 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; +} + +function nop() { } +function mirror(val) { return val; } + +function callBoth(on1, on2) { + return function () { + on1.apply(this, arguments); + on2.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); + +var libraryFilter = function () { return true; }; +var NEEDS_THROW_FOR_STACK = !new Error("").stack; +function getErrorWithStack() { + 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. + 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(''); +} +// TODO: Replace this in favor of a decorator instead. + +var dexieErrorNames = [ + 'Modify', + 'Bulk', + 'OpenFailed', + 'VersionChange', + 'Schema', + 'Upgrade', + 'InvalidTable', + 'MissingAPI', + 'NoSuchDatabase', + 'InvalidArgument', + 'SubTransaction', + 'Unsupported', + 'Internal', + 'DatabaseClosed', + 'PrematureCommit', + 'ForeignAwait' +]; +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: " + Object.keys(failures) + .map(function (key) { return failures[key].toString(); }) + .filter(function (v, i, s) { return s.indexOf(v) === i; }) // Only unique error strings + .join('\n'); +} +// +// ModifyError - thrown in Collection.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; + this.message = getMultiErrorMessage(msg, failures); +} +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 + (!inner ? '' : '\n ' + inner); + 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; +}, {}); + +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; + +/* + * Copyright (c) 2014-2017 David Fahlander + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0 + */ +// +// Promise and Zone (PSD) 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. +// +// 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 micro-task, but have an own micro-task +// engine that is indexedDB compliant across all browsers. +// 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: +// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as +// native async / await. +// * Promise.follow() method built upon the custom zone engine, 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 ZONE_ECHO_LIMIT = 100; +var _a = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, globalP.__proto__, globalP]; + // Generate a native promise (as window.Promise may have been patched) + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + nativeP.__proto__, + globalP + ]; + })(); +var resolvedNativePromise = _a[0]; +var nativePromiseProto = _a[1]; +var resolvedGlobalPromise = _a[2]; +var nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +var NativePromise$1 = resolvedNativePromise && resolvedNativePromise.constructor; +var patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +/* The default 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 + indexedDB-compatible emulated micro task loop. +*/ +var schedulePhysicalTick = resolvedGlobalPromise ? + function () { resolvedGlobalPromise.then(physicalTick); } + : + _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); }; +// Configurable 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 = myFuncThatThrowsException +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 = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + pgp: false, + env: {}, + 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. +function DexiePromise(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) + } + 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); +} +// Prepare a property descriptor to put onto Promise.prototype.then +var thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + if (possibleAwait) + decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; // For idempotense, see setter below. + return then; + }, + // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then + // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor. + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : // Restore to original property descriptor. + { + get: function () { + return value; // Getter returning provided value (behaves like value is just changed) + }, + set: thenProp.set // Keep a setter that is prepared to restore original. + }); + } +}; +props(DexiePromise.prototype, { + then: thenProp, + _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, PSD)); + }, + 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) { + // Catching errors by its constructor type (similar to java / c++ / c#) + // Sample: promise.catch(TypeError, function (e) { ... }); + return err instanceof type ? handler(err) : PromiseReject(err); + }) + : this.then(null, function (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) { ... }); + return 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); + }); + }, + 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; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? + new DexiePromise(function (resolve, reject) { + var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms); + _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } +}); +if (typeof Symbol !== 'undefined' && Symbol.toStringTag) + setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); +// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env. +// Environment globals snapshotted on leaving global zone +globalPSD.env = snapShot(); +function Listener(onFulfilled, onRejected, resolve, reject, zone) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = zone; +} +// Promise Static Properties +props(DexiePromise, { + all: function () { + var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like. + .map(onPossibleParallellAsync); // Handle parallell async/awaits + return new DexiePromise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + values.map(function (value) { return DexiePromise.resolve(value).then(resolve, reject); }); + }); + }, + PSD: { + get: function () { return PSD; }, + set: function (value) { return PSD = value; } + }, + //totalEchoes: {get: ()=>totalEchoes}, + //task: {get: ()=>task}, + 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, zoneProps) { + return new DexiePromise(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 _this = 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 () { + _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } +}); +if (NativePromise$1) { + if (NativePromise$1.allSettled) + setProp(DexiePromise, "allSettled", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve) { + if (possiblePromises.length === 0) + resolve([]); + var remaining = possiblePromises.length; + var results = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) + .then(function () { return --remaining || resolve(results); }); }); + }); + }); + if (NativePromise$1.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + var remaining = possiblePromises.length; + var failures = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + }); }); + }); + }); +} +/** +* 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; // Already settled + 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 DexiePromise ? + 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); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap$1(callListener, [cb, promise, listener]); +} +function callListener(cb, promise, listener) { + try { + // 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 ret, value = promise._value; + if (promise._state) { + // cb is onResolved + ret = cb(value); + } + else { + // cb is onRejected + 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 env and currentFulfiller. + currentFulfiller = null; + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + --listener.psd.ref || listener.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; + } +} +function PromiseReject(reason) { + return new DexiePromise(INTERNAL, false, reason); +} + +// +// variables used for native await support +// +var task = { awaits: 0, echoes: 0, id: 0 }; // The ongoing macro-task when using zone-echoing. +var taskCounter = 0; // ID counter for macro tasks. +var zoneStack = []; // Stack of left zones to restore asynchronically. +var zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions. +var totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then. +var zone_id_counter = 0; +function newScope(fn, props$$1, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + // Prepare for promise patching (done in usePSD): + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: DexiePromise, + PromiseProp: { value: DexiePromise, configurable: true, writable: true }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) // global then + } : {}; + if (props$$1) + extend(psd, props$$1); + // 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); + if (psd.ref === 0) + psd.finalize(); + return rv; +} +// Function to call if scopeFunc returns NativePromise +// Also for each NativePromise in the arguments to Promise.all() +function incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; +} +// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called. +// Also call this when a native await calls then method on a promise. In that case, don't supply +// sourceTaskId because we already know it refers to current task. +function decrementExpectedAwaits(sourceTaskId) { + if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) + return; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0. +} +if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + // If the native promise' prototype is patched, we cannot rely on zone echoing. + // Disable that here: + incrementExpectedAwaits = decrementExpectedAwaits = nop; +} +// Call from Promise.all() and Promise.race() +function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise$1) { + incrementExpectedAwaits(); + return possiblePromise.then(function (x) { + decrementExpectedAwaits(); + return x; + }, function (e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; +} +function zoneEnterEcho(targetZone) { + ++totalEchoes; + //console.log("Total echoes ", totalEchoes); + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.id = 0; // Cancel zone echoing. + } + zoneStack.push(PSD); + switchToZone(targetZone, true); +} +function zoneLeaveEcho() { + var zone = zoneStack[zoneStack.length - 1]; + zoneStack.pop(); + switchToZone(zone, false); +} +function switchToZone(targetZone, bEnteringZone) { + var currentZone = PSD; + if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { + // Enter or leave zone asynchronically as well, so that tasks initiated during current tick + // will be surrounded by the zone when they are invoked. + enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; // The actual zone switch occurs at this line. + // Snapshot on every leave from global zone. + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + // Let's patch the global and native Promises (may be same or may be different) + var GlobalPromise_1 = globalPSD.env.Promise; + // Swich environments (may be PSD-zone or the global zone. Both apply.) + var targetEnv = targetZone.env; + // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed) + // Must be done on each zone change because the patched method contains targetZone in its closure. + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise_1.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + // Leaving or entering global zone. It's time to patch / restore global Promise. + // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular. + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might + // not be accessing global.Promise but a local reference to it) + GlobalPromise_1.all = targetEnv.all; + GlobalPromise_1.race = targetEnv.race; + GlobalPromise_1.resolve = targetEnv.resolve; + GlobalPromise_1.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise_1.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise_1.any = targetEnv.any; + } + } +} +function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + resolve: GlobalPromise.resolve, + reject: GlobalPromise.reject, + nthen: nativePromiseProto.then, + gthen: GlobalPromise.prototype.then + } : {}; +} +function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + switchToZone(psd, true); + return fn(a1, a2, a3); + } + finally { + switchToZone(outerScope, false); + } +} +function enqueueNativeMicroTask(job) { + // + // Precondition: nativePromiseThen !== undefined + // + nativePromiseThen.call(resolvedNativePromise, job); +} +function nativeAwaitCompatibleWrap(fn, zone, possibleAwait) { + return typeof fn !== 'function' ? fn : function () { + var outerZone = PSD; + if (possibleAwait) + incrementExpectedAwaits(); + switchToZone(zone, true); + try { + return fn.apply(this, arguments); + } + finally { + switchToZone(outerZone, false); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone, false), nativeAwaitCompatibleWrap(onRejected, zone, false)); + }; +} +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 (debug && event && !event.defaultPrevented) { + console.warn("Unhandled rejection: " + (err.stack || err)); + } + } + catch (e) { } +} +var rejection = DexiePromise.reject; + +var _resolve = NativePromise$1.resolve.bind(NativePromise$1); +var _then = NativePromise$1.prototype.then; +var IdbPromiseIncompatibleError = /** @class */ (function (_super) { + __extends(IdbPromiseIncompatibleError, _super); + function IdbPromiseIncompatibleError() { + var _this = _super.call(this, "IndexedDB and Promise are incompatible on this browser") || this; + _this.name = "IdbPromiseIncompatibleError"; + return _this; + } + return IdbPromiseIncompatibleError; +}(Error)); +function isIdbAndPromiseCompatible() { + return __awaiter(this, void 0, void 0, function () { + var db; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie("idbPromiseCompatTest"); + db.version(1).stores({ foo: 'bar' }); + return [4 /*yield*/, db.transaction('r', db.foo, function () { return __awaiter(_this, void 0, void 0, function () { + var x, p, i, result, ex_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.foo.count()]; + case 1: + x = _a.sent(); + p = _resolve(0); + for (i = 0; i < 10; ++i) { + p = _then.call(p, function (x) { return x + 1; }); + } + return [4 /*yield*/, p]; + case 2: + result = _a.sent(); + console.log("Result: " + result + " (should be 10"); + _a.label = 3; + case 3: + _a.trys.push([3, 5, , 6]); + return [4 /*yield*/, db.foo.count()]; + case 4: + _a.sent(); + db.close(); + return [2 /*return*/, true]; + case 5: + ex_1 = _a.sent(); + db.close(); + throw new IdbPromiseIncompatibleError(); + case 6: return [2 /*return*/]; + } + }); + }); })]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); +} + +var idbAndPromiseCompatible = isIdbAndPromiseCompatible(); +var hasNativeAsyncFunctions = false; +try { + hasNativeAsyncFunctions = !!new Function("return (async ()=>{})();")().then; +} +catch (e) { } +var db$5 = new Dexie("TestDBTranx"); +db$5.version(1).stores({ + items: "id" +}); +QUnit.module("asyncawait", { + setup: function (assert) { + var done = assert.async(); + resetDatabase(db$5).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(done); + }, + teardown: function () { + } +}); +QUnit.test("Should be able to use global Promise within transaction scopes", function (assert) { + var done = assert.async(); + db$5.transaction('rw', db$5.items, function (trans) { + return window.Promise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$5.items.add({ id: "foobar" }); + }).then(function () { + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie.currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$5.items.get('foobar'); + }); + }).then(function (foobar) { + QUnit.equal(foobar.id, 'foobar', "Transaction should have lived throughout the Promise.resolve() chain"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + (e.stack || e)); + }).finally(done); +}); +QUnit.test("Should be able to use native async await", function (assert) { + var done = assert.async(); + Dexie.Promise.resolve(idbAndPromiseCompatible).then(function () { + var f = new Function('ok', 'equal', 'Dexie', 'db', "return db.transaction('rw', db.items, async ()=>{\n let trans = Dexie.currentTransaction;\n ok(!!trans, \"Should have a current transaction\");\n await db.items.add({id: 'foo'});\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of Dexie.Promise\");\n await Dexie.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of Dexie.Promise synch\");\n await window.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of global Promise\");\n await 3;\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of primitive(!)\");\n await db.transaction('r', db.items, async innerTrans => {\n ok(!!innerTrans, \"SHould have inner transaction\");\n equal(Dexie.currentTransaction, innerTrans, \"Inner transaction should be there\");\n equal(innerTrans.parent, trans, \"Parent transaction should be correct\");\n let x = await db.items.get(1);\n ok(Dexie.currentTransaction === innerTrans, \"Transaction persisted in inner transaction\");\n });\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of sub transaction\");\n await (async ()=>{\n return await db.items.get(1);\n })();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of async function\");\n await (async ()=>{\n await Promise.all([db.transaction('r', db.items, async() => {\n await db.items.get(1);\n await db.items.get(2);\n }), db.transaction('r', db.items, async() => {\n return await db.items.get(1);\n })]);\n })();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of async function 2\");\n\n await window.Promise.resolve().then(()=>{\n ok(Dexie.currentTransaction === trans, \"Transaction persisted after window.Promise.resolve().then()\");\n return (async ()=>{})(); // Resolve with native promise\n }).then(()=>{\n ok(Dexie.currentTransaction === trans, \"Transaction persisted after native promise completion\");\n return window.Promise.resolve();\n }).then(()=>{\n ok(Dexie.currentTransaction === trans, \"Transaction persisted after window.Promise.resolve().then()\");\n return (async ()=>{})();\n });\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of mixed promises\");\n \n try {\n let foo = await db.items.get('foo');\n ok(true, \"YOUR BROWSER HAS COMPATIBILITY BETWEEN NATIVE PROMISES AND INDEXEDDB!\");\n } catch (e) {\n ok(true, \"Browser has no compatibility between native promises and indexedDB.\");\n }\n })"); + return f(QUnit.ok, QUnit.equal, Dexie, db$5); + }).catch('IdbPromiseIncompatibleError', function (e) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails in idb transaction by reality"); + }).catch(function (e) { + if (hasNativeAsyncFunctions) + QUnit.ok(false, "Error: " + (e.stack || e)); + else + QUnit.ok(true, "This browser does not support native async functions"); + }).then(done); +}); +QUnit.test("Should be able to use native async await from upgrade handler (issue #612)", function (assert) { + var done = assert.async(); + Dexie.Promise.resolve(idbAndPromiseCompatible).then(function () { + var f = new Function('ok', 'equal', 'Dexie', "\n return Dexie.delete('issue612').then(async ()=>{\n const log = [];\n const db = new Dexie('issue612');\n db.version(1).stores({foo: 'id'});\n await db.open();\n await db.foo.add({id: 1, name: \"Foo Bar\"});\n db.close();\n db.version(2).stores({foo: 'id, firstName, lastName'}).upgrade(async tx => {\n log.push(\"2:1\");\n await tx.foo.toCollection().modify(x => {\n const [firstName, lastName] = x.name.split(' ');\n x.firstName = firstName;\n x.lastName = lastName;\n ++x.v\n });\n log.push(\"2:2\");\n });\n db.version(3).upgrade(async tx => {\n log.push(\"3:1\");\n await tx.foo.toArray();\n log.push(\"3:2\");\n });\n await db.open();\n const count = await db.foo.where({firstName: 'Foo'}).count();\n equal(count, 1, \"Should find base on the upgraded index\");\n equal(log.join(','), \"2:1,2:2,3:1,3:2\", \"Execution order of upgraders should be correct\");\n db.close();\n });"); + return f(QUnit.ok, QUnit.equal, Dexie); + }).catch('IdbPromiseIncompatibleError', function (e) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails in idb transaction by reality"); + }).catch(function (e) { + if (hasNativeAsyncFunctions) + QUnit.ok(false, "Error: " + (e.stack || e)); + else + QUnit.ok(true, "This browser does not support native async functions"); + }).then(function () { + return Dexie.delete("issue612"); + }).then(done); +}); +var NativePromise$2 = (function () { + try { + return new Function("return (async ()=>{})().constructor")(); + } + catch (e) { + return window.Promise; + } +})(); +QUnit.test("Must not leak PSD zone", function (assert) { + return __awaiter(this, void 0, void 0, function () { + var done, compatiblity, F; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + done = assert.async(); + return [4 /*yield*/, idbAndPromiseCompatible.catch(function (e) { + return false; + })]; + case 1: + compatiblity = _a.sent(); + if (!compatiblity) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\""); + done(); + return [2 /*return*/]; + } + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + done(); + return [2 /*return*/]; + } + F = new Function('ok', 'equal', 'Dexie', 'db', "\n ok(Dexie.currentTransaction === null, \"Should not have an ongoing transaction to start with\");\n var trans1, trans2;\n var p1 = db.transaction('r', db.items, async ()=> {\n var trans = trans1 = Dexie.currentTransaction;\n await db.items.get(1); // Just to prohibit IDB bug in Safari - must use transaction in initial tick!\n await 3;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.0 - after await 3\");\n await 4;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.0 - after await 4\");\n await 5;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.0 - after await 5\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.1 - after db.items.get(1)\");\n await 6;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.1 - after await 6\");\n await subFunc(1);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.2 - after async subFunc()\");\n await Promise.all([subFunc(11), subFunc(12), subFunc(13)]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.3 - after Promise.all()\");\n await subFunc2_syncResult();\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.4 - after async subFunc_syncResult()\");\n await Promise.all([subFunc2_syncResult(), subFunc2_syncResult(), subFunc2_syncResult()]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.5 - after Promise.all(sync results)\");\n });\n var p2 = db.transaction('r', db.items, async ()=> {\n var trans = trans2 = Dexie.currentTransaction;\n await db.items.get(1); // Just to prohibit IDB bug in Safari - must use transaction in initial tick!\n ok(trans1 !== trans2, \"Parallell transactions must be different from each other\");\n await 3;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.0 - after await 3\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.1 - after db.items.get(1)\");\n await subFunc(2);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.2 - after async subFunc()\");\n await Promise.all([subFunc(21), subFunc(22), subFunc(23)]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.3 - after Promise.all()\");\n await subFunc2_syncResult();\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.4 - after async subFunc_syncResult()\");\n await Promise.all([subFunc2_syncResult(), subFunc2_syncResult(), subFunc2_syncResult()]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.5 - after Promise.all(sync results)\");\n });\n //var p2 = Promise.resolve();\n ok(Dexie.currentTransaction === null, \"Should not have an ongoing transaction after transactions\");\n\n async function subFunc(n) {\n await 3;\n let result = await db.items.get(2);\n return result;\n }\n\n async function subFunc2_syncResult() {\n let result = await 3;\n return result;\n }\n \n return Promise.all([p1, p2]);\n "); + F(QUnit.ok, QUnit.equal, Dexie, db$5).catch(function (e) { return QUnit.ok(false, e.stack || e); }).then(done); + return [2 /*return*/]; + } + }); + }); +}); +QUnit.test("Must not leak PSD zone2", function (assert) { + return __awaiter(this, void 0, void 0, function () { + var done; + return __generator(this, function (_a) { + done = assert.async(); + QUnit.ok(Dexie.currentTransaction === null, "Should not have an ongoing transaction to start with"); + db$5.transaction('rw', db$5.items, function () { + var trans = Dexie.currentTransaction; + QUnit.ok(trans !== null, "Should have a current transaction"); + var otherZonePromise; + Dexie.ignoreTransaction(function () { + QUnit.ok(Dexie.currentTransaction == null, "No Transaction in this zone"); + function promiseFlow() { + return NativePromise$2.resolve().then(function () { + if (Dexie.currentTransaction !== null) + QUnit.ok(false, "PSD zone leaked"); + return new NativePromise$2(function (resolve) { return NativePromise$2.resolve().then(resolve); }); + }); + } + + otherZonePromise = promiseFlow(); + for (var i = 0; i < 100; ++i) { + otherZonePromise = otherZonePromise.then(promiseFlow); + } + }); + // In parallell with the above 2*100 async tasks are being executed and verified, + // maintain the transaction zone below: + return db$5.items.get(1).then(function () { + return idbAndPromiseCompatible; + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 1"); + // Make sure native async functions maintains the zone: + var f = new Function('ok', 'equal', 'Dexie', 'trans', 'NativePromise', 'db', "return (async ()=>{\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.1\");\n await Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.2\");\n await Dexie.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.3\");\n await window.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.4\");\n await db.items.get(1);\n })()"); + return f(QUnit.ok, QUnit.equal, Dexie, trans, NativePromise$2, db$5); + }).catch(function (e) { + // Could not test native async functions in this browser. + if (e.name === 'IdbPromiseIncompatibleError') { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + } + else if (hasNativeAsyncFunctions) + QUnit.ok(false, "Error: " + (e.stack || e)); + else + QUnit.ok(true, "This browser does not support native async functions"); + }).then(function () { + // NativePromise + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 2"); + return Promise.resolve(); + }).then(function () { + // window.Promise + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 3"); + return Dexie.Promise.resolve(); + }).then(function () { + // Dexie.Promise + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 4"); + return otherZonePromise; // wait for the foreign zone promise to complete. + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 5"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + (e.stack || e)); + }).then(done); + return [2 /*return*/]; + }); + }); +}); +QUnit.test("Should be able to await Promise.all()", function (assert) { return __awaiter(void 0, void 0, void 0, function () { + var done, compatible; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + done = assert.async(); + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + done(); + return [2 /*return*/]; + } + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { return false; })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + done(); + return [2 /*return*/]; + } + (new Function('ok', 'equal', 'Dexie', 'db', "return db.transaction('r', db.items, async (trans)=>{\n ok(Dexie.currentTransaction === trans, \"Correct initial transaction.\");\n await db.items.get(1); // Just to prohibit IDB bug in Safari - must use transaction in initial tick!\n var promises = [];\n for (var i=0; i<50; ++i) {\n promises.push(subAsync1(trans));\n }\n for (var i=0; i<50; ++i) {\n promises.push(subAsync2(trans));\n }\n await Promise.all(promises);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1 - after await Promise.all([100 promises...]);\");\n await Promise.all([1,2,3, db.items.get(2)]);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 2 - after Promise.all(1,2,3,db.items.get(2))\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 3 - after await db.items.get(1);\");\n await 3;\n ok(Dexie.currentTransaction === trans, \"Still same transaction 4 - after await 3;\");\n });\n\n async function subAsync1 (trans) {\n await 1;\n await 2;\n await 3;\n if (Dexie.currentTransaction !== trans) ok(false, \"Not in transaction\");\n }\n\n async function subAsync2 (trans) {\n await 1;\n await 2;\n if (Dexie.currentTransaction !== trans) ok(false, \"Not in transaction 2\");\n await db.items.get(1);\n }\n "))(QUnit.ok, QUnit.equal, Dexie, db$5) + .catch(function (e) { + QUnit.ok(false, e.stack || e); + }).then(done); + return [2 /*return*/]; + } + }); +}); }); +spawnedTest("Should use Promise.all where applicable", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { + var x, all; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve(3)]; + case 1: + x = _a.sent(); + return [4 /*yield*/, db$5.items.bulkAdd([{ id: 'a' }, { id: 'b' }])]; + case 2: + _a.sent(); + return [4 /*yield*/, Promise.all([db$5.items.get('a'), db$5.items.get('b')])]; + case 3: + all = _a.sent(); + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + return [4 /*yield*/, Promise.all([db$5.items.get('a'), db$5.items.get('b')])]; + case 4: + all = _a.sent(); + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + return [2 /*return*/]; + } + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("Even when keeping a reference to global Promise, still maintain PSD zone states", function () { + var Promise; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + Promise = window.Promise; + return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { + var trans = Dexie.currentTransaction; + QUnit.ok(trans !== null, "Have a transaction"); + return Promise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still have the same current transaction."); + return Promise.resolve().then(function () { return Promise.resolve(); }); + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still have the same current transaction after multiple global.Promise.resolve() calls"); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("Sub Transactions with async await", function () { + var compatible, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { return false; })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return [2 /*return*/]; + } + return [4 /*yield*/, new Function('equal', 'ok', 'Dexie', 'db', "return (async ()=>{\n await db.items.bulkAdd([{id: 1}, {id:2}, {id: 3}]);\n let result = await db.transaction('rw', db.items, async ()=>{\n let items = await db.items.toArray();\n let numItems = await db.transaction('r', db.items, async ()=>{\n equal(await db.items.count(), await db.items.count(), \"Two awaits of count should equal\");\n equal(await db.items.count(), 3, \"Should be 3 items\");\n return await db.items.count();\n });\n let numItems2 = await db.transaction('r', db.items, async ()=>{\n equal(await db.items.count(), await db.items.count(), \"Two awaits of count should equal\");\n equal(await db.items.count(), 3, \"Should be 3 items\");\n return await db.items.count();\n });\n equal (numItems, numItems2, \"The total two inner transactions should be possible to run after each other\");\n return numItems;\n });\n equal (result, 3, \"Result should be 3\");\n })();")(QUnit.equal, QUnit.ok, Dexie, db$5)]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + QUnit.ok(e_1.name === 'SyntaxError', "No support for native async functions in this browser"); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); +}); +promisedTest("Should patch global Promise within transaction scopes but leave them intact outside", function () { return __awaiter(void 0, void 0, void 0, function () { + var GlobalPromise; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(Promise !== Dexie.Promise, "At global scope. Promise should not be Dexie.Promise"); + QUnit.ok(window.Promise !== Dexie.Promise, "At global scope. Promise should not be Dexie.Promise"); + GlobalPromise = window.Promise; + return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + QUnit.ok(Promise === Dexie.Promise, "Within transaction scope, Promise should be Dexie.Promise."); + QUnit.ok(window.Promise === Dexie.Promise, "Within transaction scope, window.Promise should be Dexie.Promise."); + QUnit.ok(GlobalPromise !== Promise, "Promises are different"); + QUnit.ok(GlobalPromise.resolve === Promise.resolve, "If holding a reference to the real global promise and doing Promise.resolve() it should be Dexie.Promise.resolve withing transaction scopes"); + QUnit.ok(GlobalPromise.reject === Promise.reject, "If holding a reference to the real global promise and doing Promise.reject() it should be Dexie.Promise.reject withing transaction scopes"); + QUnit.ok(GlobalPromise.all === Promise.all, "If holding a reference to the real global promise and doing Promise.all() it should be Dexie.Promise.all withing transaction scopes"); + QUnit.ok(GlobalPromise.race === Promise.race, "If holding a reference to the real global promise and doing Promise.race() it should be Dexie.Promise.race withing transaction scopes"); + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Should be able to use transpiled async await", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { return __awaiter(void 0, void 0, void 0, function () { + var trans; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + trans = Dexie.currentTransaction; + QUnit.ok(!!trans, "Should have a current transaction"); + return [4 /*yield*/, db$5.items.add({ id: 'foo' })]; + case 1: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of Dexie.Promise"); + return [4 /*yield*/, Promise.resolve()]; + case 2: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of Promise.resolve()"); + return [4 /*yield*/, 3]; + case 3: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after await 3"); + return [4 /*yield*/, db$5.transaction('r', db$5.items, function (innerTrans) { return __awaiter(void 0, void 0, void 0, function () { + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(!!innerTrans, "Should have inner transaction"); + QUnit.equal(Dexie.currentTransaction, innerTrans, "Inner transaction should be there"); + QUnit.equal(innerTrans.parent, trans, "Parent transaction should be correct"); + return [4 /*yield*/, db$5.items.get(1)]; + case 1: + x = _a.sent(); + QUnit.ok(Dexie.currentTransaction === innerTrans, "Transaction persisted in inner transaction"); + return [2 /*return*/]; + } + }); + }); })]; + case 4: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of sub transaction"); + return [4 /*yield*/, (function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$5.items.get(1)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); })()]; + case 5: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of async function"); + return [4 /*yield*/, (function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all([db$5.transaction('r', db$5.items, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$5.items.get(1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$5.items.get(2)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }), db$5.transaction('r', db$5.items, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$5.items.get(1)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); })])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })()]; + case 6: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of async function 2"); + return [4 /*yield*/, Promise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after window.Promise.resolve().then()"); + return (function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); })(); // Resolve with native promise + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after native promise completion"); + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after window.Promise.resolve().then()"); + return (function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); })(); + })]; + case 7: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of mixed promises"); + return [2 /*return*/]; + } + }); + }); }).catch('PrematureCommitError', function () { + QUnit.ok(true, "PROMISE IS INCOMPATIBLE WITH INDEXEDDB (https://github.com/dfahlander/Dexie.js/issues/317). Ignoring test."); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Should be able to use some simpe native async await even without zone echoing ", function () { return __awaiter(void 0, void 0, void 0, function () { + var compatible; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + return [2 /*return*/]; + } + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { return false; })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return [2 /*return*/]; + } + return [4 /*yield*/, (new Function('ok', 'equal', 'Dexie', 'db', "return db.transaction('r', db.items, trans=> (async (trans) => {\n ok(Dexie.currentTransaction === trans, \"Correct initial transaction.\");\n await Promise.all([1,2,3, db.items.get(2), Promise.resolve()]);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1 - after Promise.all(1,2,3,db.items.get(2))\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 2 - after await db.items.get(1);\");\n })(trans));"))(QUnit.ok, QUnit.equal, Dexie, db$5)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }); +var GlobalPromise = window.Promise; +promisedTest("Should behave outside transactions as well", function () { return __awaiter(void 0, void 0, void 0, function () { + var compatible; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + return [2 /*return*/]; + } + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { return false; })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return [2 /*return*/]; + } + return [4 /*yield*/, (new Function('ok', 'equal', 'Dexie', 'db', 'GlobalPromise', "async function doSomething() {\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n ok(window.Promise !== Dexie.Promise, \"window.Promise should be original\");\n ok(window.Promise === GlobalPromise, \"window.Promise should be original indeed\");\n await db.items.get(1);\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n await 3;\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n await db.items.put({id:1, aj: \"aj\"});\n ok(true, \"Could put an item\");\n await db.items.update(1, {aj: \"oj\"});\n ok(true, \"Could query an item\");\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n await 4;\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n }\n\n return doSomething();\n "))(QUnit.ok, QUnit.equal, Dexie, db$5, GlobalPromise)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }); + +var db$6 = new Dexie("TestDBException"); +db$6.version(1).stores({ users: "id,first,last,&username,&*email,*pets" }); +db$6.on("populate", function (trans) { + db$6.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$6.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$6).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. + if (!supports("domevents")) { + QUnit.ok(true, "Skipping - DOM events not supported"); + QUnit.start(); + } + var onErrorSignals = 0; + function onerror(ev) { + ++onErrorSignals; + ev.preventDefault(); + } + var prevUnhandledRejection = window.onunhandledrejection; + window.onunhandledrejection = onerror; + db$6.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", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, db$6.transaction("rw", db$6.users, function () { + var id; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$6.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" })]; + case 1: + id = _a.sent(); + QUnit.equal(id, 3); + return [4 /*yield*/, db$6.users.where('id').equals(null).toArray()]; + case 2: + _a.sent(); + QUnit.ok(false, "Should not come here"); + return [2 /*return*/]; + } + }); + }).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw DataError: " + e); + })]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$6.users.where('first').equals("Foo").count()]; + case 2: + _a.apply(void 0, [_c.sent(), 0, "Should not have succeeded to add when transaction was aborted"]); + return [4 /*yield*/, db$6.transaction("rw", db$6.users, function () { + db$6.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" }); + db$6.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 3: + _c.sent(); + _b = QUnit.equal; + return [4 /*yield*/, db$6.users.where('first').equals("Foo").count()]; + case 4: + _b.apply(void 0, [_c.sent(), 0, "Should not have succeeded to add when transaction was aborted"]); + return [2 /*return*/]; + } + }); +}); +QUnit.asyncTest("eventError-transaction-catch", function () { + db$6.transaction("rw", db$6.users, function () { + db$6.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$6.transaction("rw", db$6.users, function () { + db$6.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$6.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$6.transaction("r", db$6.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$6.transaction("r", db$6.users, function () { + db$6.users.where("username").equals("apa").toArray(function () { + db$6.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$6.users.hook('deleting', deletingHook); + db$6.transaction('rw', db$6.users, function () { + function deleteKarls() { + db$6.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }); + } + db$6.users.delete(1); + deleteKarls(); + }).then(function () { + QUnit.ok(false, "Transaction should not complete!"); + }).catch(function (err) { + QUnit.ok(true, "Transaction aborted"); + }).finally(function () { + db$6.users.hook('deleting').unsubscribe(deletingHook); + QUnit.start(); + }); +}); +QUnit.asyncTest("exceptionThrown-iteration-should-not-abort-when-using-hook", function () { + db$6.users.hook('deleting', function () { + // Testing with + }); + db$6.transaction('rw', db$6.users, function () { + function deleteKarls() { + db$6.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }).catch(function (err) { + // Catching error should prevent transaction from aborting. + }); + } + db$6.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("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$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.transaction('rw', db$6.users, function () { + db$6.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$6.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 #67 - Regression test 2 - other error in key", function () { + db$6.transaction('rw', db$6.users, function () { + db$6.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$6.users.where('first').above(false).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 () { + if (!supports("domevents")) { + QUnit.ok(true, "Skipping - DOM events not supported"); + QUnit.start(); + } + 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! + }); + Dexie.Promise.resolve(Promise.reject(new Error("Converting a rejected standard promise to Dexie.Promise but don't catch it"))) + .finally(function () { + // With finally, it should yet trigger the global event: + return 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 new Error("FOO"); // Here a generic error is thrown (not a DB error) + //console.log("after"); + }); + db.delete().finally(function () { + QUnit.equal(errorList.length, 6, "THere should be 6 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].message, "Converting a rejected standard promise to Dexie.Promise but don't catch it", "Converting a rejected standard promise to Dexie.Promise but don't catch it"); + QUnit.equal(errorList[4], "forth error (uncatched but with finally)", "forth error (uncatched but with finally)"); + QUnit.equal(errorList[5].message, "FOO", "FOO"); + errorList.slice(6).map(function (e, i) { return "Unexpected error: " + ((i + 6) + ": " + e.stack); }).forEach(function (txt) { + console.error(txt); + QUnit.ok(false, txt); + }); + // cleanup: + window.removeEventListener('unhandledrejection', globalRejectionHandler); + QUnit.start(); + }); + }); + }); +}); + +QUnit.module("upgrading"); +var Promise$1 = Dexie.Promise; +// tests: +// * separate tests with a commented line of --- up to column 80. +// * put test result checking as a then of the relevant db.open call. +// * db.close at the top of a new section. +// another top-level then should indicate another part of the sequence +// of upgrade actions. +// put db.delete() in its own clause. +QUnit.test("upgrade", function (assert) { + var done = assert.async(); + // 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; + // Instead of expecting an empty database to have 0 tables, we read + // how many an empty database has. + // Reason: Addons may add meta tables. + var baseNumberOfTables = 0; + var baseTables = []; + // Ensure Dexie verno and backing IDB version are as expected. + function checkVersion(version) { + QUnit.equal(db.verno, version, "DB should be version " + version); + QUnit.equal(db.backendDB().version, version * 10, "idb should be version " + version * 10); + } + // Ensure object store names are as expected. + function checkObjectStores(expected) { + // Add baseTables. + expected = expected.concat(baseTables).sort(); + // Already sorted. + var idbNames = [].slice.call(db.backendDB().objectStoreNames); + var dexieNames = db.tables.map(function (t) { return t.name; }).sort(); + QUnit.deepEqual(dexieNames, expected, "Dexie.tables must match expected."); + if (supports("deleteObjectStoreAfterRead")) { + // Special treatment for IE/Edge where Dexie avoids deleting the actual store to avoid a bug. + // This special treatment in the unit tests may not need to be here if we can work around Dexie issue #1. + QUnit.deepEqual(idbNames, expected, "IDB object stores must match expected."); + } + } + Promise$1.resolve(function () { + return Dexie.delete(DBNAME); + }).then(function () { + // -------------------------------------------------------------------- + // Test: 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"); + // Set so add-on tables don't invalidate checks. + baseNumberOfTables = db.tables.length; + baseTables = db.tables.map(function (t) { return t.name; }); + }); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Adding version. + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 2"); + checkVersion(2); + //equal(db.verno, 2, "DB should be version 2"); + QUnit.equal(db.table("store1").schema.primKey.name, "id", "Primary key is 'id'"); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Adding an index to a store + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + // Adding the name index + db.version(3).stores({ store1: "++id,name" }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 3 (adding an index to a store)"); + checkVersion(3); + }); + }).then(function () { + // 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(); + // -------------------------------------------------------------------- + // Testing: + // 1. Place latest version first (order should not matter) + // 2. Removing the 'name' index. + db = new Dexie(DBNAME); + 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)"); + checkVersion(4); + QUnit.equal(db.tables[0].schema.indexes.length, 0, "No indexes in schema now when 'name' index was removed"); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Running an upgrader function. + db = new Dexie(DBNAME); + var upgraders = 0; + // (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) { + upgraders++; + 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"); + checkVersion(5); + QUnit.equal(upgraders, 1, "1 upgrade function should have run."); + }); + }).then(function () { + 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"); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Changing a property of an index + db = new Dexie(DBNAME); + db.version(5).stores({ store1: "++id,&email" }); + // Changing email index from unique to multi-valued + db.version(6).stores({ store1: "++id,*email" }).upgrade(function (t) { + t.table("store1").toCollection().modify(function (obj) { + // Turning single-valued unique email into an array of + // emails. + obj.email = [obj.email]; + }); + }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 6"); + checkVersion(6); + checkObjectStores(["store1"]); + }); + }).then(function () { + return db.table('store1').get(1, function (apaUser) { + QUnit.ok(Array.isArray(apaUser.email), "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"); + }); + }).then(function (array) { + db.close(); + // -------------------------------------------------------------------- + // Test: Only changed object stores need to be specified. + db = new Dexie(DBNAME); + // No need to specify an upgrade function when we know it's not + // gonna run (we are already on ver 5) + db.version(6).stores({ store1: "++id,*email" }); + db.version(7).stores({ store2: "uuid" }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 7"); + checkVersion(7); + checkObjectStores(["store1", "store2"]); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Object store removal. + db = new Dexie(DBNAME); + // Need to keep version 6 or add its missing stores to version 7, + // 7. Choosing to keep version 6. + db.version(6).stores({ store1: "++id,*email" }); + db.version(7).stores({ store2: "uuid" }); + // Deleting a version. + db.version(8).stores({ store1: null }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 8 - deleting an object store"); + checkVersion(8); + checkObjectStores(["store2"]); + }); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Use a removed object store while running an upgrade function. + /*db = new Dexie(DBNAME); + db.version(7).stores({ store2: "uuid" }); + db.version(8).stores({ store1: null }); + db.version(9).stores({ store1: "++id,email" }); + db.version(10).stores({ store1: null }).upgrade(t => { + checkTransactionObjectStores(t, ["store1"]); + // TODO: actually use the object store. + ok(true, "Upgrade transaction contains deleted store."); + }); + return db.open().then(() => { + ok(true, "Could upgrade to version 10 - deleting an object store with upgrade function"); + checkVersion(10); + checkObjectStores(["store2"]); + });*/ + }).then(function () { + // Reset. + return db.delete(); + }).then(function () { + // -------------------------------------------------------------------- + // Test: + // 1. Upgrade transactions should have the correct object + // stores available. (future version) + db = new Dexie(DBNAME); + db.version(1).stores({ + store1: "++id,name" + }); + return db.open().then(function () { + // Populate db. + return db.store1.put({ name: "A B" }); + }); + }).then(function () { + db.close(); + // Add upgrade functions. + // Track number of upgrade functions run. + var upgraders = 0; + db.version(2).stores({ + store2: "++id,firstname,lastname" + }).upgrade(function (t) { + /*checkTransactionObjectStores(t, + ["store1", "store2"]);*/ + QUnit.ok(true, "Upgrade transaction has stores deleted later."); + upgraders++; + // TODO: copy value to store2. + }); + db.version(3).stores({ + store1: null, + store3: "++id" + }).upgrade(function (t) { + /*checkTransactionObjectStores(t, + ["store1", "store2", "store3"]);*/ + upgraders++; + // TODO: Add some value to store3. + }); + return db.open().then(function () { + checkVersion(3); + QUnit.equal(upgraders, 2, "2 upgrade functions should have run."); + checkObjectStores(["store2", "store3"]); + // TODO: Check that the data is as-expected. + }); + }).then(function () { + return db.delete(); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Dexie identifies the correct table name and schema given a + // sequence of versions to go through. + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + // Adding the name index + db.version(3).stores({ store1: "++id,name" }); + db.version(4).stores({ store1: "++id" }); + db.version(5).stores({ store1: "++id,&email" }).upgrade(function (t) { + var counter = 0; + t.table("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"; + }); + }); + // Changing email index from unique to multi-valued + db.version(6).stores({ store1: "++id,*email" }).upgrade(function (t) { + t.table("store1").toCollection().modify(function (obj) { + // Turning single-valued unique email into an array of + // emails. + obj.email = [obj.email]; + }); + }); + db.version(7).stores({ store2: "uuid" }); + db.version(8).stores({ store1: null }); + return db.open().then(function () { + QUnit.ok(true, "Could create new database"); + checkVersion(8); + checkObjectStores(["store2"]); + QUnit.equal(db.table("store2").schema.primKey.name, "uuid", "The prim key is uuid"); + }); + }).then(function () { + return db.delete(); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Order of version declaration should not matter. + 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 () { + 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"); + checkVersion(8); + checkObjectStores(["store2"]); + QUnit.equal(db.table("store2").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(done); + }); +}); +QUnit.test("Issue #30 - Problem with existing db", function (assert) { + var done = assert.async(); + if (!supports("compound+multiEntry")) { + QUnit.ok(true, "SKIPPED - COMPOUND + MULTIENTRY UNSUPPORTED"); + return done(); + } + /// + 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(done); + }); +}); +promisedTest("Issue #713 - how to change table name", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, db2, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie.delete("issue713")]; + case 1: + _a.sent(); + db = new Dexie('issue713'); + _a.label = 2; + case 2: + _a.trys.push([2, , 5, 7]); + db.version(1).stores({ + friends: '++id, name, age' + }); + return [4 /*yield*/, db.friends.bulkAdd([ + { name: "Foo", age: 25 }, + { name: "Bar", age: 75 } + ])]; + case 3: + _a.sent(); + db.close(); + db2 = new Dexie('issue713'); + db2.version(1).stores({ + friends: '++id, name, age' + }); + db2.version(2).stores({ + friends2: 'id, name, age' + }).upgrade(function (tx) { + return tx.friends.toArray().then(function (objs) { + return tx.friends2.bulkAdd(objs); + }); + }); + db2.version(3).stores({ + friends: null + }); + return [4 /*yield*/, db2.friends2.toArray()]; + case 4: + result = _a.sent(); + QUnit.equal(result.length, 2, "Should get 2 friends"); + QUnit.equal(result[0].name, "Foo", "First friend is 'Foo'"); + QUnit.equal(result[1].name, "Bar", "First friend is 'Bar'"); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, db.delete()]; + case 6: + _a.sent(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); +}); }); +promisedTest("Issue #713 - how to change table name (short)", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, db2, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie.delete("issue713Short")]; + case 1: + _a.sent(); + db = new Dexie('issue713Short'); + _a.label = 2; + case 2: + _a.trys.push([2, , 5, 7]); + db.version(1).stores({ + friends: '++id, name, age' + }); + return [4 /*yield*/, db.friends.bulkAdd([ + { name: "Foo", age: 25 }, + { name: "Bar", age: 75 } + ])]; + case 3: + _a.sent(); + db.close(); + db2 = new Dexie('issue713Short'); + db2.version(1).stores({ + friends: '++id, name, age' + }); + db2.version(2).stores({ + friends2: 'id, name, age', + friends: null // delete after upgrader + }).upgrade(function (tx) { + return tx.friends.toArray().then(function (objs) { + return tx.friends2.bulkAdd(objs); + }); + }); + return [4 /*yield*/, db2.friends2.toArray()]; + case 4: + result = _a.sent(); + QUnit.equal(result.length, 2, "Should get 2 friends"); + QUnit.equal(result[0].name, "Foo", "First friend is 'Foo'"); + QUnit.equal(result[1].name, "Bar", "First friend is 'Bar'"); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, db.delete()]; + case 6: + _a.sent(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); +}); }); +promisedTest("Changing primary key", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, foos, foo2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE || isEdge) { + QUnit.ok(true, "Skipping this test for IE and Edge - it has a bug that prevents it from renaming a table"); + return [2 /*return*/]; + } + return [4 /*yield*/, Dexie.delete("changePrimKey")]; + case 1: + _a.sent(); + db = new Dexie("changePrimKey"); + db.version(1).stores({ + foos: '++id' + }); + return [4 /*yield*/, db.foos.bulkAdd([{ name: "Hola" }, { name: "Hello" }])]; + case 2: + _a.sent(); + db.close(); + // To change primary key, let's start by copying the table + // and then deleting and recreating the original table + // to copy it back again + db = new Dexie("changePrimKey"); + db.version(1).stores({ + foos: '++id' + }); + // Add version 2 that copies the data to foos2 + db.version(2).stores({ + foos2: 'objId' + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos2.bulkAdd(foos.map(function (foo) { return ({ + objId: "obj:" + foo.id, + hello: foo.name + }); }))]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + // Add version 3 that deletes old "foos" + db.version(3).stores({ + foos: null + }); + // Add version 4 that recreates "foos" with wanted primary key + // and do the copying again + db.version(4).stores({ + foos: 'objId, hello' + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos2.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos.bulkAdd(foos)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + // Finally delete the temp table + db.version(5).stores({ + foos2: null + }); + return [4 /*yield*/, db.foos.toArray()]; + case 3: + foos = _a.sent(); + QUnit.equal(foos.length, 2, "Should have 2 rows"); + QUnit.equal(foos[0].objId, "obj:1", "A primary key with an object ID 1 is there"); + QUnit.equal(foos[1].objId, "obj:2", "A primary key with an object ID 2 is there"); + return [4 /*yield*/, db.foos.get({ hello: "Hello" })]; + case 4: + foo2 = _a.sent(); + QUnit.ok(foo2 != null, "Should get a match"); + QUnit.equal(foo2.objId, "obj:2", "The expected ID was returned"); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Changing primary key (short)", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, foos, foo2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE || isEdge) { + QUnit.ok(true, "Skipping this test for IE and Edge - it has a bug that prevents it from renaming a table"); + return [2 /*return*/]; + } + return [4 /*yield*/, Dexie.delete("changePrimKeyShort")]; + case 1: + _a.sent(); + db = new Dexie("changePrimKeyShort"); + db.version(1).stores({ + foos: '++id' + }); + return [4 /*yield*/, db.foos.bulkAdd([{ name: "Hola" }, { name: "Hello" }])]; + case 2: + _a.sent(); + db.close(); + // To change primary key, let's start by copying the table + // and then deleting and recreating the original table + // to copy it back again + db = new Dexie("changePrimKeyShort"); + db.version(1).stores({ + foos: '++id' + }); + // Add version 2 that copies the data to foos2 + db.version(2).stores({ + foos: null, + foos2: 'objId' + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos2.bulkAdd(foos.map(function (foo) { return ({ + objId: "obj:" + foo.id, + hello: foo.name + }); }))]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + // Add version 3 that recreates "foos" with wanted primary key + // and do the copying again + db.version(3).stores({ + foos: 'objId, hello', + foos2: null // delete after upgrader + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos2.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos.bulkAdd(foos)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + return [4 /*yield*/, db.foos.toArray()]; + case 3: + foos = _a.sent(); + QUnit.equal(foos.length, 2, "Should have 2 rows"); + QUnit.equal(foos[0].objId, "obj:1", "A primary key with an object ID 1 is there"); + QUnit.equal(foos[1].objId, "obj:2", "A primary key with an object ID 2 is there"); + return [4 /*yield*/, db.foos.get({ hello: "Hello" })]; + case 4: + foo2 = _a.sent(); + QUnit.ok(foo2 != null, "Should get a match"); + QUnit.equal(foo2.objId, "obj:2", "The expected ID was returned"); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Issue 919: Store not found when versions declared in decending order", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, _a, _b, _c, _d, _e, _f; + return __generator(this, function (_g) { + switch (_g.label) { + case 0: return [4 /*yield*/, Dexie.delete("issue919")]; + case 1: + _g.sent(); + db = new Dexie("issue919"); + db.version(1).stores({ + friends: "++id,name,age" + }); + return [4 /*yield*/, db.open()]; + case 2: + _g.sent(); + // succeeds + _a = QUnit.ok; + _b = [true]; + _c = "Could open v1: "; + return [4 /*yield*/, db.friends.toArray()]; + case 3: + // succeeds + _a.apply(void 0, _b.concat([_c + (_g.sent())])); + db.close(); + db = new Dexie("issue919"); + // add a new store, `friends` store remains as before + db.version(2).stores({ + enemies: "++id,name" + }); + db.version(1).stores({ + friends: "++id,name,age" + }); + return [4 /*yield*/, db.open()]; + case 4: + _g.sent(); + // fails with: NotFoundError: `The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.` + _d = QUnit.ok; + _e = [true]; + _f = "Could open version 2: "; + return [4 /*yield*/, db.friends.toArray()]; + case 5: + // fails with: NotFoundError: `The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.` + _d.apply(void 0, _e.concat([_f + (_g.sent())])); + return [4 /*yield*/, db.delete()]; + case 6: + _g.sent(); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("PR #959: Dexie should no more require users to keep old versions if they don't attach an upgrader to it", function () { return __awaiter(void 0, void 0, void 0, function () { + var DBNAME, db, foo; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + DBNAME = "pr959"; + return [4 /*yield*/, Dexie.delete(DBNAME)]; + case 1: + _a.sent(); + db = new Dexie(DBNAME); + db.version(1).stores({ + friends: "id" + }); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + QUnit.ok(true, "Could open v1"); + return [4 /*yield*/, db.friends.add({ id: 1, name: "Foo 959" })]; + case 3: + _a.sent(); + db.close(); + db = new Dexie(DBNAME); + db.version(2).stores({ + friends: "id, name" + }); + return [4 /*yield*/, db.open()]; + case 4: + _a.sent(); + QUnit.ok(true, "Could open v2 without having v1 specified. Name should now be indexed."); + return [4 /*yield*/, db.friends.where("name").startsWith("Foo").first()]; + case 5: + foo = _a.sent(); + QUnit.ok(!!foo, "Could find friend using newly added index"); + QUnit.equal(foo.id, 1, "Got the right foo here"); + db.close(); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Issue #959 - Should migrate successfully with an explicit unique modifier of the primary key", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, result, result2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie.delete("issue959")]; + case 1: + _a.sent(); + db = new Dexie("issue959"); + db.version(1).stores({ + friends: "&name, age" + }); + return [4 /*yield*/, db.friends.bulkAdd([ + { name: "Foo", age: 25, weight: 70 }, + { name: "Bar", age: 75, weight: 100 } + ])]; + case 2: + _a.sent(); + db.close(); + db = new Dexie("issue959"); + db.version(1).stores({ + friends: "&name, age" + }); + db.version(2).stores({ + friends: "&name, age, weight" + }); + return [4 /*yield*/, db.friends.orderBy("age").toArray()]; + case 3: + result = _a.sent(); + QUnit.equal(result.length, 2, "Should get 2 friends"); + QUnit.equal(result[0].name, "Foo", "First friend is 'Foo'"); + QUnit.equal(result[1].name, "Bar", "First friend is 'Bar'"); + return [4 /*yield*/, db.friends.get({ weight: 100 })]; + case 4: + result2 = _a.sent(); + QUnit.ok(result2 != null, "Should get a match"); + QUnit.equal(result2.name, "Bar", "The expected friends was returned"); + return [2 /*return*/]; + } + }); +}); }); + +var async$3 = Dexie.async; +var db$7 = new Dexie("TestIssuesDB"); +db$7.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$7).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +// +// Misc Tests +// +promisedTest("issue#729", function () { return __awaiter(void 0, void 0, void 0, function () { + var onConsoleWarn, warnDescriptor, err_1, f, err_2, f, err_3, f, err_4; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + onConsoleWarn = function (txt) { + QUnit.ok(false, 'console warn happened: ' + txt); + }; + warnDescriptor = Object.getOwnPropertyDescriptor(console, 'warn'); + console.warn = onConsoleWarn; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, db$7.foo.bulkPut([{ + id: 1, + foo: 'foo', + }, { + id: 2, + foo: 'bar', + } + ])]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + QUnit.ok(false, "Couldn't populate data: " + err_1); + return [3 /*break*/, 4]; + case 4: + _a.trys.push([4, 6, , 7]); + return [4 /*yield*/, db$7.foo.add({ id: 1, foo: "bar" })]; + case 5: + f = _a.sent(); + return [3 /*break*/, 7]; + case 6: + err_2 = _a.sent(); + QUnit.ok(true, "Got the err:" + err_2); + return [3 /*break*/, 7]; + case 7: + _a.trys.push([7, 9, , 10]); + return [4 /*yield*/, db$7.foo.get(false)]; + case 8: + f = _a.sent(); + return [3 /*break*/, 10]; + case 9: + err_3 = _a.sent(); + QUnit.ok(true, "Got the err:" + err_3); + return [3 /*break*/, 10]; + case 10: + _a.trys.push([10, 12, , 13]); + return [4 /*yield*/, db$7.foo.where({ id: 1 }) + .modify({ id: 2, foo: "bar" })]; + case 11: + f = _a.sent(); + return [3 /*break*/, 13]; + case 12: + err_4 = _a.sent(); + QUnit.ok(true, "Got the err:" + err_4); + return [3 /*break*/, 13]; + case 13: + if (warnDescriptor) { + Object.defineProperty(console, 'warn', warnDescriptor); + } + else { + delete console.warn; + } + return [2 /*return*/]; + } + }); +}); }); +QUnit.asyncTest("Adding object with falsy keys", function () { + db$7.keyless.add({ name: "foo" }, 1).then(function (id) { + QUnit.equal(id, 1, "Normal case ok - Object with key 1 was successfully added."); + return db$7.keyless.add({ name: "bar" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could add a numeric falsy value (0)"); + return db$7.keyless.add({ name: "foobar" }, ""); + }).then(function (id) { + QUnit.equal(id, "", "Could add a string falsy value ('')"); + return db$7.keyless.put({ name: "bar2" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could put a numeric falsy value (0)"); + return db$7.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); +}); +promisedTest("#770", function () { return __awaiter(void 0, void 0, void 0, function () { + var dbName, db, runnedVersions, otherDB, otherDbRows, origDbRows, err_5; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + dbName = 'TestDB-' + Math.random(); + db = new Dexie(dbName, { addons: [] }); + runnedVersions = []; + _a.label = 1; + case 1: + _a.trys.push([1, 7, 8, 11]); + db.version(1).stores({ test: 'id' }); + return [4 /*yield*/, db.test.put({ id: 1 })]; + case 2: + _a.sent(); + return [4 /*yield*/, db.open()]; + case 3: + _a.sent(); + db.close(); + db = new Dexie(dbName, { addons: [] }); + db.version(1).stores({ test: 'id' }); + db.version(2).stores({ test: 'id' }).upgrade(function (t) { return __awaiter(void 0, void 0, void 0, function () { + var rowsToCopy; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + runnedVersions.push(2); + return [4 /*yield*/, t.test.toArray()]; + case 1: + rowsToCopy = _a.sent(); + return [4 /*yield*/, Dexie.waitFor((function () { return __awaiter(void 0, void 0, void 0, function () { + var otherDB; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + otherDB = new Dexie(dbName + '-another-unrelated-db', { addons: [] }); + otherDB.version(1).stores({ foo: 'id' }); + return [4 /*yield*/, otherDB.open()]; + case 1: + _a.sent(); + return [4 /*yield*/, otherDB.foo.bulkAdd(rowsToCopy)]; + case 2: + _a.sent(); + otherDB.close(); + return [2 /*return*/]; + } + }); + }); })())]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + db.version(3).stores({ test: 'id' }).upgrade(function (t) { + runnedVersions.push(3); + }); + return [4 /*yield*/, db.open()]; + case 4: + _a.sent(); + QUnit.deepEqual(runnedVersions, [2, 3], "Versions 3 did indeed proceed (as well as version 2)"); + otherDB = new Dexie(dbName + '-another-unrelated-db', { addons: [] }); + otherDB.version(1).stores({ foo: 'id' }); + return [4 /*yield*/, otherDB.foo.toArray()]; + case 5: + otherDbRows = _a.sent(); + return [4 /*yield*/, db.test.toArray()]; + case 6: + origDbRows = _a.sent(); + QUnit.deepEqual(otherDbRows, origDbRows, "All rows was copied atomically"); + db.close(); + otherDB.close(); + return [3 /*break*/, 11]; + case 7: + err_5 = _a.sent(); + QUnit.ok(false, "Error " + err_5); + return [3 /*break*/, 11]; + case 8: return [4 /*yield*/, db.delete()]; + case 9: + _a.sent(); + return [4 /*yield*/, new Dexie(dbName + '-another-unrelated-db', { addons: [] }).delete()]; + case 10: + _a.sent(); + return [7 /*endfinally*/]; + case 11: return [2 /*return*/]; + } + }); +}); }); +QUnit.asyncTest("#102 Passing an empty array to anyOf throws exception", async$3(function () { + var count, err_6; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, db$7.users.where("username").anyOf([]).count()]; + case 1: + count = _a.sent(); + QUnit.equal(count, 0, "Zarro items matched the query anyOf([])"); + return [3 /*break*/, 4]; + case 2: + err_6 = _a.sent(); + QUnit.ok(false, "Error when calling anyOf([]): " + err_6); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); +})); +spawnedTest("#248 'modifications' object in 'updating' hook can be bizarre", function () { + 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(); + //... + } + function creatingHook(primKey, obj) { + ++numCreating; + var date = obj.date; + if (date && date instanceof CustomDate) { + obj.date = new Date(date._year, date._month, date._day); + } + } + 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) }; + } + } + function isDate(obj) { + // obj instanceof Date does NOT work with Safari when Date are retrieved from IDB. + return obj.getTime && obj.getDate && obj.getFullYear; + } + function readingHook(obj) { + if (obj.date && isDate(obj.date)) { + obj.date = new CustomDate(obj.date); + } + return obj; + } + var numCreating, numUpdating, testDate, testDate2, retrieved; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + numCreating = 0, numUpdating = 0; + db$7.foo.hook('creating', creatingHook); + db$7.foo.hook('reading', readingHook); + db$7.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)); + _a.label = 1; + case 1: + _a.trys.push([1, , 4, 5]); + db$7.foo.add({ id: 1, date: testDate }); + return [4 /*yield*/, db$7.foo.get(1)]; + case 2: + retrieved = _a.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$7.foo.put({ id: 1, date: testDate2 }); + return [4 /*yield*/, db$7.foo.get(1)]; + case 3: + retrieved = _a.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"); + return [3 /*break*/, 5]; + case 4: + db$7.foo.hook('creating').unsubscribe(creatingHook); + db$7.foo.hook('reading').unsubscribe(readingHook); + db$7.foo.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); +}); +QUnit.asyncTest("Issue: Broken Promise rejection #264", 1, function () { + db$7.open().then(function () { + return db$7.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 = /** @class */ (function () { + function Foo() { + } + Object.defineProperty(Foo.prototype, "synced", { + get: function () { return false; }, + enumerable: true, + configurable: true + }); + return Foo; + }()); + db$7.foo.mapToClass(Foo); + db$7.transaction('rw', db$7.foo, function () { + db$7.foo.put({ id: 1 }); + db$7.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$7.foo.get(1); + }).then(function (foo) { + return db$7.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$7.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$7.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$7.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); +}); +spawnedTest("#360 DB unresponsive after multiple Table.update() or Collection.modify()", function () { + var NUM_UPDATES, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + NUM_UPDATES = 2000; + return [4 /*yield*/, db$7.transaction('rw', db$7.foo, function () { + var i; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$7.foo.put({ id: 1, value: 0 })]; + case 1: + _a.sent(); + for (i = 0; i < NUM_UPDATES; ++i) { + db$7.foo.where('id').equals(1).modify(function (item) { return ++item.value; }); + } + return [4 /*yield*/, db$7.foo.get(1)]; + case 2: return [2 /*return*/, _a.sent()]; + } + }); + })]; + case 1: + result = _a.sent(); + QUnit.equal(result.value, NUM_UPDATES, "Should have updated id 1 a " + NUM_UPDATES + " times"); + return [2 /*return*/]; + } + }); +}); +spawnedTest("delByKeyPath not working correctly for arrays", function () { + var obj, obj2, jsonResult, jsonResult2; + return __generator(this, function (_a) { + obj = { deepObject: { someArray: ["a", "b"] } }; + obj2 = { deepObject: { someArray: ["a", "b", "c"] } }; + jsonResult = JSON.stringify(obj); + console.log("jsonResult = ", jsonResult); + Dexie.delByKeyPath(obj2, "deepObject.someArray.2"); + jsonResult2 = JSON.stringify(obj2); + console.log("jsonResult2 = ", jsonResult2); + QUnit.equal(jsonResult, jsonResult2, "Should be equal " + jsonResult + " " + jsonResult2); + return [2 /*return*/]; + }); +}); +QUnit.asyncTest("#1079 mapToClass", function () { + var Foo = /** @class */ (function () { + function Foo() { + } + return Foo; + }()); + db$7.foo.mapToClass(Foo); + db$7.transaction('rw', db$7.foo, function () { + db$7.foo.put({ id: 1 }); + }).catch(function (e) { + QUnit.ok(true, "Unexpected error from put: " + (e.stack || e)); + }).then(function () { + return db$7.foo.get(1); + }).then(function (getResult) { + QUnit.ok(getResult instanceof Foo, "Result of get not mapped to class"); + }).catch(function (e) { + QUnit.ok(true, "Unexpected error from get: " + (e.stack || e)); + }).then(function () { + return db$7.foo.bulkGet([1]); + }).then(function (bulkGetResult) { + QUnit.ok(bulkGetResult.length === 1, "Unexpected array length " + bulkGetResult.length + " from bulkGet"); + QUnit.ok(bulkGetResult[0] instanceof Foo, "Result of bulkGet not mapped to class"); + }).catch(function (e) { + QUnit.ok(true, "Unexpected error from bulkGet: " + (e.stack || e)); + }).finally(QUnit.start); +}); + +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("onunhandledrejection should propagate once", 1, function () { + if (!supports("domevents")) { + QUnit.ok(true, "Skipping - DOM events not supported"); + QUnit.start(); + return; + } + var Promise = Dexie.Promise; + function logErr(ev) { + QUnit.ok(true, ev.reason); + return false; + } + 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("onunhandledrejection should not propagate if catched after finally", 1, function () { + if (!supports("domevents")) { + QUnit.ok(true, "Skipping - DOM events not supported"); + QUnit.start(); + return; + } + 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 () { + if (!supports("domevents")) { + QUnit.ok(true, "Skipping - DOM events not supported"); + QUnit.start(); + return; + } + 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 () { + if (!supports("domevents")) { + QUnit.ok(true, "Skipping - DOM events not supported"); + QUnit.start(); + return; + } + 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 () { + if (!supports("domevents")) { + QUnit.ok(true, "Skipping - DOM events not supported"); + QUnit.start(); + return; + } + 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); +}); + +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)"); +}); + +/** + * Created by David on 3/31/2016. + */ +var Promise$2 = Dexie.Promise; +var all = Promise$2.all; +var async$4 = Dexie.async; +var spawn$1 = Dexie.spawn; +var db$8 = new Dexie("TestDBCrudHooks"); +db$8.version(1).stores({ + table1: "id,idx", + table2: ",&idx", + table3: "++id,&idx", + table4: "++,&idx", + table5: "" +}); +var ourTables = [db$8.table1, db$8.table2, db$8.table3, db$8.table4, db$8.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$4(function reset() { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + unsubscribeHooks(); + return [4 /*yield*/, all(ourTables.map(function (table) { return table.clear(); }))]; + case 1: + _a.sent(); + subscrubeHooks(); + opLog = []; + successLog = []; + errorLog = []; + watchSuccess = false; + watchError = false; + deliverKeys = []; + deliverModifications = null; + deliverKeys2 = []; + deliverModifications2 = null; + opLog2 = []; + successLog2 = []; + errorLog2 = []; + transLog = []; + return [2 /*return*/]; + } + }); +}); +/*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$1() { } +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 = function (updatedObj){} 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 (updatedObj) { return successLog.push(updatedObj); }; + } + 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 = function (updatedObj){} 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 (updatedObj) { return successLog2.push(updatedObj); }; + } + 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$8).then(function () { return reset(); }).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + unsubscribeHooks(); + } +}); +var expect = async$4(function (expected, modifyer) { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, reset()]; + case 1: + _a.sent(); + return [4 /*yield*/, modifyer()]; + case 2: + _a.sent(); + QUnit.equal(JSON.stringify(opLog, null, 2), JSON.stringify(expected.map(function (x) { return (__assign(__assign({}, x), { updatedObj: undefined })); }), 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"); + return [4 /*yield*/, reset()]; + case 3: + _a.sent(); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 4: + _a.sent(); + 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 (x.op === "update") { + QUnit.equal(JSON.stringify(successLog[i]), JSON.stringify(x.updatedObj), "Success events got the updated object"); + QUnit.equal(JSON.stringify(successLog2[i]), JSON.stringify(x.updatedObj), "Success events got the updated object (2)"); + } + }); + if (!expected.some(function (x) { return x.op === "create" && x.key === undefined; })) return [3 /*break*/, 7]; + // Test to deliver prim key from both hooks and expect the second hook's key to win. + return [4 /*yield*/, reset()]; + case 5: + // Test to deliver prim key from both hooks and expect the second hook's key to win. + _a.sent(); + deliverKeys = expected.map(function (x, i) { return "Hook1Key" + i; }); + deliverKeys2 = expected.map(function (x, i) { return "Hook2Key" + i; }); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 6: + _a.sent(); + 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)"); + } + }); + _a.label = 7; + case 7: + if (!expected.some(function (x) { return x.op === "update"; })) return [3 /*break*/, 10]; + return [4 /*yield*/, reset()]; + case 8: + _a.sent(); + deliverModifications = { "someProp.someSubProp": "someValue" }; + return [4 /*yield*/, modifyer()]; + case 9: + _a.sent(); + 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"); + } + }); + _a.label = 10; + case 10: return [2 /*return*/]; + } + }); +}); +var verifyErrorFlows = async$4(function (modifyer) { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, reset()]; + case 1: + _a.sent(); + QUnit.ok(true, "Verifying ERROR flows"); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 2: + _a.sent(); + 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)); + return [2 /*return*/]; + } + }); +}); +// +// +// Tests goes here... +// +// +// +// CREATING hook tests... +// +// Ways to produce CREATEs: +// Table.add() +// Table.put() +// Table.bulkAdd() +// Table.bulkPut() +spawnedTest("creating using Table.add()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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$8.transaction('rw', db$8.tables, function () { + db$8.table1.add({ id: 1, idx: 11 }); + db$8.table2.add({ idx: 12 }, 2); + db$8.table3.add({ idx: 13 }); + db$8.table4.add({ idx: 14 }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$8.table1.add({ id: 1 }).catch(nop$1)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table2.add({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$8.table2.add({}, 1).catch(nop$1)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table1.add({ id: {} }).catch(nop$1)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("creating using Table.put()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + //console.log("Putting {id:1, idx: 11} into table1"); + return [4 /*yield*/, db$8.table1.put({ id: 1, idx: 11 })]; + case 1: + //console.log("Putting {id:1, idx: 11} into table1"); + _a.sent(); + //console.log("Putting {idx: 12} for key 2 into table2"); + return [4 /*yield*/, db$8.table2.put({ idx: 12 }, 2)]; + case 2: + //console.log("Putting {idx: 12} for key 2 into table2"); + _a.sent(); + //console.log("Putting {idx: 13} into table3"); + return [4 /*yield*/, db$8.table3.put({ idx: 13 })]; + case 3: + //console.log("Putting {idx: 13} into table3"); + _a.sent(); + //console.log("Putting {idx: 14} into table4"); + return [4 /*yield*/, db$8.table4.put({ idx: 14 })]; + case 4: + //console.log("Putting {idx: 14} into table4"); + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table3.put({ idx: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$8.table3.put({ idx: 1 }).catch(nop$1)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table2.put({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$8.table2.put({}, 1).catch(nop$1)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table3.put({ id: {} }).catch(nop$1)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("creating using Table.bulkAdd()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + db$8.table1.bulkAdd([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }]); + db$8.table2.bulkAdd([{ idx: 12 }, { idx: 12.2 }], [2, 2.2]); + db$8.table3.bulkAdd([{ idx: 13 }, { idx: 13.2 }]); + db$8.table4.bulkAdd([{ idx: 14 }, { idx: 14.2 }]); + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.bulkAdd([{ id: 1 }, { id: 1 }]).catch(nop$1)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$8.table1.bulkAdd([{ id: 2 }, { id: 2 }, { id: 3 }]).catch(nop$1)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$8.table2.bulkAdd([{}, {}], [1, 1]).catch(nop$1)]; + case 3: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$8.table2.bulkAdd([{}, {}, {}], [2, 2, 3]).catch(nop$1)]; + case 4: + _a.sent(); // 1. success, 2. error event. 3. success. + return [4 /*yield*/, db$8.table1.bulkAdd([{ id: {} }]).catch(nop$1)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("creating using Table.bulkPut()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.bulkPut([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table2.bulkPut([{ idx: 12 }, { idx: 12.2 }], [2, 2.2])]; + case 2: + _a.sent(); + return [4 /*yield*/, db$8.table3.bulkPut([{ idx: 13 }, { idx: 13.2 }])]; + case 3: + _a.sent(); + return [4 /*yield*/, db$8.table4.bulkPut([{ idx: 14 }, { idx: 14.2 }])]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table3.bulkPut([{ idx: 1 }, { idx: 1 }]).catch(nop$1)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$8.table3.bulkPut([{ idx: 2 }, { idx: 2 }, { idx: 3 }]).catch(nop$1)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$8.table1.bulkPut([{ id: {} }]).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +// +// READING hooks test +// Ways to produce READs: +// Table.get() +// Table.bulkGet() +// Collection.toArray() +// Collection.each() +// Collection.first() +// Collection.last() +// But not: +// Table.filter() / Collection.and() +spawnedTest("reading tests", function () { + var readOps, readOps2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { foo: "bar" } + }, { + op: "create", + key: 2, + value: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }], function () { return db$8.transaction('rw', 'table5', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table5.bulkAdd([{ foo: "bar" }, { fee: "bore" }], [1, 2])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table5.toArray()]; + case 2: + _a.sent(); + return [4 /*yield*/, db$8.table5.reverse().each(function (x) { })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$8.table5.orderBy(':id').first()]; + case 4: + _a.sent(); + return [4 /*yield*/, db$8.table5.orderBy(':id').last()]; + case 5: + _a.sent(); + return [4 /*yield*/, db$8.table5.bulkGet([1, 2])]; + case 6: + _a.sent(); + return [4 /*yield*/, db$8.table5.filter(function (x) { return false; }).toArray()]; + case 7: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + 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"); + return [2 /*return*/]; + } + }); +}); +// +// UPDATING hooks test +// Ways to produce UPDATEs: +// Table.put() +// Table.bulkPut() +// Table.update() +// Collection.modify() +spawnedTest("updating using Table.put()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + db$8.table1.put({ id: 1, address: { city: 'A' } }); // create + db$8.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table3.add({ id: 1, idx: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table3.put({ id: 2, idx: 1 }).catch(nop$1)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$8.table3.put({ id: {} }).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("updating using Table.bulkPut()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + db$8.table1.put({ id: 1, address: { city: 'A' } }); // create + db$8.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table4.add({ idx: 1 }, 1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table4.bulkPut([{ idx: 1 }], [2]).catch(nop$1)]; + case 2: + _a.sent(); // error event (DataError) + return [4 /*yield*/, db$8.table3.bulkPut([{}], [{}]).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("updating using Table.update()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.update(1, { "address.city": "B" })]; + case 2: + _a.sent(); // update + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table3.update(1, { idx: 2 }).catch(nop$1)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$8.table3.update(1, 3).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception? + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("updating using Collection.modify()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, 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" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.where('id').equals(1).modify({ "address.city": "B" })]; + case 2: + _a.sent(); // update + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table3.where('id').equals(1).modify({ idx: 2 }).catch(nop$1)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$8.table3.where('id').equals(1).modify(function () { throw "apa"; }).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception + return [2 /*return*/]; + } + }); + }).catch(nop$1); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +// +// 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)", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.delete(1)]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("deleting using Table.bulkDelete(key)", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.bulkDelete([1])]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("deleting using Table.clear()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.clear()]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("deleting using Table.modify()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.where('id').between(0, 2).modify(function () { + delete this.value; + })]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); +spawnedTest("deleting using Collection.delete()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$8.transaction('rw', db$8.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.where('id').between(0, 2).delete()]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); +}); + +var db$9 = new Dexie("TestDBBinary"); +db$9.version(1).stores({ + items: "id" +}); +QUnit.module("blobs", { + setup: function () { + QUnit.stop(); + resetDatabase(db$9).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +function readBlob(blob) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onloadend = function (ev) { return resolve(ev.target.result); }; + reader.onerror = function (ev) { return reject(ev.target.error); }; + reader.onabort = function (ev) { return reject(new Error("Blob Aborted")); }; + reader.readAsArrayBuffer(blob); + }); +} +function arraysAreEqual(a1, a2) { + var length = a1.length; + if (a2.length !== length) + return false; + for (var i = 0; i < length; ++i) { + if (a1[i] !== a2[i]) + return false; + } + return true; +} +promisedTest("Test blobs", function () { return __awaiter(void 0, void 0, void 0, function () { + var binaryData, blob, back, arrayBuffer, resultBinaryData; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + binaryData = new Uint8Array([1, 2, 3, 4]); + blob = new Blob([binaryData], { type: 'application/octet-binary' }); + return [4 /*yield*/, db$9.items.add({ id: 1, blob: blob })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.items.get(1)]; + case 2: + back = _a.sent(); + return [4 /*yield*/, readBlob(back.blob)]; + case 3: + arrayBuffer = _a.sent(); + resultBinaryData = new Uint8Array(arrayBuffer); + QUnit.ok(arraysAreEqual(resultBinaryData, binaryData), "Arrays should be equal"); + return [2 /*return*/]; + } + }); +}); }); +promisedTest("Test blob with creating hook applied", function () { return __awaiter(void 0, void 0, void 0, function () { + function updatingHook(modifications, primKey, obj, trans) { + QUnit.ok(modifications.blob instanceof Blob, "When hook is called, the modifications should point to a Blob object"); + } + var binaryData, blob, back, arrayBuffer, resultBinaryData; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, , 5, 6]); + db$9.items.hook('updating', updatingHook); + binaryData = new Uint8Array([1, 2, 3, 4]); + blob = new Blob([binaryData], { type: 'application/octet-binary' }); + return [4 /*yield*/, db$9.items.add({ id: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.items.put({ id: 1, blob: blob })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$9.items.get(1)]; + case 3: + back = _a.sent(); + return [4 /*yield*/, readBlob(back.blob)]; + case 4: + arrayBuffer = _a.sent(); + resultBinaryData = new Uint8Array(arrayBuffer); + QUnit.ok(arraysAreEqual(resultBinaryData, binaryData), "Arrays should be equal"); + return [3 /*break*/, 6]; + case 5: + db$9.items.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); +}); }); + +var db$10 = new Dexie("TestDBBinaryKeys"); +db$10.version(1).stores({ + items: "id,data" +}); +db$10.on('populate', function () { + db$10.items.bulkAdd([ + { id: 'Uint8Array', data: new Uint8Array([1, 2, 3]) }, + { id: 'ArrayBuffer', data: new Uint8Array([4, 5, 6]).buffer }, + ]); +}); +QUnit.module("binarykeys", { + setup: function () { + QUnit.stop(); + resetDatabase(db$10).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } +}); +promisedTest('Binary Primary Key (Int32Array)', function () { return __awaiter(void 0, void 0, void 0, function () { + var id, back; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 4, 6]); + id = new Int32Array([4, 2]); + QUnit.equal(id[0], 4, "Sanity check 1"); + QUnit.equal(id[1], 2, "Sanity check 2"); + return [4 /*yield*/, db$10.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$10.items.where({ id: new Int32Array([4, 2]) }).first()]; + case 3: + back = _a.sent(); + QUnit.equal(back.data, "string", "Should retrieve an object by its binary primary key"); + QUnit.equal(back.id[0], 4, "Should get correct value 4"); + QUnit.equal(back.id[1], 2, "Should get correcg value 2"); + return [3 /*break*/, 6]; + case 4: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + return [4 /*yield*/, db$10.items.clear()]; + case 5: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + _a.sent(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); +}); }); +promisedTest('Binary Primary Key (Float32Array)', function () { return __awaiter(void 0, void 0, void 0, function () { + var id, back; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 4, 6]); + id = new Float32Array([4.3, 2.5]); + QUnit.equal(Math.round(id[0] * 100), 4.3 * 100, "Sanity check 1"); + QUnit.equal(Math.round(id[1] * 100), 2.5 * 100, "Sanity check 2"); + return [4 /*yield*/, db$10.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$10.items // avoiding db.items.get(key) because it triggers bug in Firefox 55. + .where({ id: new Float32Array([4.3, 2.5]) }) + .first()]; + case 3: + back = _a.sent(); + QUnit.equal(back.data, "string", "Should retrieve an object by its binary primary key"); + QUnit.equal(Math.round(back.id[0] * 100), 4.3 * 100, "Should get correct float value 4.3"); + QUnit.equal(Math.round(back.id[1] * 100), 2.5 * 100, "Should get correcg float value 2.5"); + return [3 /*break*/, 6]; + case 4: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + return [4 /*yield*/, db$10.items.clear()]; + case 5: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + _a.sent(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); +}); }); +promisedTest('Binary Index', function () { return __awaiter(void 0, void 0, void 0, function () { + var _a, x; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a = QUnit.equal; + return [4 /*yield*/, db$10.items.where('data').equals(new Uint8Array([1, 2, 3])).count()]; + case 1: + _a.apply(void 0, [_b.sent(), 1, "Should be able to query on binary key"]); + return [4 /*yield*/, db$10.items.where('data') + .anyOf([new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])]) + .toArray()]; + case 2: + x = _b.sent(); + QUnit.equal(x.length, 2, "Should find both keys even though the second has another binary type (IndexedDB should not distinguish them)"); + return [2 /*return*/]; + } + }); +}); }); +promisedTest('OR-query', function () { return __awaiter(void 0, void 0, void 0, function () { + var a; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 4, 6]); + return [4 /*yield*/, db$10.items.bulkAdd([ + { + id: new Float32Array([6.3, 10.5]), + data: "something" + }, + { + id: new Uint8Array([1, 2, 3]), + data: "somethingelse" + } + ])]; + case 2: + _a.sent(); + return [4 /*yield*/, db$10.items.where('data').equals("something") + .or('id').equals(new Uint8Array([1, 2, 3])) + .toArray()]; + case 3: + a = _a.sent(); + QUnit.equal(a.length, 2, "Should get two entries"); + QUnit.ok(a.some(function (x) { return x.data === "something"; }), "Should get 'something' in the result"); + QUnit.ok(a.some(function (x) { return x.data === "somethingelse"; }), "Should get 'somethingelse' in the result"); + return [3 /*break*/, 6]; + case 4: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + return [4 /*yield*/, db$10.items.clear()]; + case 5: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + _a.sent(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); +}); }); + +Dexie.test = true; // Improve code coverage + +//import "./tests-performance.js"; Not required. Should make other performance tests separately instead. + +}))); +//# sourceMappingURL=bundle.js.map