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..1568c97fb --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.d.ts @@ -0,0 +1,116 @@ +// Type definitions for dexie-observable v3.0.0-beta.11 +// Project: https://github.com/dfahlander/Dexie.js/tree/master/addons/Dexie.Observable +// Definitions by: David Fahlander + +import Dexie, { DexieEventSet } from 'dexie'; +import { IDatabaseChange } from '../api'; + +export interface SyncNodeConstructor { + new() : SyncNode; +} + +// +// Interfaces of Dexie.Observable +// + + +/** + * 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. + */ +export 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. +} + +export interface ObservableEventSet extends 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; +} + +// +// 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: { + version: string; + SyncNode: 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: SyncNode; + + _changes: Dexie.Table; + _syncNodes: Dexie.Table; + _intercomm: Dexie.Table; + } + + // 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: MessageEvent)=>any): void; + } + + // Extended IndexSpec with uuid boolean for primary key. + interface IndexSpec { + uuid: boolean; + } + + interface DexieConstructor { + Observable: { + (db: Dexie) : void; + + version: string; + createUUID: () => string; + on: ObservableEventSet; + localStorageImpl: { + setItem(key: string, value: string): void, + getItem(key: string): string, + removeItem(key: string): void; + }; + _onStorage: (event: StorageEvent) => 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..26de4b187 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js @@ -0,0 +1,1010 @@ +/* ========================================================================== + * 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} + * + * https://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$2 = 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$2.reject(new Dexie.DatabaseClosedError()) : + Promise$2.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$2(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$2.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$2.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} + * + * https://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; +/** Dexie addon for change tracking and real-time observation. + * + * @param {Dexie} db + */ +function Observable(db) { + if (!/^3\./.test(Dexie.version)) + throw new Error("Missing dexie version 3.x"); + if (db.observable) { + if (db.observable.version !== "{version}") + throw new Error("Mixed versions of dexie-observable"); + return; // Addon already active. + } + 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 = { version: "{version}" }; + 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._syncNodes.put(mySyncNode.node).then(Dexie.ignoreTransaction(function () { + // By default, this node will become master unless we discover an existing, up-to-date master + var mySyncNodeShouldBecomeMaster = 1; + return db._syncNodes.orderBy('isMaster').reverse().modify(function (existingNode) { + if (existingNode.isMaster) { + if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Existing master record is out-of-date; demote it + existingNode.isMaster = 0; + } + else { + // An existing up-to-date master record exists, so it will remain master + mySyncNodeShouldBecomeMaster = 0; + } + } + // The local node reference may be unassigned at any point by a database close() operation + if (!mySyncNode.node) + return; + // Assign the local node state + // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause + if (existingNode.id === mySyncNode.node.id) { + existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster; + } + }); + })).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().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.version = "{version}"; +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 === null || global === void 0 ? void 0 : global.addEventListener) { + global.addEventListener("storage", Observable._onStorage); + global.addEventListener("beforeunload", Observable._onBeforeUnload); +} +if (Dexie.Observable) { + if (Dexie.Observable.version !== "{version}") { + throw new Error("Mixed versions of dexie-observable"); + } +} +else { + // Register addon: + Dexie.Observable = Observable; + Dexie.addons.push(Observable); +} +var Dexie_Observable = Dexie.Observable; + +export { Dexie_Observable as default }; +//# 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..da4bd05fa --- /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 * https://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\n/** Dexie addon for change tracking and real-time observation.\n * \n * @param {Dexie} db \n */\nfunction Observable(db) {\n if (!/^3\\./.test(Dexie.version))\n throw new Error(`Missing dexie version 3.x`);\n if (db.observable) {\n if (db.observable.version !== \"{version}\") throw new Error(`Mixed versions of dexie-observable`);\n return; // Addon already active.\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 = {version: \"{version}\"};\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._syncNodes.put(mySyncNode.node).then(Dexie.ignoreTransaction(() => {\n // By default, this node will become master unless we discover an existing, up-to-date master\n var mySyncNodeShouldBecomeMaster = 1;\n return db._syncNodes.orderBy('isMaster').reverse().modify(existingNode => {\n if (existingNode.isMaster) {\n if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Existing master record is out-of-date; demote it\n existingNode.isMaster = 0;\n } else {\n // An existing up-to-date master record exists, so it will remain master\n mySyncNodeShouldBecomeMaster = 0;\n }\n }\n\n // The local node reference may be unassigned at any point by a database close() operation\n if (!mySyncNode.node) return;\n\n // Assign the local node state\n // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause\n if (existingNode.id === mySyncNode.node.id) {\n existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster;\n }\n });\n })).then(() => {\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 }).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.version = \"{version}\";\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\nif (Dexie.Observable) {\n if (Dexie.Observable.version !== \"{version}\") {\n throw new Error (`Mixed versions of dexie-observable`);\n }\n} else {\n // Register addon:\n Dexie.Observable = Observable;\n Dexie.addons.push(Observable);\n}\n\nexport default Dexie.Observable;\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;SAAgB,GAAG,MAAK;SAER,eAAe,CAAC,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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AAU,CAAC,CAAC;CACjC;AAED,uBAAe,KAAK,CAAC,UAAU;;;;"} \ 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..2dd12a5ed --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js @@ -0,0 +1,1020 @@ +/* ========================================================================== + * 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 3.0.0-beta.11, Tue Feb 13 2024 + * + * https://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 = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.Dexie = global.Dexie || {}, global.Dexie.Observable = factory(global.Dexie))); +})(this, (function (Dexie) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var Dexie__default = /*#__PURE__*/_interopDefaultLegacy(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__default["default"].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__default["default"].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__default["default"].deepClone(oldObj); + for (var propPath in mods) { + var mod = mods[propPath]; + if (typeof mod === 'undefined') { + Dexie__default["default"].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__default["default"].getByKeyPath(oldObj, propPath); + if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) { + Dexie__default["default"].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__default["default"].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$2 = Dexie__default["default"].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$2.reject(new Dexie__default["default"].DatabaseClosedError()) : + Promise$2.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__default["default"].extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ... + return Dexie__default["default"].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$2(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__default["default"].ignoreTransaction(function () { + db._syncNodes.toArray(function (nodes) { + return Promise$2.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$2.reject(new Dexie__default["default"].DatabaseClosedError()); + return Dexie__default["default"].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__default["default"].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 3.0.0-beta.11, Tue Feb 13 2024 + * + * https://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__default["default"].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__default["default"].override; + var Promise$1 = Dexie__default["default"].Promise; + var browserIsShuttingDown = false; + /** Dexie addon for change tracking and real-time observation. + * + * @param {Dexie} db + */ + function Observable(db) { + if (!/^3\./.test(Dexie__default["default"].version)) + throw new Error("Missing dexie version 3.x"); + if (db.observable) { + if (db.observable.version !== "3.0.0-beta.11") + throw new Error("Mixed versions of dexie-observable"); + return; // Addon already active. + } + 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__default["default"].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 = { version: "3.0.0-beta.11" }; + 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__default["default"].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__default["default"].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._syncNodes.put(mySyncNode.node).then(Dexie__default["default"].ignoreTransaction(function () { + // By default, this node will become master unless we discover an existing, up-to-date master + var mySyncNodeShouldBecomeMaster = 1; + return db._syncNodes.orderBy('isMaster').reverse().modify(function (existingNode) { + if (existingNode.isMaster) { + if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Existing master record is out-of-date; demote it + existingNode.isMaster = 0; + } + else { + // An existing up-to-date master record exists, so it will remain master + mySyncNodeShouldBecomeMaster = 0; + } + } + // The local node reference may be unassigned at any point by a database close() operation + if (!mySyncNode.node) + return; + // Assign the local node state + // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause + if (existingNode.id === mySyncNode.node.id) { + existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster; + } + }); + })).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__default["default"].vip(function () { + readChanges().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__default["default"].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__default["default"].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__default["default"].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__default["default"].vip(function () { + db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup); + }); + } + } + } + // + // Static properties and methods + // + Observable.version = "3.0.0-beta.11"; + Observable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37; + Observable.on = Dexie__default["default"].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 === null || global === void 0 ? void 0 : global.addEventListener) { + global.addEventListener("storage", Observable._onStorage); + global.addEventListener("beforeunload", Observable._onBeforeUnload); + } + if (Dexie__default["default"].Observable) { + if (Dexie__default["default"].Observable.version !== "3.0.0-beta.11") { + throw new Error("Mixed versions of dexie-observable"); + } + } + else { + // Register addon: + Dexie__default["default"].Observable = Observable; + Dexie__default["default"].addons.push(Observable); + } + var Dexie_Observable = Dexie__default["default"].Observable; + + return Dexie_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..8518c1362 --- /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 * https://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\n/** Dexie addon for change tracking and real-time observation.\n * \n * @param {Dexie} db \n */\nfunction Observable(db) {\n if (!/^3\\./.test(Dexie.version))\n throw new Error(`Missing dexie version 3.x`);\n if (db.observable) {\n if (db.observable.version !== \"{version}\") throw new Error(`Mixed versions of dexie-observable`);\n return; // Addon already active.\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 = {version: \"{version}\"};\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._syncNodes.put(mySyncNode.node).then(Dexie.ignoreTransaction(() => {\n // By default, this node will become master unless we discover an existing, up-to-date master\n var mySyncNodeShouldBecomeMaster = 1;\n return db._syncNodes.orderBy('isMaster').reverse().modify(existingNode => {\n if (existingNode.isMaster) {\n if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Existing master record is out-of-date; demote it\n existingNode.isMaster = 0;\n } else {\n // An existing up-to-date master record exists, so it will remain master\n mySyncNodeShouldBecomeMaster = 0;\n }\n }\n\n // The local node reference may be unassigned at any point by a database close() operation\n if (!mySyncNode.node) return;\n\n // Assign the local node state\n // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause\n if (existingNode.id === mySyncNode.node.id) {\n existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster;\n }\n });\n })).then(() => {\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 }).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.version = \"{version}\";\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\nif (Dexie.Observable) {\n if (Dexie.Observable.version !== \"{version}\") {\n throw new Error (`Mixed versions of dexie-observable`);\n }\n} else {\n // Register addon:\n Dexie.Observable = Observable;\n Dexie.addons.push(Observable);\n}\n\nexport default Dexie.Observable;\n"],"names":["Dexie","Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAAgB,GAAG,MAAK;aAER,eAAe,CAAC,EAAE,EAAE,EAAE;QACpC,IAAI,EAAE,KAAK,GAAG;YAAE,OAAO,EAAE,CAAC;QAC1B,OAAO;YACL,IAAI,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;YACpC,IAAI,GAAG,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,EAAE;gBACzC,IAAI,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;gBAClC,OAAO,GAAG,CAAC,IAAI,CAAC;oBACd,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;iBAC7B,CAAC,CAAC;aACJ;YACD,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SAClC,CAAC;IACJ,CAAC;aAEe,UAAU;;QAExB,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACnB,IAAI,IAAI,GAAG,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAS,CAAC;YAC3E,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;YAC1C,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;YACvB,OAAO,CAAC,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;SACvD,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IACd;;aCzBwB,6BAA6B,CAAC,EAAE,EAAE,eAA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CAAC;IAElD,UAAU,CAAC,eAAe,GAAG;QACzB,UAAU,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC;IACtC,CAAC,CAAC;IAEF,IAAI;QACA,UAAU,CAAC,gBAAgB,GAAG,MAAM,CAAC,YAAY,CAAC;KACrD;IAAC,OAAO,EAAE,EAAC,GAAE;IAEd;IACA;IACA;IACA,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,EAAE;QAC1B,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;QAC1D,MAAM,CAAC,gBAAgB,CAAC,cAAc,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;KACvE;IAED,IAAIA,yBAAK,CAAC,UAAU,EAAE;QAClB,IAAIA,yBAAK,CAAC,UAAU,CAAC,OAAO,KAAK,WAAW,EAAE;YAC1C,MAAM,IAAI,KAAK,CAAE,oCAAoC,CAAC,CAAC;SAC1D;KACJ;SAAM;;QAEHA,yBAAK,CAAC,UAAU,GAAG,UAAU,CAAC;QAC9BA,yBAAK,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;KACjC;AAED,2BAAeA,yBAAK,CAAC,UAAU;;;;;;;;"} \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.min.js b/addons/Dexie.Observable/dist/dexie-observable.min.js new file mode 100644 index 000000000..fb74d0f3b --- /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="undefined"!=typeof globalThis?globalThis:e||self).Dexie=e.Dexie||{},e.Dexie.Observable=n(e.Dexie))})(this,function(e){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var N=n(e);function T(){}function S(o,i){return o===T?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 u(){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)})}var l=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=u(),s.schema.primKey.keyPath&&N.default.setByKeyPath(e,s.schema.primKey.keyPath,n));var i={source:t.source||null,table:s.name,key:void 0===n?null:n,type:l,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=N.default.deepClone(t);for(var s in e){var u=e[s];if(void 0===u)N.default.delByKeyPath(a,s),r=!(i[s]=null);else{var l=N.default.getByKeyPath(t,s);u!==l&&JSON.stringify(u)!==JSON.stringify(l)&&(N.default.setByKeyPath(a,s,u),i[s]=u,r=!0)}}if(r){var c={source:o.source||null,table:m,key:n,type:v,mods:i,oldObj:t,obj:a},d=f._changes.add(c);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 c=N.default.Promise;function M(r,a,e,s,u){var l={};function n(){return s.node?N.default.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=l[n.requestId.toString()];e&&(n.isFailure?e.reject(n.message.error):e.resolve(n.message.result),delete l[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()})})}):c.reject(new N.default.DatabaseClosedError)}return r.observable.sendMessage=function(e,n,t,o){if(o=o||{},!s.node)return o.wantReply?c.reject(new N.default.DatabaseClosedError):c.resolve();var i={message:n,destinationNode:t,sender:s.node.id,type:e};return N.default.extend(i,o),N.default.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 c(function(e,n){l[t.toString()]={resolve:e,reject:n}})),u&&u.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;N.default.ignoreTransaction(function(){r._syncNodes.toArray(function(e){return c.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 j(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,B=self,C=N.default.defineClass({rev:Number,source:String,table:String,key:Object,type:Number,obj:Object,mods:Object,oldObj:Object}),I=N.default.override,k=N.default.Promise,E=!1;function H(a){if(!/^3\./.test(N.default.version))throw new Error("Missing dexie version 3.x");if(a.observable){if("3.0.0-beta.11"!==a.observable.version)throw new Error("Mixed versions of dexie-observable")}else{var o=2e4,i=2e4,t=500,r=o-5e3,s=H.localStorageImpl,u=N.default.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={version:"3.0.0-beta.11"},a.observable.SyncNode=u;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&&N.default.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,N.default.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=B.localStorage}catch(e){}if((null==B?void 0:B.addEventListener)&&(B.addEventListener("storage",H._onStorage),B.addEventListener("beforeunload",H._onBeforeUnload)),N.default.Observable){if("3.0.0-beta.11"!==N.default.Observable.version)throw new Error("Mixed versions of dexie-observable")}else N.default.Observable=H,N.default.addons.push(H);return N.default.Observable}); \ 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..9b84ae579 --- /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","globalThis","self","Dexie","Observable","this","_interopDefaultLegacy","e","default","Dexie__default","nop","promisableChain","f1","f2","res","apply","arguments","then","thiz","args","createUUID","d","Date","now","replace","c","r","Math","random","floor","toString","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","console","log","stack","initDeletingHook","Promise$2","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","DatabaseChange","defineClass","Number","String","override","Promise$1","browserIsShuttingDown","test","version","Error","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","_uncommittedChanges","Version","prototype","_parseStoresSpec","addEventType","changes","cleanup","_createTransaction","open","close","origClose","unsubscribe","onLatestRevisionIncremented","onSuicide","onBeforeUnload","suicideNurseCall","origDelete","orderBy","last","lastChange","latestRevisionIncremented","mySyncNodeShouldBecomeMaster","reverse","modify","existingNode","poll","heartbeat","handledRevision","vip","readChanges","recursion","wasPartial","ongoingOperation","partial","ourSyncNode","limit","length","ourNodeStillExists","syncNode","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":"CAsBA,SAAWA,EAAQC,GACI,iBAAZC,SAA0C,oBAAXC,OAAyBA,OAAOD,QAAUD,EAAQG,QAAQ,UAC9E,mBAAXC,QAAyBA,OAAOC,IAAMD,OAAO,CAAC,SAAUJ,KAC9DD,EAA+B,oBAAfO,WAA6BA,WAAaP,GAAUQ,MAAcC,MAAQT,EAAOS,OAAS,GAAIT,EAAOS,MAAMC,WAAaT,EAAQD,EAAOS,SAH5J,CAIGE,KAAM,SAAWF,GAAS,aAEzB,SAASG,EAAuBC,GAAK,OAAOA,GAAkB,iBAANA,GAAkB,YAAaA,EAAIA,EAAI,CAAEC,QAAWD,GAE5G,IAAIE,EAA8BH,EAAsBH,GAExD,SAASO,KACT,SAASC,EAAgBC,EAAIC,GACzB,OAAID,IAAOF,EACAG,EACJ,WACH,IAAIC,EAAMF,EAAGG,MAAMV,KAAMW,WACzB,GAAIF,GAA2B,mBAAbA,EAAIG,KAAqB,CACvC,IAAIC,EAAOb,KAAMc,EAAOH,UACxB,OAAOF,EAAIG,KAAK,WACZ,OAAOJ,EAAGE,MAAMG,EAAMC,KAG9B,OAAON,EAAGE,MAAMV,KAAMW,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,MA+E1D,IAAIC,EAAS,EACTC,EAAS,EACTC,EAAS,EA8Hb,SAASC,EAAgBC,GAIrB,OAAO,SAAqBC,GAExB,IAAIA,EAAMC,KAAKC,WAAf,CAEAF,EAAMC,KAAKC,YAAa,EACxB,IAAIC,EAAYH,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/K,EAAOkG,aAEzC,MAAOmM,IAQP,IAJIrS,MAAAA,OAAuC,EAASA,EAAOsS,oBACvDtS,EAAOsS,iBAAiB,UAAW5R,EAAWiR,YAC9C3R,EAAOsS,iBAAiB,eAAgB5R,EAAWyR,kBAEnDpR,EAAwB,QAAEL,YAC1B,GAAqD,kBAAjDK,EAAwB,QAAEL,WAAW+J,QACrC,MAAM,IAAIC,MAAM,2CAKpB3J,EAAwB,QAAEL,WAAaA,EACvCK,EAAwB,QAAEwR,OAAOlK,KAAK3H,GAI1C,OAFuBK,EAAwB,QAAEL"} \ 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..79f7966af --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.d.ts @@ -0,0 +1,111 @@ +// Type definitions for dexie-syncable v3.0.0-beta.10 +// Project: https://github.com/dfahlander/Dexie.js/tree/master/addons/Dexie.Syncable +// Definitions by: David Fahlander + +import Dexie, { DexieEventSet } from 'dexie'; +import 'dexie-observable'; +import { ISyncProtocol, SyncStatus } from '../api'; +import {IDatabaseChange} from 'dexie-observable/api'; + + +export interface SyncableEventSet extends DexieEventSet { + (eventName: 'statusChanged', subscriber: (status: number, url: string) => void): void; +} + +// +// Extend Dexie interface +// +declare module 'dexie' { + interface Dexie { + syncable: { + version: string; + /** + * 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: 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; + } + + interface DexieConstructor { + Syncable: { + (db: Dexie) : void; + + version: string; + + /** + * See documentation at: + * https://dexie.org/docs/Syncable/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}; + } + } +} + +// +// Extend dexie-observable interfaces +// +declare module "dexie-observable" { + // Extend SyncNode interface from Dexie.Observable to + // allow storing remote nodes in table _syncNodes. + 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 + } + } +} + +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..e598b3eef --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.es.js @@ -0,0 +1,1214 @@ +/* ========================================================================== + * 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} + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; +import 'dexie-observable'; + +var Promise$3 = 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$3.reject(new Dexie.DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$3.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$3(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); + 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(); + } + } + // 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} + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +var override = Dexie.override, Promise$1 = Dexie.Promise, Observable = Dexie.Observable; +/** Dexie addon for remote database sync. + * + * @param {Dexie} db + */ +function Syncable(db) { + if (!/^3\./.test(Dexie.version)) + throw new Error("Missing dexie version 3.x"); + if (!db.observable || (db.observable.version !== "{version}" && !/^3\./.test(db.observable.version))) + throw new Error("Missing dexie-observable version 3.x"); + if (db.syncable) { + if (db.syncable.version !== "{version}") + throw new Error("Mixed versions of dexie-syncable"); + return; // Addon already active. + } + 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$1.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 = { + version: "{version}" + }; + 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$1.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$1.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise$1.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$1.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.version = "{version}"; +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; +}; +if (Dexie.Syncable) { + if (Dexie.Syncable.version !== "{version}") { + throw new Error("Mixed versions of dexie-syncable"); + } +} +else { + // Register addon in Dexie: + Dexie.Syncable = Syncable; + Dexie.addons.push(Syncable); +} +var Dexie_Syncable = Dexie.Syncable; + +export { Dexie_Syncable as default }; diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.js b/addons/Dexie.Syncable/dist/dexie-syncable.js new file mode 100644 index 000000000..a61aa8d7e --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js @@ -0,0 +1,1223 @@ +/* ========================================================================== + * 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 3.0.0-beta.10, Tue Feb 13 2024 + * + * https://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 = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.Dexie = global.Dexie || {}, global.Dexie.Syncable = factory(global.Dexie))); +})(this, (function (Dexie) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var Dexie__default = /*#__PURE__*/_interopDefaultLegacy(Dexie); + + var Promise$3 = Dexie__default["default"].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$3.reject(new Dexie__default["default"].DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$3.reject(new Dexie__default["default"].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$3(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__default["default"].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__default["default"].extend(this, otherProps); + } + PersistedContext.prototype.save = function () { + // Store this instance in the syncContext property of the node it belongs to. + return Dexie__default["default"].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__default["default"].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__default["default"].ignoreTransaction(function () { + return Dexie__default["default"].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__default["default"].Promise.reject(new Dexie__default["default"].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__default["default"].Promise.reject(new Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]); + }); + return clonedChange; + } + + function combineUpdateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].deepClone(node.dbUploadState), [], collection); + } + else { + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(Dexie__default["default"].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__default["default"].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__default["default"].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); + 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__default["default"].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__default["default"].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__default["default"].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(); + } + } + // 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__default["default"].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__default["default"].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__default["default"].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__default["default"].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 3.0.0-beta.10, Tue Feb 13 2024 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + var override = Dexie__default["default"].override, Promise$1 = Dexie__default["default"].Promise, Observable = Dexie__default["default"].Observable; + /** Dexie addon for remote database sync. + * + * @param {Dexie} db + */ + function Syncable(db) { + if (!/^3\./.test(Dexie__default["default"].version)) + throw new Error("Missing dexie version 3.x"); + if (!db.observable || (db.observable.version !== "3.0.0-beta.10" && !/^3\./.test(db.observable.version))) + throw new Error("Missing dexie-observable version 3.x"); + if (db.syncable) { + if (db.syncable.version !== "3.0.0-beta.10") + throw new Error("Mixed versions of dexie-syncable"); + return; // Addon already active. + } + var activePeers = []; + var connectFn = initConnectFn(db, activePeers); + var syncableConnect = initSyncableConnect(db, connectFn); + db.on('message', function (msg) { + // Message from other local node arrives... + Dexie__default["default"].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__default["default"].ignoreTransaction(function () { return Dexie__default["default"].vip(function () { + return db._syncNodes.where({ type: 'remote' }) + .filter(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { return Promise$1.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 = { + version: "3.0.0-beta.10" + }; + db.syncable.getStatus = function (url, cb) { + if (db.isOpen()) { + return Dexie__default["default"].vip(function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node ? node.status : Statuses.OFFLINE; + }); + }).then(cb); + } + else { + return Promise$1.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__default["default"].Events(db, { statusChanged: "asap" }); + db.syncable.disconnect = function (url) { + return Dexie__default["default"].ignoreTransaction(function () { + return Promise$1.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise$1.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$1.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.version = "3.0.0-beta.10"; + 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; + }; + if (Dexie__default["default"].Syncable) { + if (Dexie__default["default"].Syncable.version !== "3.0.0-beta.10") { + throw new Error("Mixed versions of dexie-syncable"); + } + } + else { + // Register addon in Dexie: + Dexie__default["default"].Syncable = Syncable; + Dexie__default["default"].addons.push(Syncable); + } + var Dexie_Syncable = Dexie__default["default"].Syncable; + + return Dexie_Syncable; + +})); 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..9221e5c2c --- /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="undefined"!=typeof globalThis?globalThis:e||self).Dexie=e.Dexie||{},e.Dexie.Syncable=n(e.Dexie))})(this,function(e){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var R=n(e),s=R.default.Promise;function d(e){return n.prototype.save=function(){return R.default.vip(function(){return e.save()})},n;function n(e,n){this.nodeID=e,n&&R.default.extend(this,n)}}var y=1,h=2,u=3;function O(c){return function(e){var i={};e.forEach(function(e){var n;i.hasOwnProperty(e.table)||(i[e.table]=((n={})[y]=[],n[u]=[],n[h]=[],n)),i[e.table][e.type].push(e)});var n=Object.keys(i),t=n.map(function(e){return c.table(e)});return c.transaction("rw",t,function(){n.forEach(function(e){var n=c.table(e),t=!n.schema.primKey.keyPath,r=i[e][y],o=i[e][u],a=i[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.default.deepClone(e);return Object.keys(n.mods).forEach(function(e){R.default.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.default.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.default.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 a={},i=0,o=!1,c=l.id,s=e;return u.transaction("r",u._changes,function(){return u._changes.where("rev").between(e,t,!1,!0).until(function(){if(i===n)return o=!0}).each(function(e){if(s=e.rev,e.source!==c){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=a[t];if(r){var o=b(r,n);a[t]=o}else a[t]=n,++i}})}).then(function(){var e=Object.keys(a).map(function(e){return a[e]});return f.hasMoreToGive=o,r(e,o,{myRevision:s})})}}(s,e,u),t=function(i,c,s,u,l,f){return function e(t,o,n){var a=!1;return n.until(function(){if(o.length===s)return a=!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(a)return l.hasMoreToGive=!0,f(o,null,!0,{dbUploadState:t});if(0!==t.tablesToUpload.length)return t.currentTable=t.tablesToUpload.shift(),e(t,o,i.table(t.currentTable).orderBy(":id"));var r=v(c);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 a=s.tables.filter(function(e){return e.schema.observable}).map(function(e){return e.name});if(0===a.length)return R.default.Promise.resolve(r([],null,!1,{}));var i={tablesToUpload:a,currentTable:a.shift(),currentKey:null};return s._changes.orderBy("rev").last(function(e){i.localBaseRevision=e&&e.rev||0;var n=s.table(i.currentTable).orderBy(":id");return t(i,[],n)})}if(e.dbUploadState.currentKey){var c=s.table(e.dbUploadState.currentTable).where(":id").above(e.dbUploadState.currentKey);return t(R.default.deepClone(e.dbUploadState),[],c)}c=s.table(i.currentTable).orderBy(":id");return t(R.default.deepClone(e.dbUploadState),[],c)}}var w={ERROR:-1,OFFLINE:0,CONNECTING:1,ONLINE:2,SYNCING:3,ERROR_WILL_RETRY:4},E=R.default.Promise;function p(b,p,a,m,g){var i=function(a){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.default.ignoreTransaction(function(){return R.default.vip(function(){return t()})}).finally(function(){delete n.ongoingOperation}),n.ongoingOperation}return r?a._localSyncNode&&r===a._localSyncNode.id?o():R.default.Promise.reject(new R.default.DatabaseClosedError):a.isOpen()?o():R.default.Promise.reject(new R.default.DatabaseClosedError)}}(b),t={hasMoreToGive:!0};function N(){return b._localSyncNode&&b._localSyncNode.id===a}return function(s,u){var l,c=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(w.CONNECTING),y();function y(){return i(y,function(){return n(s,e)},a)}function e(e,o,a,n){var t=new E(function(t,r){g.p=function(e){r(e)},R.default.asap(function(){try{p.sync(s.syncContext,f,m,o,s.appliedRemoteRevision,e,a,v,i,function(e){t(e)},n)}catch(e){n(e,1/0)}function n(e,n){r(e),N()&&(!isNaN(n)&&n<1/0?(setTimeout(function(){N()&&(d(w.SYNCING),y().catch("DatabaseClosedError",h))},n),d(w.ERROR_WILL_RETRY),l&&l.disconnect&&l.disconnect(),l=null):h(e))}})});return t.then(function(){}).finally(function(){g.p=null});function i(){return Object.keys(n).forEach(function(e){R.default.setByKeyPath(s,e,n[e])}),t.then(r),s.save()}}function h(e){u.disconnect(w.ERROR,e)}function n(a,i){return c(a,function e(n,t,r,o){return 0===n.length&&"myRevision"in o&&o.myRevision!==a.myRevision?(Object.keys(o).forEach(function(e){R.default.setByKeyPath(a,e,o[e])}),a.save().catch("DatabaseClosedError",function(){}),c(a,e)):i(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,a){var i=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.default.currentTransaction,r=0;return t._changes.orderBy("rev").last(function(e){r=e&&e.rev||0}).then(function(){return e.source=a.id,t._uncommittedChanges.where("node").equals(a.id).toArray()}).then(function(e){return i(e)}).then(function(){return t._uncommittedChanges.where("node").equals(a.id).delete()}).then(function(){return i(n)}).then(function(){return t._changes.orderBy("rev").last()}).then(function(e){var n=e&&e.rev||0;if(a.appliedRemoteRevision=o,a.remoteBaseRevisions.push({remote:o,local:n}),a.myRevision===r&&(a.myRevision=n),1=a.remoteBaseRevisions[t].local){a.remoteBaseRevisions.splice(0,t);break}a.save().catch(function(e){console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: "+(e.stack||e))})})})}}(b,s);return i(v,function(){return N()?(t?r(e,n):o(e,n)).catch(function(e){return h(e),E.reject(e)}):E.reject(new R.default.DatabaseClosedError)},a)}function r(e){N()?(l=e,u.on("disconnect",function(){if(l){if(l.react)try{l.disconnect()}catch(e){}l=null}}),e.react?function(o){var a,i;function e(){l&&(d(w.SYNCING),i?a=!0:c())}function c(){l&&(i=!(a=!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 } + }; + 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__default['default'].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 (_b) { + switch (_b.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 (_c) { + switch (_c.label) { + case 0: + if (progressCallback) { + // Keep ongoing transaction private + Dexie__default['default'].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 = _c.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__default['default'].waitFor(TSON.finalize(tsonValues))]; + case 2: + _c.sent(); + _c.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__default['default'].getByKeyPath(values[values.length - 1], primKey.keyPath) : + null; + return [3 /*break*/, 8]; + case 4: return [4 /*yield*/, chunkedCollection.primaryKeys()]; + case 5: + keys = _c.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__default['default'].waitFor(TSON.finalize(tsonTuples))]; + case 6: + _c.sent(); + _c.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; + _c.label = 8; + case 8: + progress.completedRows += values.length; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!mayHaveMoreRows) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_2()]; + case 2: + state_1 = _b.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__default['default'].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__default['default'].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; + (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__default['default'](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 peakImportFile(exportedData) { + return __awaiter(this, void 0, void 0, function () { + var stream; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = JsonStream(exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(5 * 1024)]; + case 2: + _a.sent(); // 5 k is normally enough for the headers. If not, it will just do another go. + if (stream.result.data && stream.result.data.data) { + // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it. + delete stream.result.data.data; // Don't return half-baked data array. + return [3 /*break*/, 3]; + } + return [3 /*break*/, 1]; + case 3: return [2 /*return*/, stream.result]; + } + }); + }); + } + 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, _c, keys, values; + return __generator(this, function (_d) { + switch (_d.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__default['default'].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; + _c = tableExport.inbound ? + [undefined, filteredRows] : + [filteredRows.map(function (row) { return row[0]; }), rows.map(function (row) { return row[1]; })], keys = _c[0], values = _c[1]; + if (!options.overwriteValues) return [3 /*break*/, 2]; + return [4 /*yield*/, table.bulkPut(values, keys)]; + case 1: + _d.sent(); + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, table.bulkAdd(values, keys)]; + case 3: + _d.sent(); + _d.label = 4; + case 4: + 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__default['default'].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]; + case 10: return [2 /*return*/]; + } + }); + }); + } + var CHUNK_SIZE, jsonStream, dbExportFile, readBlobsSynchronously, dbExport, progressCallback, progress, _i, _a, table; + return __generator(this, function (_b) { + switch (_b.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 = _b.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__default['default'].ignoreTransaction(function () { return progressCallback(progress); }); + } + if (!options.clearTablesBeforeImport) return [3 /*break*/, 5]; + _i = 0, _a = db.tables; + _b.label = 2; + case 2: + if (!(_i < _a.length)) return [3 /*break*/, 5]; + table = _a[_i]; + return [4 /*yield*/, table.clear()]; + case 3: + _b.sent(); + _b.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + if (!options.noTransaction) return [3 /*break*/, 7]; + return [4 /*yield*/, importAll()]; + case 6: + _b.sent(); + return [3 /*break*/, 9]; + case 7: return [4 /*yield*/, db.transaction('rw', db.tables, importAll)]; + case 8: + _b.sent(); + _b.label = 9; + case 9: + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie__default['default'].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__default['default'].prototype.export = function (options) { + return exportDB(this, options); + }; + Dexie__default['default'].prototype.import = function (blob, options) { + return importInto(this, blob, options); + }; + Dexie__default['default'].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.default = dexieExportImport; + exports.exportDB = exportDB; + exports.importDB = importDB; + exports.importInto = importInto; + exports.peakImportFile = peakImportFile; + + 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..55b40e5f2 --- /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.\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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\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 var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, 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\n/** @deprecated */\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\n/** @deprecated */\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 __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\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\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\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 (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, 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, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\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 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\n/** Same as DexieExportJsonStructure but without the data.data array */\nexport interface DexieExportJsonMeta {\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 }\n}\n\nexport interface DexieExportJsonStructure extends DexieExportJsonMeta {\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 { DexieExportJsonMeta, 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 peakImportFile(exportedData: Blob): Promise {\n const stream = JsonStream(exportedData);\n while (!stream.eof()) {\n await stream.pullAsync(5 * 1024); // 5 k is normally enough for the headers. If not, it will just do another go.\n if (stream.result.data && stream.result.data!.data) {\n // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it.\n delete stream.result.data.data; // Don't return half-baked data array.\n break;\n }\n }\n return stream.result as DexieExportJsonMeta;\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!.clearTablesBeforeImport) {\n for (const table of db.tables) {\n await table.clear();\n }\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!.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, peakImportFile, ImportOptions, importInto, StaticImportOptions } from './import';\nimport { DexieExportJsonMeta } from './json-structure';\n\nexport { exportDB, ExportOptions};\nexport { importDB, importInto, peakImportFile, ImportOptions, DexieExportJsonMeta};\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","Dexie","require$$0","clarinet"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AAuDA;IACO,SAAS,SAAS,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE;IAC7D,IAAI,SAAS,KAAK,CAAC,KAAK,EAAE,EAAE,OAAO,KAAK,YAAY,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC,CAAC,UAAU,OAAO,EAAE,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE;IAChH,IAAI,OAAO,KAAK,CAAC,K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--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..05087b48d --- /dev/null +++ b/addons/dexie-export-import/dist/dexie-export-import.mjs @@ -0,0 +1,1677 @@ +/* ========================================================================== + * dexie-export-import.js + * ========================================================================== + * + * Dexie addon for exporting and importing databases to / from Blobs. + * + * By David Fahlander, david.fahlander@gmail.com, + * + * ========================================================================== + * + * Version 1.0.3, Tue Feb 13 2024 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from '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. +***************************************************************************** */ + +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 }; + } +} + +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 } + }; + 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 (_b) { + switch (_b.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 (_c) { + switch (_c.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 = _c.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: + _c.sent(); + _c.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 = _c.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: + _c.sent(); + _c.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; + _c.label = 8; + case 8: + progress.completedRows += values.length; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!mayHaveMoreRows) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_2()]; + case 2: + state_1 = _b.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; + (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 peakImportFile(exportedData) { + return __awaiter(this, void 0, void 0, function () { + var stream; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = JsonStream(exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(5 * 1024)]; + case 2: + _a.sent(); // 5 k is normally enough for the headers. If not, it will just do another go. + if (stream.result.data && stream.result.data.data) { + // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it. + delete stream.result.data.data; // Don't return half-baked data array. + return [3 /*break*/, 3]; + } + return [3 /*break*/, 1]; + case 3: return [2 /*return*/, stream.result]; + } + }); + }); +} +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, _c, keys, values; + return __generator(this, function (_d) { + switch (_d.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; + _c = tableExport.inbound ? + [undefined, filteredRows] : + [filteredRows.map(function (row) { return row[0]; }), rows.map(function (row) { return row[1]; })], keys = _c[0], values = _c[1]; + if (!options.overwriteValues) return [3 /*break*/, 2]; + return [4 /*yield*/, table.bulkPut(values, keys)]; + case 1: + _d.sent(); + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, table.bulkAdd(values, keys)]; + case 3: + _d.sent(); + _d.label = 4; + case 4: + 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]; + case 10: return [2 /*return*/]; + } + }); + }); + } + var CHUNK_SIZE, jsonStream, dbExportFile, readBlobsSynchronously, dbExport, progressCallback, progress, _i, _a, table; + return __generator(this, function (_b) { + switch (_b.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 = _b.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.clearTablesBeforeImport) return [3 /*break*/, 5]; + _i = 0, _a = db.tables; + _b.label = 2; + case 2: + if (!(_i < _a.length)) return [3 /*break*/, 5]; + table = _a[_i]; + return [4 /*yield*/, table.clear()]; + case 3: + _b.sent(); + _b.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + if (!options.noTransaction) return [3 /*break*/, 7]; + return [4 /*yield*/, importAll()]; + case 6: + _b.sent(); + return [3 /*break*/, 9]; + case 7: return [4 /*yield*/, db.transaction('rw', db.tables, importAll)]; + case 8: + _b.sent(); + _b.label = 9; + case 9: + 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, peakImportFile }; +//# 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..d1fb565b1 --- /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.\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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\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 var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, 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\n/** @deprecated */\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\n/** @deprecated */\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 __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\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\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\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 (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, 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, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\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 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\n/** Same as DexieExportJsonStructure but without the data.data array */\nexport interface DexieExportJsonMeta {\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 }\n}\n\nexport interface DexieExportJsonStructure extends DexieExportJsonMeta {\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 { DexieExportJsonMeta, 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 peakImportFile(exportedData: Blob): Promise {\n const stream = JsonStream(exportedData);\n while (!stream.eof()) {\n await stream.pullAsync(5 * 1024); // 5 k is normally enough for the headers. If not, it will just do another go.\n if (stream.result.data && stream.result.data!.data) {\n // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it.\n delete stream.result.data.data; // Don't return half-baked data array.\n break;\n }\n }\n return stream.result as DexieExportJsonMeta;\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!.clearTablesBeforeImport) {\n for (const table of db.tables) {\n await table.clear();\n }\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!.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, peakImportFile, ImportOptions, importInto, StaticImportOptions } from './import';\nimport { DexieExportJsonMeta } from './json-structure';\n\nexport { exportDB, ExportOptions};\nexport { importDB, importInto, peakImportFile, ImportOptions, DexieExportJsonMeta};\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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAuDA;AACO,SAAS,SAAS,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE;AAC7D,IAAI,SAAS,KAAK,CAAC,KAAK,EAAE,EAAE,OAAO,KAAK,YAAY,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC,CAAC,UAAU,OAAO,EAAE,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE;AAChH,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,EAAE,UAAU,OAAO,EAAE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E;wBACzC,MAAM,IAAI,KAAK,CAAC,oBAAkB,YAAY,CAAC,aAAa,mBAAgB,CAAC,CAAC;qBAC/E;oBACD,IAAI,CAAC,YAAY,CAAC,IAAK,EAAE;wBACvB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;qBAC3C;oBACD,IAAI,CAAC,YAAY,CAAC,IAAK,CAAC,YAAY,EAAE;wBACpC,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;qBACxD;oBACD,IAAI,CAAC,YAAY,CAAC,IAAK,CAAC,eAAe,EAAE;wBACvC,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;qBAC3D;oBACD,IAAI,CAAC,YAAY,CAAC,IAAK,CAAC,MAAM,EAAE;wBAC9B,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;qBAClD;oBACD,sBAAO,MAAM,EAAC;;;;;;ACjMhB;AACA;AACA;AAEA,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,OAAuB;IACrE,OAAO,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjC,CAAC,CAAC;AACF,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,IAAU,EAAE,OAAuB;IACjF,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;AACzC,CAAC,CAAC;AACF,KAAK,CAAC,MAAM,GAAG,UAAC,IAAU,EAAE,OAA6B,IAAK,OAAA,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,GAAA,CAAC;AAEtF,yBAAe;IACb,MAAM,IAAI,KAAK,CAAC,kHAAkH,CAAC,CAAA;AACrI,CAAC;;;;;"} \ No newline at end of file diff --git a/addons/dexie-export-import/package-lock.json b/addons/dexie-export-import/package-lock.json index 4a9ef6f58..cffd15a30 100644 --- a/addons/dexie-export-import/package-lock.json +++ b/addons/dexie-export-import/package-lock.json @@ -5,6 +5,7 @@ "requires": true, "packages": { "": { + "name": "dexie-export-import", "version": "1.0.3", "license": "Apache-2.0", "devDependencies": { 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..c20aaf588 --- /dev/null +++ b/dist/dexie.d.ts @@ -0,0 +1,1028 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 3.2.6, Tue Feb 13 2024 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + // Generated by dts-bundle-generator v5.9.0 + +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; +} +export interface DBCoreTransaction { + abort(): void; +} +export interface DbCoreTransactionOptions { + durability: ChromeTransactionDurability; +} +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. +} +export interface DBCoreAddRequest { + type: "add"; + trans: DBCoreTransaction; + values: any[]; + keys?: any[]; + /** @deprecated Will always get results since 3.1.0-alpha.5 */ + wantResults?: boolean; +} +export interface DBCorePutRequest { + type: "put"; + trans: DBCoreTransaction; + values: any[]; + keys?: any[]; + criteria?: { + index: string | null; + range: DBCoreKeyRange; + }; + changeSpec?: { + [keyPath: string]: any; + }; // Common changeSpec for each key + changeSpecs?: { + [keyPath: string]: any; + }[]; // changeSpec per key. + /** @deprecated Will always get results since 3.1.0-alpha.5 */ + wantResults?: boolean; +} +export interface DBCoreDeleteRequest { + type: "delete"; + trans: DBCoreTransaction; + keys: any[]; + criteria?: { + index: string | null; + range: DBCoreKeyRange; + }; +} +export interface DBCoreDeleteRangeRequest { + type: "deleteRange"; + trans: DBCoreTransaction; + range: DBCoreKeyRange; +} +export interface DBCoreGetManyRequest { + trans: DBCoreTransaction; + keys: any[]; + cache?: "immutable" | "clone"; +} +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 (https://dexie.org/docs/inbound) */ + readonly outbound?: boolean; + /** True if and only if keyPath is an array (https://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). Null for outbound primary keys */ + readonly extractKey: ((value: any) => any) | null; +} +export interface DBCore { + stack: "dbcore"; + // Transaction and Object Store + transaction(stores: string[], mode: "readonly" | "readwrite", options?: DbCoreTransactionOptions): DBCoreTransaction; + // Utility methods + 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<(T | undefined)[]>; + bulkAdd(items: readonly T[], keys: IndexableTypeArrayReadonly, options: { + allKeys: B; + }): PromiseExtended; + bulkAdd(items: readonly T[], options: { + allKeys: B; + }): PromiseExtended; + bulkAdd(items: readonly T[], keys?: IndexableTypeArrayReadonly, options?: { + allKeys: boolean; + }): PromiseExtended; + bulkPut(items: readonly T[], keys: IndexableTypeArrayReadonly, options: { + allKeys: B; + }): PromiseExtended; + bulkPut(items: readonly T[], options: { + allKeys: B; + }): PromiseExtended; + bulkPut(items: readonly T[], keys?: IndexableTypeArrayReadonly, options?: { + allKeys: boolean; + }): PromiseExtended; + bulkDelete(keys: TKey[]): PromiseExtended; +} +export interface Version { + stores(schema: { + [tableName: string]: string | null; + }): Version; + upgrade(fn: (trans: Transaction) => PromiseLike | void): Version; +} +export type IntervalTree = IntervalTreeNode | EmptyRange; +export interface IntervalTreeNode { + from: IndexableType; // lower bound + to: IndexableType; // upper bound + l: IntervalTreeNode | null; // left + r: IntervalTreeNode | null; // right + d: number; // depth +} +export interface EmptyRange { + d: 0; +} +export interface DexieOnReadyEvent { + subscribe(fn: (vipDb: Dexie) => any, bSticky: boolean): void; + unsubscribe(fn: (vipDb: Dexie) => any): void; + fire(vipDb: Dexie): 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 DexieCloseEvent { + subscribe(fn: (event: Event) => any): void; + unsubscribe(fn: (event: Event) => any): void; + fire(event: Event): any; +} +export interface DbEvents extends DexieEventSet { + (eventName: "ready", subscriber: (vipDb: Dexie) => 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; + (eventName: "close", subscriber: (event: Event) => any): void; + ready: DexieOnReadyEvent; + populate: DexiePopulateEvent; + blocked: DexieEvent; + versionchange: DexieVersionChangeEvent; + close: DexieCloseEvent; +} +export type ObservabilitySet = { + // `idb:${dbName}/${tableName}/changedRowContents` - keys. + // `idb:${dbName}/${tableName}/changedIndexes/${indexName}` - indexes + [part: string]: IntervalTree; +}; +export interface DexieOnStorageMutatedEvent { + subscribe(fn: (parts: ObservabilitySet) => any): void; + unsubscribe(fn: (parts: ObservabilitySet) => any): void; + fire(parts: ObservabilitySet): any; +} +export interface GlobalDexieEvents extends DexieEventSet { + (eventName: "storagemutated", subscriber: (parts: ObservabilitySet) => any): void; + storagemutated: DexieOnStorageMutatedEvent; +} +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 vip: Dexie; + 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. + * + * https://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 https://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 = { + // https://dexie.org/docs/DexieErrors/Dexie.OpenFailedError + OpenFailed: "OpenFailedError"; + // https://dexie.org/docs/DexieErrors/Dexie.VersionChangeError + VersionChange: "VersionChangeError"; + // https://dexie.org/docs/DexieErrors/Dexie.SchemaError + Schema: "SchemaError"; + // https://dexie.org/docs/DexieErrors/Dexie.UpgradeError + Upgrade: "UpgradeError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidTableError + InvalidTable: "InvalidTableError"; + // https://dexie.org/docs/DexieErrors/Dexie.MissingAPIError + MissingAPI: "MissingAPIError"; + // https://dexie.org/docs/DexieErrors/Dexie.NoSuchDatabaseError + NoSuchDatabase: "NoSuchDatabaseError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidArgumentError + InvalidArgument: "InvalidArgumentError"; + // https://dexie.org/docs/DexieErrors/Dexie.SubTransactionError + SubTransaction: "SubTransactionError"; + // https://dexie.org/docs/DexieErrors/Dexie.UnsupportedError + Unsupported: "UnsupportedError"; + // https://dexie.org/docs/DexieErrors/Dexie.InternalError + Internal: "InternalError"; + // https://dexie.org/docs/DexieErrors/Dexie.DatabaseClosedError + DatabaseClosed: "DatabaseClosedError"; + // https://dexie.org/docs/DexieErrors/Dexie.PrematureCommitError + PrematureCommit: "PrematureCommitError"; + // https://dexie.org/docs/DexieErrors/Dexie.ForeignAwaitError + ForeignAwait: "ForeignAwaitError"; + // https://dexie.org/docs/DexieErrors/Dexie.UnknownError + Unknown: "UnknownError"; + // https://dexie.org/docs/DexieErrors/Dexie.ConstraintError + Constraint: "ConstraintError"; + // https://dexie.org/docs/DexieErrors/Dexie.DataError + Data: "DataError"; + // https://dexie.org/docs/DexieErrors/Dexie.TransactionInactiveError + TransactionInactive: "TransactionInactiveError"; + // https://dexie.org/docs/DexieErrors/Dexie.ReadOnlyError + ReadOnly: "ReadOnlyError"; + // https://dexie.org/docs/DexieErrors/Dexie.VersionError + Version: "VersionError"; + // https://dexie.org/docs/DexieErrors/Dexie.NotFoundError + NotFound: "NotFoundError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidStateError + InvalidState: "InvalidStateError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidAccessError + InvalidAccess: "InvalidAccessError"; + // https://dexie.org/docs/DexieErrors/Dexie.AbortError + Abort: "AbortError"; + // https://dexie.org/docs/DexieErrors/Dexie.TimeoutError + Timeout: "TimeoutError"; + // https://dexie.org/docs/DexieErrors/Dexie.QuotaExceededError + QuotaExceeded: "QuotaExceededError"; + // https://dexie.org/docs/DexieErrors/Dexie.DataCloneError + DataClone: "DataCloneError"; +}; +/** ModifyError + * + * https://dexie.org/docs/DexieErrors/Dexie.ModifyError + */ +export interface ModifyError extends DexieError { + failures: Array; + failedKeys: IndexableTypeArrayReadonly; + successCount: number; +} +/** BulkError + * + * https://dexie.org/docs/DexieErrors/Dexie.BulkError + */ +export interface BulkError extends DexieError { + failures: Error[]; + failuresByPos: { + [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; +} +declare global { + interface SymbolConstructor { + readonly observable: symbol; + } +} +export interface Subscribable { + subscribe(observer: Partial>): Unsubscribable; +} +export interface Unsubscribable { + unsubscribe(): void; +} +export interface Observable { + subscribe(observerOrNext?: Observer | ((value: T) => void)): Subscription; + subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription; + getValue?(): T; + hasValue?(): boolean; + [Symbol.observable]: () => Subscribable; +} +export interface Subscription { + unsubscribe(): void; + readonly closed: boolean; +} +export interface Observer { + start?: (subscription: Subscription) => void; + next?: (value: T) => void; + error?: (error: any) => void; + complete?: () => void; +} +export type ChromeTransactionDurability = "default" | "strict" | "relaxed"; +export interface DexieOptions { + addons?: Array<(db: Dexie) => void>; + autoOpen?: boolean; + indexedDB?: { + open: Function; + }; + IDBKeyRange?: { + bound: Function; + lowerBound: Function; + upperBound: Function; + }; + allowEmptyDB?: boolean; + modifyChunkSize?: number; + chromeTransactionDurability?: ChromeTransactionDurability; +} +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; + liveQuery(fn: () => T | Promise): Observable; + extendObservabilitySet(target: ObservabilitySet, newSet: ObservabilitySet): ObservabilitySet; + 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; + on: GlobalDexieEvents; + errnames: DexieErrors; +} +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. +} +export function liveQuery(querier: () => T | Promise): Observable; +export function mergeRanges(target: IntervalTree, newSet: IntervalTree): void; +export function rangesOverlap(rangeSet1: IntervalTree, rangeSet2: IntervalTree): boolean; +/** Exporting 'Dexie' as the default export. + **/ +export default Dexie; + +export {}; diff --git a/dist/dexie.js b/dist/dexie.js new file mode 100644 index 000000000..61dcfee44 --- /dev/null +++ b/dist/dexie.js @@ -0,0 +1,5221 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 3.2.6, Tue Feb 13 2024 + * + * https://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 = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Dexie = factory()); +})(this, (function () { 'use strict'; + + /*! ***************************************************************************** + 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. + ***************************************************************************** */ + 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 __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + + var _global = typeof globalThis !== 'undefined' ? globalThis : + typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; + + var keys = Object.keys; + var isArray = Array.isArray; + 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)); + (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(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$1(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 (typeof keyPath === 'string' && 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 == null ? 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 || !hasOwn(obj, currentKeyPath)) + 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 = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" + .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]; }); + arrayToObject(intrinsicTypeNames, function (x) { return [x, true]; }); + var circularRefs = null; + function deepClone(any) { + circularRefs = typeof WeakMap !== 'undefined' && new WeakMap(); + var rv = innerDeepClone(any); + circularRefs = null; + return rv; + } + function innerDeepClone(any) { + if (!any || typeof any !== 'object') + return any; + var rv = circularRefs && circularRefs.get(any); + if (rv) + return rv; + if (isArray(any)) { + rv = []; + circularRefs && circularRefs.set(any, rv); + for (var i = 0, l = any.length; i < l; ++i) { + rv.push(innerDeepClone(any[i])); + } + } + else if (intrinsicTypes.indexOf(any.constructor) >= 0) { + rv = any; + } + else { + var proto = getProto(any); + rv = proto === Object.prototype ? {} : Object.create(proto); + circularRefs && circularRefs.set(any, rv); + for (var prop in any) { + if (hasOwn(any, prop)) { + rv[prop] = innerDeepClone(any[prop]); + } + } + } + return rv; + } + var toString = {}.toString; + function toStringTag(o) { + return toString.call(o).slice(8, -1); + } + var iteratorSymbol = typeof Symbol !== 'undefined' ? + Symbol.iterator : + '@@iterator'; + var getIteratorOf = typeof iteratorSymbol === "symbol" ? 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 { + getErrorWithStack.arguments; + 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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" + }; + 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 = Object.keys(failures).map(function (pos) { return failures[pos]; }); + this.failuresByPos = 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, + MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], 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 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } + }; + var isOutsideMicroTick = true, + needsNewPhysicalTick = true, + unhandledErrors = [], + rejectingErrors = [], + currentFulfiller = null, 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); + var cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), 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; } + }, + totalEchoes: { get: function () { return totalEchoes; } }, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap; }, + set: function (value) { asap = 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(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(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(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, 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) + extend(psd, props); + ++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() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; + return true; + } + 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, cleanup) { + 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); + if (cleanup) + enqueueNativeMicroTask(decrementExpectedAwaits); + } + }; + } + function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; + } + 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.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { + if (db._state.openComplete) { + return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); + } + 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(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + 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.2.6'; + 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 + }; + + function workaroundForUndefinedPrimKey(keyPath) { + return typeof keyPath === "string" && !/\./.test(keyPath) + ? function (obj) { + if (obj[keyPath] === undefined && (keyPath in obj)) { + obj = deepClone(obj); + delete obj[keyPath]; + } + return obj; + } + : function (obj) { return obj; }; + } + + 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) { + if (ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; })) { + for (var i = 0; i < keyPaths.length; ++i) { + if (keyPaths.indexOf(ix.keyPath[i]) === -1) + return false; + } + return true; + } + return false; + }).sort(function (a, b) { return a.keyPath.length - b.keyPath.length; })[0]; + if (compoundIndex && this.db._maxKey !== maxString) { + var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); + return this + .where(keyPathsInValidOrder) + .equals(keyPathsInValidOrder.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; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); + }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + }; + Table.prototype.update = function (keyOrObject, modifications) { + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === undefined) + return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); + try { + if (typeof modifications !== "function") { + keys(modifications).forEach(function (keyPath) { + setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); + }); + } + else { + modifications(keyOrObject, { value: keyOrObject, primKey: key }); + } + } + catch (_a) { + } + 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; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, 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) { + var _this = this; + return this._trans('readonly', function (trans) { + return _this.core.getMany({ + keys: keys, + 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 = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToAdd = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'add', keys: keys, values: objectsToAdd, 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", failures); + }); + }); + }; + Table.prototype.bulkPut = function (objects, keysOrOptions, options) { + var _this = this; + var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToPut = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'put', keys: keys, values: objectsToPut, 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", failures); + }); + }); + }; + Table.prototype.bulkDelete = function (keys) { + var _this = this; + var numKeys = keys.length; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'delete', keys: keys }); + }).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$1(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(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(); + }); + } + }); + } + + function cmp(a, b) { + try { + var ta = type(a); + var tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; + } + function compareArrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + var res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function compareUint8Arrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function type(x) { + var t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + var tsTag = toStringTag(x); + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; + } + function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); + } + + 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) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props) + extend(ctx, props); + 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 = _this.db._options.modifyChunkSize || 200; + 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) { + var nextChunk = function (offset) { + var count = Math.min(limit, keys.length - offset); + return coreTable.getMany({ + trans: trans, + keys: keys.slice(offset, offset + count), + cache: "immutable" + }).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[offset + i] + }; + if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { + if (ctx_1.value == null) { + deleteKeys.push(keys[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { + deleteKeys.push(keys[offset + i]); + addValues.push(ctx_1.value); + } + else { + putValues.push(ctx_1.value); + if (outbound) + putKeys.push(keys[offset + i]); + } + } + } + var criteria = isPlainKeyRange(ctx) && + ctx.limit === Infinity && + (typeof changes !== 'function' || changes === deleteCallback) && { + index: ctx.index, + range: ctx.range + }; + 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 () { return (putValues.length > 0 || (criteria && typeof changes === 'object')) && + coreTable.mutate({ + trans: trans, + type: 'put', + keys: putKeys, + values: putValues, + criteria: criteria, + changeSpec: typeof changes !== 'function' + && changes + }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && + coreTable.mutate({ + trans: trans, + type: 'delete', + keys: deleteKeys, + criteria: criteria + }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { + return keys.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.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; _a.lastResult; _a.results; var 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(deleteCallback); + }; + return Collection; + }()); + var deleteCallback = function (value, ctx) { return ctx.value = null; }; + + function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection(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: false, + 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) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + 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(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(); + 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 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 DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; + var STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; + var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); + + 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 || + (this.db.core + ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) + : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); + 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(); + if ('mutatedParts' in idbtrans) { + globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); + } + }); + 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 () { + if (this.active) { + this.active = false; + if (this.idbtrans) + this.idbtrans.abort(); + this._reject(new exceptions.Abort()); + } + }; + 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(mode, storeNames, dbschema, chromeTransactionDurability, parent) { + var _this = this; + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.chromeTransactionDurability = chromeTransactionDurability; + 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 safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; + } + var getMaxKey = function (IdbKeyRange) { + try { + IdbKeyRange.only([[]]); + getMaxKey = function () { return [[]]; }; + return [[]]; + } + catch (e) { + getMaxKey = function () { return maxString; }; + return maxString; + } + }; + + 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 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, IdbKeyRange, tmpTrans) { + 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 = _a.keys, values = _a.values, range = _a.range; + 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 || values || { length: 1 }).length; + if (keys && values && keys.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 req; + var reqs = []; + var failures = []; + var numFailures = 0; + var errorHandler = function (event) { + ++numFailures; + preventDefault(event); + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures: numFailures, failures: failures, results: [], lastResult: undefined }); + if (range.type === 3 ) + reqs.push(req = store.clear()); + else + reqs.push(req = store.delete(makeIDBKeyRange(range))); + } + else { + var _a = isAddOrPut ? + outbound ? + [values, keys] : + [values, null] : + [keys, null], args1 = _a[0], args2 = _a[1]; + if (isAddOrPut) { + for (var i = 0; i < length; ++i) { + reqs.push(req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i]))); + req.onerror = errorHandler; + } + } + else { + for (var i = 0; i < length; ++i) { + reqs.push(req = store[type](args1[i])); + req.onerror = errorHandler; + } + } + } + var done = function (event) { + var lastResult = event.target.result; + reqs.forEach(function (req, i) { return req.error != null && (failures[i] = req.error); }); + resolve({ + numFailures: numFailures, + failures: failures, + results: type === "delete" ? keys : reqs.map(function (req) { return req.result; }), + 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 = _a.keys; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var length = keys.length; + var result = new Array(length); + var keyCount = 0; + var callbackCount = 0; + var req; + var successHandler = function (event) { + var req = event.target; + if ((result[req._pos] = req.result) != null) + ; + if (++callbackCount === keyCount) + resolve(result); + }; + var errorHandler = eventRejectHandler(reject); + for (var i = 0; i < length; ++i) { + var key = keys[i]; + if (key != null) { + req = store.get(keys[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]; + }, + 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; _a.indexedDB; + var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore: dbcore + }; + } + function generateMiddlewareStacks(_a, tmpTrans) { + var db = _a._novip; + 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(_a, objs, tableNames, dbschema) { + var db = _a._novip; + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + var propDesc = getPropertyDescriptor(obj, tableName); + if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { + 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(_a, objs) { + var db = _a._novip; + 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(_a, oldVersion, trans, idbUpgradeTrans) { + var db = _a._novip; + 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); + trans._memoizedTables = {}; + 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.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || + (oldDef.primKey.auto !== newDef.primKey.auto && !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) { + [].slice.call(idbtrans.db.objectStoreNames).forEach(function (storeName) { + return 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(_a, idbdb, tmpTrans) { + var db = _a._novip; + 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 verifyInstalledSchema(db, tmpTrans) { + var installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); + var diff = getSchemaDiff(installedSchema, db._dbSchema); + return !(diff.add.length || diff.change.some(function (ch) { return ch.add.length || ch.change.length; })); + } + function adjustToExistingIndexNames(_a, schema, idbtrans) { + var db = _a._novip; + 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 = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); + return this; + }; + return Version; + }()); + + function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); + } + + function getDbNamesTable(indexedDB, IDBKeyRange) { + var dbNamesDB = indexedDB["_dbNamesDB"]; + if (!dbNamesDB) { + dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { + addons: [], + indexedDB: indexedDB, + IDBKeyRange: IDBKeyRange, + }); + dbNamesDB.version(1).stores({ dbnames: "name" }); + } + return dbNamesDB.table("dbnames"); + } + function hasDatabasesNative(indexedDB) { + return indexedDB && typeof indexedDB.databases === "function"; + } + function getDatabaseNames(_a) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + return hasDatabasesNative(indexedDB) + ? Promise.resolve(indexedDB.databases()).then(function (infos) { + return infos + .map(function (info) { return info.name; }) + .filter(function (name) { return name !== DBNAMES_DB; }); + }) + : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); + } + function _onDatabaseCreated(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).put({ name: name }).catch(nop); + } + function _onDatabaseDeleted(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); + } + + function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); + } + + function idbReady() { + var isSafari = !navigator.userAgentData && + /Safari\//.test(navigator.userAgent) && + !/Chrom(e|ium)\//.test(navigator.userAgent); + if (!isSafari || !indexedDB.databases) + return Promise.resolve(); + var intervalId; + return new Promise(function (resolve) { + var tryIdb = function () { return indexedDB.databases().finally(resolve); }; + intervalId = setInterval(tryIdb, 100); + tryIdb(); + }).finally(function () { return clearInterval(intervalId); }); + } + + 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 openCanceller = state.openCanceller; + function throwIfCancelled() { + if (state.openCanceller !== openCanceller) + throw new exceptions.DatabaseClosed('db.open() was cancelled'); + } + var resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null, wasCreated = false; + var tryOpenDB = function () { return new DexiePromise(function (resolve, reject) { + throwIfCancelled(); + if (!indexedDB) + throw new exceptions.MissingAPI(); + 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(); + 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; + wasCreated = oldVer < 1; + db._novip.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(function () { + upgradeTransaction = null; + var idbdb = db._novip.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); + if (!verifyInstalledSchema(db, tmpTrans)) { + console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail."); + } + } + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(function (ev) { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + idbdb.onclose = wrap(function (ev) { + db.on("close").fire(ev); + }); + if (wasCreated) + _onDatabaseCreated(db._deps, dbName); + resolve(); + }, reject); + }).catch(function (err) { + if (err && err.name === 'UnknownError' && state.PR1398_maxLoop > 0) { + state.PR1398_maxLoop--; + console.warn('Dexie: Workaround for Chrome UnknownError on open()'); + return tryOpenDB(); + } + else { + return DexiePromise.reject(err); + } + }); }; + return DexiePromise.race([ + openCanceller, + (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) + ]).then(function () { + throwIfCancelled(); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return db.on.ready.fire(db.vip); })).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return remainders_1(db.vip); })).then(fireRemainders); + } + }); + }).finally(function () { + state.onReadyBeingFired = null; + state.isBeingOpened = false; + }).then(function () { + return db; + }).catch(function (err) { + state.dbOpenError = err; + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (_a) { } + if (openCanceller === state.openCanceller) { + db._close(); + } + return rejection(err); + }).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 { + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return enterTransactionScope(db, mode, storeNames, null, scopeFunc); }); + } + return rejection(ex); + } + } + 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, 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(cursor.key.slice(0, keyLength) + .concat(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); + } + }, + primaryKey: { + get: function () { + return cursor.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 + }; + + 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) { + rv[prfx + prop] = b[prop]; + } + else if (apTypeName === 'Object') { + getObjectDiff(ap, bp, rv, prfx + prop + '.'); + } + else if (ap !== bp) { + 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; + } + + function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); + } + + 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 = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req); + if (req.type !== 'delete') + req.values = __spreadArray([], req.values, true); + if (req.keys) + req.keys = __spreadArray([], req.keys, true); + return getExistingValues(downTable, req, keys).then(function (existingValues) { + var contexts = keys.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) { + if (hasOwn(requestedValue_1, keyPath)) { + requestedValue_1[keyPath] = additionalChanges_1[keyPath]; + } + else { + 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.length; ++i) { + var primKey = results ? results[i] : keys[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; + } })); } + }; + function getExistingValues(table, req, effectiveKeys) { + return req.type === "add" + ? Promise.resolve([]) + : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); + } + + function getFromTransactionCache(keys, cache, clone) { + try { + if (!cache) + return null; + if (cache.keys.length < keys.length) + return null; + var result = []; + for (var i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { + if (cmp(cache.keys[i], keys[j]) !== 0) + continue; + result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); + ++j; + } + return result.length === keys.length ? result : null; + } + catch (_a) { + return null; + } + } + var cacheExistingValuesMiddleware = { + stack: "dbcore", + level: -1, + create: function (core) { + return { + table: function (tableName) { + var table = core.table(tableName); + return __assign(__assign({}, table), { getMany: function (req) { + if (!req.cache) { + return table.getMany(req); + } + var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); + if (cachedResult) { + return DexiePromise.resolve(cachedResult); + } + return table.getMany(req).then(function (res) { + req.trans["_cache"] = { + keys: req.keys, + values: req.cache === "clone" ? deepClone(res) : res, + }; + return res; + }); + }, mutate: function (req) { + if (req.type !== "add") + req.trans["_cache"] = null; + return table.mutate(req); + } }); + }, + }; + }, + }; + + var _a; + function isEmptyRange(node) { + return !("from" in node); + } + var RangeSet = function (fromOrTree, to) { + if (this) { + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + var rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } + }; + props(RangeSet.prototype, (_a = { + add: function (rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey: function (key) { + addRange(this, key, key); + return this; + }, + addKeys: function (keys) { + var _this = this; + keys.forEach(function (key) { return addRange(_this, key, key); }); + return this; + } + }, + _a[iteratorSymbol] = function () { + return getRangeSetIterator(this); + }, + _a)); + function addRange(target, from, to) { + var diff = cmp(from, to); + if (isNaN(diff)) + return; + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from: from, to: to, d: 1 }); + var left = target.l; + var right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; + target.d = right ? right.d + 1 : 1; + } + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; + target.d = target.l ? target.l.d + 1 : 1; + } + var rightWasCutOff = !target.r; + if (left && !target.l) { + mergeRanges(target, left); + } + if (right && rightWasCutOff) { + mergeRanges(target, right); + } + } + function mergeRanges(target, newSet) { + function _addRangeSet(target, _a) { + var from = _a.from, to = _a.to, l = _a.l, r = _a.r; + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); + } + function rangesOverlap(rangeSet1, rangeSet2) { + var i1 = getRangeSetIterator(rangeSet2); + var nextResult1 = i1.next(); + if (nextResult1.done) + return false; + var a = nextResult1.value; + var i2 = getRangeSetIterator(rangeSet1); + var nextResult2 = i2.next(a.from); + var b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) + : (b = (nextResult2 = i2.next(a.from)).value); + } + return false; + } + function getRangeSetIterator(node) { + var state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next: function (key) { + var keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + case 1: + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + if (state.n.r) { + state.s = 3; + state = { up: state, n: state.n.r, s: 0 }; + continue; + } + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; + } + function rebalance(target) { + var _a, _b; + var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + var l = r === "r" ? "l" : "r"; + var rootClone = __assign({}, target); + var oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); + } + function computeDepth(_a) { + var r = _a.r, l = _a.l; + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; + } + + var observabilityMiddleware = { + stack: "dbcore", + level: 0, + create: function (core) { + var dbName = core.schema.name; + var FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); + return __assign(__assign({}, core), { table: function (tableName) { + var table = core.table(tableName); + var schema = table.schema; + var primaryKey = schema.primaryKey; + var extractKey = primaryKey.extractKey, outbound = primaryKey.outbound; + var tableClone = __assign(__assign({}, table), { mutate: function (req) { + var trans = req.trans; + var mutatedParts = trans.mutatedParts || (trans.mutatedParts = {}); + var getRangeSet = function (indexName) { + var part = "idb://" + dbName + "/" + tableName + "/" + indexName; + return (mutatedParts[part] || + (mutatedParts[part] = new RangeSet())); + }; + var pkRangeSet = getRangeSet(""); + var delsRangeSet = getRangeSet(":dels"); + var type = req.type; + var _a = req.type === "deleteRange" + ? [req.range] + : req.type === "delete" + ? [req.keys] + : req.values.length < 50 + ? [[], req.values] + : [], keys = _a[0], newObjs = _a[1]; + var oldCache = req.trans["_cache"]; + return table.mutate(req).then(function (res) { + if (isArray(keys)) { + if (type !== "delete") + keys = res.results; + pkRangeSet.addKeys(keys); + var oldObjs = getFromTransactionCache(keys, oldCache); + if (!oldObjs && type !== "add") { + delsRangeSet.addKeys(keys); + } + if (oldObjs || newObjs) { + trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); + } + } + else if (keys) { + var range = { from: keys.lower, to: keys.upper }; + delsRangeSet.add(range); + pkRangeSet.add(range); + } + else { + pkRangeSet.add(FULL_RANGE); + delsRangeSet.add(FULL_RANGE); + schema.indexes.forEach(function (idx) { return getRangeSet(idx.name).add(FULL_RANGE); }); + } + return res; + }); + } }); + var getRange = function (_a) { + var _b, _c; + var _d = _a.query, index = _d.index, range = _d.range; + return [ + index, + new RangeSet((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY), + ]; + }; + var readSubscribers = { + get: function (req) { return [primaryKey, new RangeSet(req.key)]; }, + getMany: function (req) { return [primaryKey, new RangeSet().addKeys(req.keys)]; }, + count: getRange, + query: getRange, + openCursor: getRange, + }; + keys(readSubscribers).forEach(function (method) { + tableClone[method] = function (req) { + var subscr = PSD.subscr; + if (subscr) { + var getRangeSet = function (indexName) { + var part = "idb://" + dbName + "/" + tableName + "/" + indexName; + return (subscr[part] || + (subscr[part] = new RangeSet())); + }; + var pkRangeSet_1 = getRangeSet(""); + var delsRangeSet_1 = getRangeSet(":dels"); + var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1]; + getRangeSet(queriedIndex.name || "").add(queriedRanges); + if (!queriedIndex.isPrimaryKey) { + if (method === "count") { + delsRangeSet_1.add(FULL_RANGE); + } + else { + var keysPromise_1 = method === "query" && + outbound && + req.values && + table.query(__assign(__assign({}, req), { values: false })); + return table[method].apply(this, arguments).then(function (res) { + if (method === "query") { + if (outbound && req.values) { + return keysPromise_1.then(function (_a) { + var resultingKeys = _a.result; + pkRangeSet_1.addKeys(resultingKeys); + return res; + }); + } + var pKeys = req.values + ? res.result.map(extractKey) + : res.result; + if (req.values) { + pkRangeSet_1.addKeys(pKeys); + } + else { + delsRangeSet_1.addKeys(pKeys); + } + } + else if (method === "openCursor") { + var cursor_1 = res; + var wantValues_1 = req.values; + return (cursor_1 && + Object.create(cursor_1, { + key: { + get: function () { + delsRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.key; + }, + }, + primaryKey: { + get: function () { + var pkey = cursor_1.primaryKey; + delsRangeSet_1.addKey(pkey); + return pkey; + }, + }, + value: { + get: function () { + wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.value; + }, + }, + })); + } + return res; + }); + } + } + } + return table[method].apply(this, arguments); + }; + }); + return tableClone; + } }); + }, + }; + function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { + function addAffectedIndex(ix) { + var rangeSet = getRangeSet(ix.name || ""); + function extractKey(obj) { + return obj != null ? ix.extractKey(obj) : null; + } + var addKeyOrKeys = function (key) { return ix.multiEntry && isArray(key) + ? key.forEach(function (key) { return rangeSet.addKey(key); }) + : rangeSet.addKey(key); }; + (oldObjs || newObjs).forEach(function (_, i) { + var oldKey = oldObjs && extractKey(oldObjs[i]); + var newKey = newObjs && extractKey(newObjs[i]); + if (cmp(oldKey, newKey) !== 0) { + if (oldKey != null) + addKeyOrKeys(oldKey); + if (newKey != null) + addKeyOrKeys(newKey); + } + }); + } + schema.indexes.forEach(addAffectedIndex); + } + + var Dexie$1 = (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; + this._novip = this; + var state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true, + PR1398_maxLoop: 3 + }; + 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", "close", { 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, _this._options.chromeTransactionDurability, 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); + this.use(observabilityMiddleware); + this.use(cacheExistingValuesMiddleware); + this.vip = Object.create(this, { _vip: { value: true } }); + 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.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise(function (resolve, reject) { + if (_this._state.openComplete) { + return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); + } + 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 state = this._state; + var idx = connections.indexOf(this); + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this._novip.idbdb = null; + } + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + }; + Dexie.prototype.close = function () { + this._close(); + var state = this._state; + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + }; + 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 () { + _onDatabaseDeleted(_this._deps, _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: false, + 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 symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol + ? Symbol.observable + : "@@observable"; + var Observable = (function () { + function Observable(subscribe) { + this._subscribe = subscribe; + } + Observable.prototype.subscribe = function (x, error, complete) { + return this._subscribe(!x || typeof x === "function" ? { next: x, error: error, complete: complete } : x); + }; + Observable.prototype[symbolObservable] = function () { + return this; + }; + return Observable; + }()); + + function extendObservabilitySet(target, newSet) { + keys(newSet).forEach(function (part) { + var rangeSet = target[part] || (target[part] = new RangeSet()); + mergeRanges(rangeSet, newSet[part]); + }); + return target; + } + + function liveQuery(querier) { + var hasValue = false; + var currentValue = undefined; + var observable = new Observable(function (observer) { + var scopeFuncIsAsync = isAsyncFunction(querier); + function execute(subscr) { + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var exec = function () { return newScope(querier, { subscr: subscr, trans: null }); }; + var rv = PSD.trans + ? + usePSD(PSD.transless, exec) + : exec(); + if (scopeFuncIsAsync) { + rv.then(decrementExpectedAwaits, decrementExpectedAwaits); + } + return rv; + } + var closed = false; + var accumMuts = {}; + var currentObs = {}; + var subscription = { + get closed() { + return closed; + }, + unsubscribe: function () { + closed = true; + globalEvents.storagemutated.unsubscribe(mutationListener); + }, + }; + observer.start && observer.start(subscription); + var querying = false, startedListening = false; + function shouldNotify() { + return keys(currentObs).some(function (key) { + return accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key]); + }); + } + var mutationListener = function (parts) { + extendObservabilitySet(accumMuts, parts); + if (shouldNotify()) { + doQuery(); + } + }; + var doQuery = function () { + if (querying || closed) + return; + accumMuts = {}; + var subscr = {}; + var ret = execute(subscr); + if (!startedListening) { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); + startedListening = true; + } + querying = true; + Promise.resolve(ret).then(function (result) { + hasValue = true; + currentValue = result; + querying = false; + if (closed) + return; + if (shouldNotify()) { + doQuery(); + } + else { + accumMuts = {}; + currentObs = subscr; + observer.next && observer.next(result); + } + }, function (err) { + querying = false; + hasValue = false; + observer.error && observer.error(err); + subscription.unsubscribe(); + }); + }; + doQuery(); + return subscription; + }); + observable.hasValue = function () { return hasValue; }; + observable.getValue = function () { return currentValue; }; + return observable; + } + + var domDeps; + try { + domDeps = { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; + } + catch (e) { + domDeps = { indexedDB: null, IDBKeyRange: null }; + } + + var Dexie = Dexie$1; + props(Dexie, __assign(__assign({}, fullNameExceptions), { + delete: function (databaseName) { + var db = new Dexie(databaseName, { addons: [] }); + return db.delete(); + }, + exists: function (name) { + return new Dexie(name, { addons: [] }).open().then(function (db) { + db.close(); + return true; + }).catch('NoSuchDatabaseError', function () { return false; }); + }, + getDatabaseNames: function (cb) { + try { + return getDatabaseNames(Dexie.dependencies).then(cb); + } + catch (_a) { + return rejection(new exceptions.MissingAPI()); + } + }, + 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.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, on: globalEvents, liveQuery: liveQuery, extendObservabilitySet: extendObservabilitySet, + getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, cmp: cmp, asap: asap$1, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: domDeps, + 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)); }) })); + Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); + + if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (updatedParts) { + if (!propagatingLocally) { + var event_1; + if (isIEOrEdge) { + event_1 = document.createEvent('CustomEvent'); + event_1.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts); + } + else { + event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { + detail: updatedParts + }); + } + propagatingLocally = true; + dispatchEvent(event_1); + propagatingLocally = false; + } + }); + addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function (_a) { + var detail = _a.detail; + if (!propagatingLocally) { + propagateLocally(detail); + } + }); + } + function propagateLocally(updateParts) { + var wasMe = propagatingLocally; + try { + propagatingLocally = true; + globalEvents.storagemutated.fire(updateParts); + } + finally { + propagatingLocally = wasMe; + } + } + var propagatingLocally = false; + + if (typeof BroadcastChannel !== 'undefined') { + var bc_1 = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); + if (typeof bc_1.unref === 'function') { + bc_1.unref(); + } + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + if (!propagatingLocally) { + bc_1.postMessage(changedParts); + } + }); + bc_1.onmessage = function (ev) { + if (ev.data) + propagateLocally(ev.data); + }; + } + else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + try { + if (!propagatingLocally) { + if (typeof localStorage !== 'undefined') { + localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({ + trig: Math.random(), + changedParts: changedParts, + })); + } + if (typeof self['clients'] === 'object') { + __spreadArray([], self['clients'].matchAll({ includeUncontrolled: true }), true).forEach(function (client) { + return client.postMessage({ + type: STORAGE_MUTATED_DOM_EVENT_NAME, + changedParts: changedParts, + }); + }); + } + } + } + catch (_a) { } + }); + if (typeof addEventListener !== 'undefined') { + addEventListener('storage', function (ev) { + if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) { + var data = JSON.parse(ev.newValue); + if (data) + propagateLocally(data.changedParts); + } + }); + } + var swContainer = self.document && navigator.serviceWorker; + if (swContainer) { + swContainer.addEventListener('message', propagateMessageLocally); + } + } + function propagateMessageLocally(_a) { + var data = _a.data; + if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) { + propagateLocally(data.changedParts); + } + } + + DexiePromise.rejectionMapper = mapError; + setDebug(debug, dexieStackFrameFilter); + + var namedExports = /*#__PURE__*/Object.freeze({ + __proto__: null, + Dexie: Dexie$1, + liveQuery: liveQuery, + 'default': Dexie$1, + RangeSet: RangeSet, + mergeRanges: mergeRanges, + rangesOverlap: rangesOverlap + }); + + __assign(Dexie$1, namedExports, { default: Dexie$1 }); + + return Dexie$1; + +})); +//# sourceMappingURL=dexie.js.map diff --git a/dist/dexie.js.map b/dist/dexie.js.map new file mode 100644 index 000000000..05fb0724d --- /dev/null +++ b/dist/dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.js","sources":["../node_modules/tslib/tslib.es6.js","../src/globals/global.ts","../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/functions/workaround-undefined-primkey.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/functions/cmp.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/event-wrappers.ts","../src/globals/global-events.ts","../src/classes/transaction/transaction.ts","../src/classes/transaction/transaction-constructor.ts","../src/helpers/index-spec.ts","../src/helpers/table-schema.ts","../src/functions/quirks.ts","../src/dbcore/get-key-extractor.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","../node_modules/safari-14-idb-fix/dist/index.js","../src/classes/dexie/dexie-open.ts","../src/helpers/yield-support.ts","../src/classes/dexie/transaction-helpers.ts","../src/dbcore/virtual-index-middleware.ts","../src/functions/get-object-diff.ts","../src/dbcore/get-effective-keys.ts","../src/hooks/hooks-middleware.ts","../src/dbcore/cache-existing-values-middleware.ts","../src/helpers/rangeset.ts","../src/live-query/observability-middleware.ts","../src/classes/dexie/dexie.ts","../src/classes/observable/observable.ts","../src/live-query/extend-observability-set.ts","../src/live-query/live-query.ts","../src/classes/dexie/dexie-dom-dependencies.ts","../src/classes/dexie/dexie-static-props.ts","../src/live-query/propagate-locally.ts","../src/live-query/enable-broadcast.ts","../src/index.ts","../src/index-umd.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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\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 var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, 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\n/** @deprecated */\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\n/** @deprecated */\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 __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\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\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\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 (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, 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, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n","import { _global } from \"../globals/global\";\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\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: T, extension: X): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\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 (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(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: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} {\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 (typeof keyPath === 'string' && 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 == null ? 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 || !hasOwn(obj, currentKeyPath)) 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 \"BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\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]);\nexport const intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, x=>[x,true]);\n\nlet circularRefs: null | WeakMap = null;\nexport function deepClone(any: T): T {\n circularRefs = typeof WeakMap !== 'undefined' && new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone(any: T): T {\n if (!any || typeof any !== 'object') return any;\n let rv = circularRefs && circularRefs.get(any); // Resolve circular references\n if (rv) return rv;\n if (isArray(any)) {\n rv = [];\n circularRefs && circularRefs.set(any, rv);\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(innerDeepClone(any[i]));\n }\n } else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n } else {\n const proto = getProto(any);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs && circularRefs.set(any, rv);\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = innerDeepClone(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\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nexport const getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nexport const asyncIteratorSymbol = typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\")\n : '@asyncIterator';\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 https://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 MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\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 = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = 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 { _global } from '../globals/global';\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend, getProto} 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, getProto(globalP), 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 getProto(nativeP),\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 const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\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() {\n if (!task.awaits) return false;\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 return true;\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, cleanup) {\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 if (cleanup) enqueueNativeMicroTask(decrementExpectedAwaits);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone),\n nativeAwaitCompatibleWrap(onRejected, zone));\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 { errnames, 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.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\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 {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(()=>tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\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: [[]],\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 { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(keyPath: string | ArrayLike) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === \"string\" && !/\\./.test(keyPath) \n ? (obj: object) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\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';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\n\n/** class Table\n * \n * https://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 * https://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 * https://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 if (\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {\n for (let i=0; i a.keyPath.length - b.keyPath.length)[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 const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));\n }\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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * https://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 * https://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * https://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\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 // object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly.\n try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }\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 * https://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * https://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 * https://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 * https://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 * https://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 {auto, keyPath} = this.schema.primKey;\n if (keyPath && 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 let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, 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`, failures);\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * https://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 {auto, keyPath} = this.schema.primKey;\n if (keyPath && 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 let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, 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`, failures);\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * https://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","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(\n a: Uint8Array,\n b: Uint8Array\n) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\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';\nimport { cmp } from \"../../functions/cmp\";\n\n/** class Collection\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * https://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 * https://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 = this.db._options.modifyChunkSize || 200;\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({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\" // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n }).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(()=>(putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>(deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\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 * https://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(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => ctx.value = null;\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 * https://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 * https://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 * https://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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();\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 { 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 Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME) as GlobalDexieEvents;\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';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n * \n * https://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: ChromeTransactionDurability;\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 ||\n (this.db.core \n ? this.db.core.transaction(this.storeNames, this.mode as 'readwrite' | 'readonly', { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n ) as IDBTransaction;\n\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 if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\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(): https://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 * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n * \n * https://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 chromeTransactionDurability: ChromeTransactionDurability,\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 chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\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 { 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 let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\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 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';\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 IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\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}) {\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 let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n \n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\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 reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()\n else\n reqs.push(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 reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\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 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, 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({_novip: 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 { _global } from \"../../globals/global\";\nimport { setProp, keys, slice, isArray, shallowClone, isAsyncFunction, defineProperty, getPropertyDescriptor } 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({_novip: db}: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\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({_novip: 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 {_novip: 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 trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\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 (\n (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n ''+(oldDef.primKey.keyPath||'')\n ) !== (\n ''+(newDef.primKey.keyPath||'')\n ) ||\n // Compare the autoIncrement flag also\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) // IE has bug reading autoIncrement prop.\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 [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\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({_novip: 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 verifyInstalledSchema(db: Dexie, tmpTrans: IDBTransaction): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\n\nexport function adjustToExistingIndexNames({_novip: 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';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\n\n/** class Version\n *\n * https://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 | null; }): 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 = promisableChain(this._cfg.contentUpgrade || nop, 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 { Dexie } from \"../classes/dexie/dexie\";\nimport { Table } from \"../public/types/table\";\nimport { DBNAMES_DB } from \"../globals/constants\";\nimport { DexieDOMDependencies } from \"../public/types/dexie-dom-dependencies\";\nimport { nop } from \"../functions/chaining-functions\";\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\") as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n 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 : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({name}).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\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","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\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, verifyInstalledSchema } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } 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';\nimport safari14Workaround from 'safari-14-idb-fix';\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 const openCanceller = state.openCanceller;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller) throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\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 wasCreated = false;\n\n const tryOpenDB = () => 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 throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\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(); // 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 wasCreated = oldVer < 1;\n db._novip.idbdb = req.result;// db._novip is because db can be an Object.create(origDb).\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._novip.idbdb = req.result; // db._novip is because db can be an Object.create(origDb).\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 {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\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 idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n\n }, reject);\n }).catch(err => {\n if (err && err.name === 'UnknownError' && state.PR1398_maxLoop > 0) {\n // Bug in Chrome after clearing site data\n // https://github.com/dexie/Dexie.js/issues/543#issuecomment-1795736695\n state.PR1398_maxLoop--;\n console.warn('Dexie: Workaround for Chrome UnknownError on open()');\n return tryOpenDB();\n } else {\n return Promise.reject(err);\n }\n });\n \n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([\n openCanceller,\n (typeof navigator === 'undefined' ? Promise.resolve() : safari14Workaround()).then(tryOpenDB)\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 throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>db.on.ready.fire(db.vip))).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(db.vip))).then(fireRemainders)\n }\n });\n }).finally(()=>{\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n return db;\n }).catch(err => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\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 { }\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection (err);\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 { errnames, 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 try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(\n db,\n mode,\n storeNames,\n null,\n scopeFunc\n ));\n }\n return rejection(ex);\n }\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 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(\n cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)\n ) :\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 primaryKey: {\n get() {\n return cursor.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 { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\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 // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) 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","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","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 { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from \"../functions/get-object-diff\";\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } 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} :\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 if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] = additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\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\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n","import { deepClone } from \"../functions/utils\";\nimport { DBCore } from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport Promise from \"../helpers/promise\";\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans[\"_cache\"],\n req.cache === \"clone\"\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== \"add\") req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { cmp } from \"../functions/cmp\";\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from \"../public/types/rangeset\";\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n * \n */\n\nfunction isEmptyRange(node: IntervalTree | {from: IndexableType, to: IndexableType}): node is EmptyRange {\n return !(\"from\" in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function(fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(this, arguments.length ? {d:1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree} : {d:0});\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n\n [iteratorSymbol](): Iterator {\n return getRangeSetIterator(this);\n }\n});\n\nfunction addRange(target: IntervalTree, from: IndexableType, to: IndexableType) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n \n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(target: IntervalTree, newSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n function _addRangeSet(\n target: IntervalTree,\n { from, to, l, r }: IntervalTreeNode | {from: IndexableType, to: IndexableType, l?: undefined, r?: undefined}\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if(!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator {\n let state: RangeSetIteratorState = isEmptyRange(node) ? null : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n // \n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n // \n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L] \n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === \"r\" ? \"l\" : \"r\"; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r]; \n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import { getFromTransactionCache } from \"../dbcore/cache-existing-values-middleware\";\nimport { cmp } from \"../functions/cmp\";\nimport { isArray, keys } from \"../functions/utils\";\nimport { PSD } from \"../helpers/promise\";\nimport { RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\n\nexport const observabilityMiddleware: Middleware = {\n stack: \"dbcore\",\n level: 0,\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts =\n trans.mutatedParts || (trans.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === \"deleteRange\"\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === \"delete\"\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [[], req.values] // keys = empty array - will be resolved in mutate().then(...).\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n const oldCache = req.trans[\"_cache\"];\n return table.mutate(req).then((res) => {\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n if (type !== \"delete\") keys = res.results;\n // individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs = getFromTransactionCache(keys, oldCache);\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs && type !== \"add\") {\n // delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(range.lower ?? core.MIN_KEY, range.upper ?? core.MAX_KEY),\n ];\n\n const readSubscribers: {[method in\n Exclude]: \n (req: any) => [DBCoreIndex, RangeSet]\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n }\n\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD;\n if (subscr) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (subscr[part] ||\n (subscr[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === \"count\") {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === \"query\" &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({ result: resultingKeys }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === \"openCursor\") {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest).values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: any[] | undefined,\n newObjs: any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) => ix.multiEntry && isArray(key)\n // multiEntry and the old property was an array - add each array entry to the rangeSet:\n ? key.forEach(key => rangeSet.addKey(key))\n // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n : rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\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 { _onDatabaseDeleted } 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';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\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 PR1398_maxLoop?: number;\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 _vip?: boolean;\n _novip?: Dexie;// db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\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 this._novip = this;\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 PR1398_maxLoop: 3\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\", \"close\", { 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, this._options.chromeTransactionDurability, 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 this.use(observabilityMiddleware);\n this.use(cacheExistingValuesMiddleware);\n\n this.vip = Object.create(this, {_vip: {value: true}}) as Dexie;\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.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\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 state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this._novip.idbdb = null; // db._novip is because db can be an Object.create(origDb).\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 close(): void {\n this._close();\n const state = this._state;\n this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\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 _onDatabaseDeleted(this._deps, 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 {\n Observable as IObservable,\n Observer,\n Subscription,\n} from \"../../public/types/observable\";\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\" as any;\n\nexport class Observable implements IObservable {\n private _subscribe: (observer: Observer) => Subscription;\n hasValue?: ()=>boolean;\n getValue?: ()=>T;\n\n constructor(subscribe: (observer: Observer) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === \"function\" ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { deepClone, keys } from \"../functions/utils\";\nimport { mergeRanges, RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach(part => {\n const rangeSet = target[part] || (target[part] = new RangeSet());\n mergeRanges(rangeSet, newSet[part]);\n });\n return target;\n}\n","import { isAsyncFunction, keys } from \"../functions/utils\";\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME } from \"../globals/global-events\";\nimport {\n decrementExpectedAwaits,\n incrementExpectedAwaits,\n newScope,\n PSD,\n usePSD,\n} from \"../helpers/promise\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n Observable as IObservable,\n Subscription,\n} from \"../public/types/observable\";\nimport { Observable } from \"../classes/observable/observable\";\nimport { extendObservabilitySet } from \"./extend-observability-set\";\nimport { rangesOverlap } from \"../helpers/rangeset\";\n\nexport function liveQuery(querier: () => T | Promise): IObservable {\n let hasValue = false;\n let currentValue: T = undefined as any;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(subscr: ObservabilitySet) {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const exec = () => newScope(querier, { subscr, trans: null });\n const rv = PSD.trans\n ? // Ignore current transaction if active when calling subscribe().\n usePSD(PSD.transless, exec)\n : exec();\n if (scopeFuncIsAsync) {\n (rv as Promise).then(\n decrementExpectedAwaits,\n decrementExpectedAwaits\n );\n }\n return rv;\n }\n\n let closed = false;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n closed = true;\n globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let querying = false,\n startedListening = false;\n\n function shouldNotify() {\n return keys(currentObs).some(\n (key) =>\n accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key])\n );\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const doQuery = () => {\n if (querying || closed) return;\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n const ret = execute(subscr);\n if (!startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n }\n querying = true;\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n querying = false;\n if (closed) return;\n if (shouldNotify()) {\n // Mutations has happened while we were querying. Redo query.\n doQuery();\n } else {\n accumMuts = {};\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n observer.next && observer.next(result);\n }\n },\n (err) => {\n querying = false;\n hasValue = false;\n observer.error && observer.error(err);\n subscription.unsubscribe();\n }\n );\n };\n\n doQuery();\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies\n\ntry {\n domDeps = {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, asap } from '../../functions/utils';\nimport { getObjectDiff } from \"../../functions/get-object-diff\";\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } 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';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\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, {addons: []});\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 try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\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 on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\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: domDeps,\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, // Commented because solved in index-umd.ts instead.\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 // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { isIEOrEdge } from '../globals/constants';\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME, STORAGE_MUTATED_DOM_EVENT_NAME } from '../globals/global-events';\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event: CustomEvent;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n } else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({detail}: CustomEvent) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\n\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n globalEvents.storagemutated.fire(updateParts);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n } \n \n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n bc.onmessage = (ev) => {\n if (ev.data) propagateLocally(ev.data);\n };\n} else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n // DOM verified - when typeof self !== \"undefined\", we are a window or worker. Not a Node process.\n\n //\n // Propagate local changes to remote tabs/windows via storage event and service worker\n // via messages. We have this code here because of https://bugs.webkit.org/show_bug.cgi?id=161472.\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n // We're a browsing window or tab. Propagate to other windows/tabs via storage event:\n localStorage.setItem(\n STORAGE_MUTATED_DOM_EVENT_NAME,\n JSON.stringify({\n trig: Math.random(),\n changedParts,\n })\n );\n }\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n })\n );\n }\n }\n } catch {}\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev: StorageEvent) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data) propagateLocally(data.changedParts);\n }\n });\n }\n\n //\n // Propagate messages from service worker\n //\n const swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\n if (swContainer) {\n // We're a browser window and want to propagate message from the SW:\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\n\nfunction propagateMessageLocally({ data }: MessageEvent) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\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';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport { liveQuery } from './live-query/live-query';\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 { RangeSet, mergeRanges, rangesOverlap } from \"./helpers/rangeset\";\nexport { Dexie, liveQuery }; // Comply with public/index.d.ts.\nexport default Dexie;\n","// Issue #1127. Need another index.ts for the UMD module with only a default export\n// like it was before.\n// In practice though, the UMD export will also export the named export in \n// https://github.com/dfahlander/Dexie.js/blob/c9187ae60c0d7a424f85bab3af179fbbc9901c8e/src/classes/dexie/dexie-static-props.ts#L223-L228\nimport Dexie from \"./index\";\nimport * as namedExports from \"./index\";\nimport { __assign } from 'tslib';\n__assign(Dexie, namedExports, {default: Dexie});\nexport default Dexie;\n"],"names":["asap","_a","Promise","Dexie","Debug.debug","Debug.getErrorWithStack","safari14Workaround","_Dexie","Debug.setDebug"],"mappings":";;;;;;;;;;;;;;;;;;;IAAA;IACA;IAEA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAkBO,IAAI,QAAQ,GAAG,WAAW;IACjC,IAAI,QAAQ,GAAG,MAAM,CAAC,MAAM,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE;IACrD,QAAQ,KAAK,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;IAC7D,YAAY,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;IAC7B,YAAY,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;IACzF,SAAS;IACT,QAAQ,OAAO,CAAC,CAAC;IACjB,MAAK;IACL,IAAI,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IAC3C,EAAC;IA4HM,SAAS,aAAa,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;IAC9C,IAAI,IAAI,IAAI,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,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C,QAAE,OAAO,CAClE,UAAC,MAAM;4BACL,OAAA,MAAM,CAAC,WAAW,CAAC;gCACjB,IAAI,EAAE,8BAA8B;gCACpC,YAAY,cAAA;6BACb,CAAC;yBAAA,CACL,CAAC;qBACH;iBACF;aACF;YAAC,WAAM,GAAE;SACX,CAAC,CAAC;QAKH,IAAI,OAAO,gBAAgB,KAAK,WAAW,EAAE;YACzC,gBAAgB,CAAC,SAAS,EAAE,UAAC,EAAgB;gBAC7C,IAAI,EAAE,CAAC,GAAG,KAAK,8BAA8B,EAAE;oBAC7C,IAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;oBACrC,IAAI,IAAI;wBAAE,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;iBAC/C;aACF,CAAC,CAAC;SACJ;QAKD,IAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,IAAI,SAAS,CAAC,aAAa,CAAC;QAC7D,IAAI,WAAW,EAAE;YAEf,WAAW,CAAC,gBAAgB,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;SAClE;KACF;IAED,SAAS,uBAAuB,CAAC,EAAsB;YAApB,IAAI,UAAA;QACrC,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,8BAA8B,EAAE;YACxD,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;SACrC;IACH;;IChFA,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCQ,YAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC;;;;;;;;;;;;ICblD,QAAQ,CAACD,OAAK,EAAE,YAAY,EAAE,EAAC,OAAO,EAAEA,OAAK,EAAC,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..14ff0c4e9 --- /dev/null +++ b/dist/dexie.min.js @@ -0,0 +1,2 @@ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Dexie=t()})(this,function(){"use strict";var g=function(){return(g=Object.assign||function(e){for(var t,n=1,r=arguments.length;n.",pt="String expected.",yt=[],vt="undefined"!=typeof navigator&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),mt=vt,gt=vt,bt="__dbnames",_t="readonly",wt="readwrite";function xt(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}var kt={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Et(t){return"string"!=typeof t||/\./.test(t)?function(e){return e}:function(e){return void 0===e[t]&&t in e&&delete(e=A(e))[t],e}}var Pt=(Kt.prototype._trans=function(e,r,t){var n=this._tx||Oe.trans,i=this.name;function o(e,t,n){if(!n.schema[i])throw new J.NotFound("Table "+i+" not part of transaction");return r(n.idbtrans,n)}var a=qe();try{return n&&n.db===this.db?n===Oe.trans?n._promise(e,o,t):Je(function(){return n._promise(e,o,t)},{trans:n,transless:Oe.transless||Oe}):function t(n,r,i,o){if(n.idbdb&&(n._state.openComplete||Oe.letThrough||n._vip)){var a=n._createTransaction(r,i,n._dbSchema);try{a.create(),n._state.PR1398_maxLoop=3}catch(e){return e.name===Q.InvalidState&&n.isOpen()&&0<--n._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),n._close(),n.open().then(function(){return t(n,r,i,o)})):lt(e)}return a._promise(r,function(e,t){return Je(function(){return Oe.trans=a,o(e,t,a)})}).then(function(e){return a._completion.then(function(){return e})})}if(n._state.openComplete)return lt(new J.DatabaseClosed(n._state.dbOpenError));if(!n._state.isBeingOpened){if(!n._options.autoOpen)return lt(new J.DatabaseClosed);n.open().catch(Z)}return n._state.dbReadyPromise.then(function(){return t(n,r,i,o)})}(this.db,e,[this.name],o)}finally{a&&Ue()}},Kt.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)},Kt.prototype.where=function(o){if("string"==typeof o)return new this.db.WhereClause(this,o);if(b(o))return new this.db.WhereClause(this,"["+o.join("+")+"]");var n=x(o);if(1===n.length)return this.where(n[0]).equals(o[n[0]]);var e=this.schema.indexes.concat(this.schema.primKey).filter(function(t){if(t.compound&&n.every(function(e){return 0<=t.keyPath.indexOf(e)})){for(var e=0;ec+l&&h(c+b)})})}return h(0).then(function(){if(0=s}).forEach(function(u){t.push(function(){var t=h,e=u._cfg.dbschema;En(f,t,l),En(f,e,l),h=f._dbSchema=e;var n=_n(t,e);n.add.forEach(function(e){wn(l,e[0],e[1].primKey,e[1].indexes)}),n.change.forEach(function(e){if(e.recreate)throw new J.Upgrade("Not yet support for changing primary key");var t=l.objectStore(e.name);e.add.forEach(function(e){return xn(t,e)}),e.change.forEach(function(e){t.deleteIndex(e.name),xn(t,e)}),e.del.forEach(function(e){return t.deleteIndex(e)})});var r=u._cfg.contentUpgrade;if(r&&u._cfg.version>s){yn(f,l),c._memoizedTables={},d=!0;var i=P(e);n.del.forEach(function(e){i[e]=t[e]}),mn(f,[f.Transaction.prototype]),vn(f,[f.Transaction.prototype],x(i),i),c.schema=i;var o,a=R(r);a&&$e();n=je.follow(function(){var e;(o=r(c))&&a&&(e=Ze.bind(null,null),o.then(e,e))});return o&&"function"==typeof o.then?je.resolve(o):n.then(function(){return o})}}),t.push(function(e){var t,n,r;d&&mt||(t=u._cfg.dbschema,n=t,r=e,[].slice.call(r.db.objectStoreNames).forEach(function(e){return null==n[e]&&r.db.deleteObjectStore(e)})),mn(f,[f.Transaction.prototype]),vn(f,[f.Transaction.prototype],f._storeNames,f._dbSchema),c.schema=f._dbSchema})}),function e(){return t.length?je.resolve(t.shift()(c.idbtrans)).then(e):je.resolve()}().then(function(){var t,n;n=l,x(t=h).forEach(function(e){n.db.objectStoreNames.contains(e)||wn(n,e,t[e].primKey,t[e].indexes)})}).catch(u))})}function _n(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 a={name:n,def:o,recreate:!1,del:[],add:[],change:[]};if(""+(i.primKey.keyPath||"")!=""+(o.primKey.keyPath||"")||i.primKey.auto!==o.primKey.auto&&!vt)a.recreate=!0,r.change.push(a);else{var u=i.idxByName,s=o.idxByName,c=void 0;for(c in u)s[c]||a.del.push(c);for(c in s){var l=u[c],f=s[c];l?l.src!==f.src&&a.change.push(f):a.add.push(f)}(0Math.pow(2,62)?0:e.oldVersion,p=e<1,f._novip.idbdb=l.result,bn(f,e/10,d,n))},n),l.onsuccess=We(function(){d=null;var e,t,n,r,i,o=f._novip.idbdb=l.result,a=y(o.objectStoreNames);if(0= 0) { + rv = any; + } + else { + var proto = getProto(any); + rv = proto === Object.prototype ? {} : Object.create(proto); + circularRefs && circularRefs.set(any, rv); + for (var prop in any) { + if (hasOwn(any, prop)) { + rv[prop] = innerDeepClone(any[prop]); + } + } + } + return rv; +} +var toString = {}.toString; +function toStringTag(o) { + return toString.call(o).slice(8, -1); +} +var iteratorSymbol = typeof Symbol !== 'undefined' ? + Symbol.iterator : + '@@iterator'; +var getIteratorOf = typeof iteratorSymbol === "symbol" ? 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 { + getErrorWithStack.arguments; + 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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" +}; +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 = Object.keys(failures).map(function (pos) { return failures[pos]; }); + this.failuresByPos = 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, +MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], 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 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; +var isOutsideMicroTick = true, +needsNewPhysicalTick = true, +unhandledErrors = [], +rejectingErrors = [], +currentFulfiller = null, 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); + var cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), 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; } + }, + totalEchoes: { get: function () { return totalEchoes; } }, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap; }, + set: function (value) { asap = 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(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(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(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, 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) + extend(psd, props); + ++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() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; + return true; +} +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, cleanup) { + 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); + if (cleanup) + enqueueNativeMicroTask(decrementExpectedAwaits); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; +} +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.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { + if (db._state.openComplete) { + return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); + } + 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(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + 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.2.6'; +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 +}; + +function workaroundForUndefinedPrimKey(keyPath) { + return typeof keyPath === "string" && !/\./.test(keyPath) + ? function (obj) { + if (obj[keyPath] === undefined && (keyPath in obj)) { + obj = deepClone(obj); + delete obj[keyPath]; + } + return obj; + } + : function (obj) { return obj; }; +} + +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) { + if (ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; })) { + for (var i = 0; i < keyPaths.length; ++i) { + if (keyPaths.indexOf(ix.keyPath[i]) === -1) + return false; + } + return true; + } + return false; + }).sort(function (a, b) { return a.keyPath.length - b.keyPath.length; })[0]; + if (compoundIndex && this.db._maxKey !== maxString) { + var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); + return this + .where(keyPathsInValidOrder) + .equals(keyPathsInValidOrder.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; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); + }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + }; + Table.prototype.update = function (keyOrObject, modifications) { + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === undefined) + return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); + try { + if (typeof modifications !== "function") { + keys(modifications).forEach(function (keyPath) { + setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); + }); + } + else { + modifications(keyOrObject, { value: keyOrObject, primKey: key }); + } + } + catch (_a) { + } + 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; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, 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) { + var _this = this; + return this._trans('readonly', function (trans) { + return _this.core.getMany({ + keys: keys, + 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 = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToAdd = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'add', keys: keys, values: objectsToAdd, 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", failures); + }); + }); + }; + Table.prototype.bulkPut = function (objects, keysOrOptions, options) { + var _this = this; + var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToPut = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'put', keys: keys, values: objectsToPut, 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", failures); + }); + }); + }; + Table.prototype.bulkDelete = function (keys) { + var _this = this; + var numKeys = keys.length; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'delete', keys: keys }); + }).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$1(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(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(); + }); + } + }); +} + +function cmp(a, b) { + try { + var ta = type(a); + var tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; +} +function compareArrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + var res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function compareUint8Arrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function type(x) { + var t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + var tsTag = toStringTag(x); + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; +} +function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); +} + +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) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props) + extend(ctx, props); + 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 = _this.db._options.modifyChunkSize || 200; + 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) { + var nextChunk = function (offset) { + var count = Math.min(limit, keys.length - offset); + return coreTable.getMany({ + trans: trans, + keys: keys.slice(offset, offset + count), + cache: "immutable" + }).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[offset + i] + }; + if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { + if (ctx_1.value == null) { + deleteKeys.push(keys[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { + deleteKeys.push(keys[offset + i]); + addValues.push(ctx_1.value); + } + else { + putValues.push(ctx_1.value); + if (outbound) + putKeys.push(keys[offset + i]); + } + } + } + var criteria = isPlainKeyRange(ctx) && + ctx.limit === Infinity && + (typeof changes !== 'function' || changes === deleteCallback) && { + index: ctx.index, + range: ctx.range + }; + 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 () { return (putValues.length > 0 || (criteria && typeof changes === 'object')) && + coreTable.mutate({ + trans: trans, + type: 'put', + keys: putKeys, + values: putValues, + criteria: criteria, + changeSpec: typeof changes !== 'function' + && changes + }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && + coreTable.mutate({ + trans: trans, + type: 'delete', + keys: deleteKeys, + criteria: criteria + }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { + return keys.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.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; _a.lastResult; _a.results; var 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(deleteCallback); + }; + return Collection; +}()); +var deleteCallback = function (value, ctx) { return ctx.value = null; }; + +function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection(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: false, + 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) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + 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(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(); + 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 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 DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; +var STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; +var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); + +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 || + (this.db.core + ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) + : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); + 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(); + if ('mutatedParts' in idbtrans) { + globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); + } + }); + 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 () { + if (this.active) { + this.active = false; + if (this.idbtrans) + this.idbtrans.abort(); + this._reject(new exceptions.Abort()); + } + }; + 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(mode, storeNames, dbschema, chromeTransactionDurability, parent) { + var _this = this; + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.chromeTransactionDurability = chromeTransactionDurability; + 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 safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} +var getMaxKey = function (IdbKeyRange) { + try { + IdbKeyRange.only([[]]); + getMaxKey = function () { return [[]]; }; + return [[]]; + } + catch (e) { + getMaxKey = function () { return maxString; }; + return maxString; + } +}; + +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 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, IdbKeyRange, tmpTrans) { + 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 = _a.keys, values = _a.values, range = _a.range; + 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 || values || { length: 1 }).length; + if (keys && values && keys.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 req; + var reqs = []; + var failures = []; + var numFailures = 0; + var errorHandler = function (event) { + ++numFailures; + preventDefault(event); + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures: numFailures, failures: failures, results: [], lastResult: undefined }); + if (range.type === 3 ) + reqs.push(req = store.clear()); + else + reqs.push(req = store.delete(makeIDBKeyRange(range))); + } + else { + var _a = isAddOrPut ? + outbound ? + [values, keys] : + [values, null] : + [keys, null], args1 = _a[0], args2 = _a[1]; + if (isAddOrPut) { + for (var i = 0; i < length; ++i) { + reqs.push(req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i]))); + req.onerror = errorHandler; + } + } + else { + for (var i = 0; i < length; ++i) { + reqs.push(req = store[type](args1[i])); + req.onerror = errorHandler; + } + } + } + var done = function (event) { + var lastResult = event.target.result; + reqs.forEach(function (req, i) { return req.error != null && (failures[i] = req.error); }); + resolve({ + numFailures: numFailures, + failures: failures, + results: type === "delete" ? keys : reqs.map(function (req) { return req.result; }), + 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 = _a.keys; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var length = keys.length; + var result = new Array(length); + var keyCount = 0; + var callbackCount = 0; + var req; + var successHandler = function (event) { + var req = event.target; + if ((result[req._pos] = req.result) != null) + ; + if (++callbackCount === keyCount) + resolve(result); + }; + var errorHandler = eventRejectHandler(reject); + for (var i = 0; i < length; ++i) { + var key = keys[i]; + if (key != null) { + req = store.get(keys[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]; + }, + 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; _a.indexedDB; + var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore: dbcore + }; +} +function generateMiddlewareStacks(_a, tmpTrans) { + var db = _a._novip; + 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(_a, objs, tableNames, dbschema) { + var db = _a._novip; + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + var propDesc = getPropertyDescriptor(obj, tableName); + if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { + 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(_a, objs) { + var db = _a._novip; + 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(_a, oldVersion, trans, idbUpgradeTrans) { + var db = _a._novip; + 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); + trans._memoizedTables = {}; + 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.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || + (oldDef.primKey.auto !== newDef.primKey.auto && !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) { + [].slice.call(idbtrans.db.objectStoreNames).forEach(function (storeName) { + return 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(_a, idbdb, tmpTrans) { + var db = _a._novip; + 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 verifyInstalledSchema(db, tmpTrans) { + var installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); + var diff = getSchemaDiff(installedSchema, db._dbSchema); + return !(diff.add.length || diff.change.some(function (ch) { return ch.add.length || ch.change.length; })); +} +function adjustToExistingIndexNames(_a, schema, idbtrans) { + var db = _a._novip; + 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 = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); + return this; + }; + return Version; +}()); + +function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); +} + +function getDbNamesTable(indexedDB, IDBKeyRange) { + var dbNamesDB = indexedDB["_dbNamesDB"]; + if (!dbNamesDB) { + dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { + addons: [], + indexedDB: indexedDB, + IDBKeyRange: IDBKeyRange, + }); + dbNamesDB.version(1).stores({ dbnames: "name" }); + } + return dbNamesDB.table("dbnames"); +} +function hasDatabasesNative(indexedDB) { + return indexedDB && typeof indexedDB.databases === "function"; +} +function getDatabaseNames(_a) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + return hasDatabasesNative(indexedDB) + ? Promise.resolve(indexedDB.databases()).then(function (infos) { + return infos + .map(function (info) { return info.name; }) + .filter(function (name) { return name !== DBNAMES_DB; }); + }) + : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); +} +function _onDatabaseCreated(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).put({ name: name }).catch(nop); +} +function _onDatabaseDeleted(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); +} + +function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); +} + +function idbReady() { + var isSafari = !navigator.userAgentData && + /Safari\//.test(navigator.userAgent) && + !/Chrom(e|ium)\//.test(navigator.userAgent); + if (!isSafari || !indexedDB.databases) + return Promise.resolve(); + var intervalId; + return new Promise(function (resolve) { + var tryIdb = function () { return indexedDB.databases().finally(resolve); }; + intervalId = setInterval(tryIdb, 100); + tryIdb(); + }).finally(function () { return clearInterval(intervalId); }); +} + +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 openCanceller = state.openCanceller; + function throwIfCancelled() { + if (state.openCanceller !== openCanceller) + throw new exceptions.DatabaseClosed('db.open() was cancelled'); + } + var resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null, wasCreated = false; + var tryOpenDB = function () { return new DexiePromise(function (resolve, reject) { + throwIfCancelled(); + if (!indexedDB) + throw new exceptions.MissingAPI(); + 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(); + 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; + wasCreated = oldVer < 1; + db._novip.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(function () { + upgradeTransaction = null; + var idbdb = db._novip.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); + if (!verifyInstalledSchema(db, tmpTrans)) { + console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail."); + } + } + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(function (ev) { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + idbdb.onclose = wrap(function (ev) { + db.on("close").fire(ev); + }); + if (wasCreated) + _onDatabaseCreated(db._deps, dbName); + resolve(); + }, reject); + }).catch(function (err) { + if (err && err.name === 'UnknownError' && state.PR1398_maxLoop > 0) { + state.PR1398_maxLoop--; + console.warn('Dexie: Workaround for Chrome UnknownError on open()'); + return tryOpenDB(); + } + else { + return DexiePromise.reject(err); + } + }); }; + return DexiePromise.race([ + openCanceller, + (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) + ]).then(function () { + throwIfCancelled(); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return db.on.ready.fire(db.vip); })).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return remainders_1(db.vip); })).then(fireRemainders); + } + }); + }).finally(function () { + state.onReadyBeingFired = null; + state.isBeingOpened = false; + }).then(function () { + return db; + }).catch(function (err) { + state.dbOpenError = err; + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (_a) { } + if (openCanceller === state.openCanceller) { + db._close(); + } + return rejection(err); + }).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 { + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return enterTransactionScope(db, mode, storeNames, null, scopeFunc); }); + } + return rejection(ex); + } + } + 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, 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(cursor.key.slice(0, keyLength) + .concat(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); + } + }, + primaryKey: { + get: function () { + return cursor.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 +}; + +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) { + rv[prfx + prop] = b[prop]; + } + else if (apTypeName === 'Object') { + getObjectDiff(ap, bp, rv, prfx + prop + '.'); + } + else if (ap !== bp) { + 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; +} + +function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); +} + +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 = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req); + if (req.type !== 'delete') + req.values = __spreadArray([], req.values, true); + if (req.keys) + req.keys = __spreadArray([], req.keys, true); + return getExistingValues(downTable, req, keys).then(function (existingValues) { + var contexts = keys.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) { + if (hasOwn(requestedValue_1, keyPath)) { + requestedValue_1[keyPath] = additionalChanges_1[keyPath]; + } + else { + 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.length; ++i) { + var primKey = results ? results[i] : keys[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; + } })); } +}; +function getExistingValues(table, req, effectiveKeys) { + return req.type === "add" + ? Promise.resolve([]) + : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); +} + +function getFromTransactionCache(keys, cache, clone) { + try { + if (!cache) + return null; + if (cache.keys.length < keys.length) + return null; + var result = []; + for (var i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { + if (cmp(cache.keys[i], keys[j]) !== 0) + continue; + result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); + ++j; + } + return result.length === keys.length ? result : null; + } + catch (_a) { + return null; + } +} +var cacheExistingValuesMiddleware = { + stack: "dbcore", + level: -1, + create: function (core) { + return { + table: function (tableName) { + var table = core.table(tableName); + return __assign(__assign({}, table), { getMany: function (req) { + if (!req.cache) { + return table.getMany(req); + } + var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); + if (cachedResult) { + return DexiePromise.resolve(cachedResult); + } + return table.getMany(req).then(function (res) { + req.trans["_cache"] = { + keys: req.keys, + values: req.cache === "clone" ? deepClone(res) : res, + }; + return res; + }); + }, mutate: function (req) { + if (req.type !== "add") + req.trans["_cache"] = null; + return table.mutate(req); + } }); + }, + }; + }, +}; + +var _a; +function isEmptyRange(node) { + return !("from" in node); +} +var RangeSet = function (fromOrTree, to) { + if (this) { + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + var rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } +}; +props(RangeSet.prototype, (_a = { + add: function (rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey: function (key) { + addRange(this, key, key); + return this; + }, + addKeys: function (keys) { + var _this = this; + keys.forEach(function (key) { return addRange(_this, key, key); }); + return this; + } + }, + _a[iteratorSymbol] = function () { + return getRangeSetIterator(this); + }, + _a)); +function addRange(target, from, to) { + var diff = cmp(from, to); + if (isNaN(diff)) + return; + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from: from, to: to, d: 1 }); + var left = target.l; + var right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; + target.d = right ? right.d + 1 : 1; + } + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; + target.d = target.l ? target.l.d + 1 : 1; + } + var rightWasCutOff = !target.r; + if (left && !target.l) { + mergeRanges(target, left); + } + if (right && rightWasCutOff) { + mergeRanges(target, right); + } +} +function mergeRanges(target, newSet) { + function _addRangeSet(target, _a) { + var from = _a.from, to = _a.to, l = _a.l, r = _a.r; + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); +} +function rangesOverlap(rangeSet1, rangeSet2) { + var i1 = getRangeSetIterator(rangeSet2); + var nextResult1 = i1.next(); + if (nextResult1.done) + return false; + var a = nextResult1.value; + var i2 = getRangeSetIterator(rangeSet1); + var nextResult2 = i2.next(a.from); + var b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) + : (b = (nextResult2 = i2.next(a.from)).value); + } + return false; +} +function getRangeSetIterator(node) { + var state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next: function (key) { + var keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + case 1: + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + if (state.n.r) { + state.s = 3; + state = { up: state, n: state.n.r, s: 0 }; + continue; + } + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; +} +function rebalance(target) { + var _a, _b; + var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + var l = r === "r" ? "l" : "r"; + var rootClone = __assign({}, target); + var oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); +} +function computeDepth(_a) { + var r = _a.r, l = _a.l; + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; +} + +var observabilityMiddleware = { + stack: "dbcore", + level: 0, + create: function (core) { + var dbName = core.schema.name; + var FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); + return __assign(__assign({}, core), { table: function (tableName) { + var table = core.table(tableName); + var schema = table.schema; + var primaryKey = schema.primaryKey; + var extractKey = primaryKey.extractKey, outbound = primaryKey.outbound; + var tableClone = __assign(__assign({}, table), { mutate: function (req) { + var trans = req.trans; + var mutatedParts = trans.mutatedParts || (trans.mutatedParts = {}); + var getRangeSet = function (indexName) { + var part = "idb://" + dbName + "/" + tableName + "/" + indexName; + return (mutatedParts[part] || + (mutatedParts[part] = new RangeSet())); + }; + var pkRangeSet = getRangeSet(""); + var delsRangeSet = getRangeSet(":dels"); + var type = req.type; + var _a = req.type === "deleteRange" + ? [req.range] + : req.type === "delete" + ? [req.keys] + : req.values.length < 50 + ? [[], req.values] + : [], keys = _a[0], newObjs = _a[1]; + var oldCache = req.trans["_cache"]; + return table.mutate(req).then(function (res) { + if (isArray(keys)) { + if (type !== "delete") + keys = res.results; + pkRangeSet.addKeys(keys); + var oldObjs = getFromTransactionCache(keys, oldCache); + if (!oldObjs && type !== "add") { + delsRangeSet.addKeys(keys); + } + if (oldObjs || newObjs) { + trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); + } + } + else if (keys) { + var range = { from: keys.lower, to: keys.upper }; + delsRangeSet.add(range); + pkRangeSet.add(range); + } + else { + pkRangeSet.add(FULL_RANGE); + delsRangeSet.add(FULL_RANGE); + schema.indexes.forEach(function (idx) { return getRangeSet(idx.name).add(FULL_RANGE); }); + } + return res; + }); + } }); + var getRange = function (_a) { + var _b, _c; + var _d = _a.query, index = _d.index, range = _d.range; + return [ + index, + new RangeSet((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY), + ]; + }; + var readSubscribers = { + get: function (req) { return [primaryKey, new RangeSet(req.key)]; }, + getMany: function (req) { return [primaryKey, new RangeSet().addKeys(req.keys)]; }, + count: getRange, + query: getRange, + openCursor: getRange, + }; + keys(readSubscribers).forEach(function (method) { + tableClone[method] = function (req) { + var subscr = PSD.subscr; + if (subscr) { + var getRangeSet = function (indexName) { + var part = "idb://" + dbName + "/" + tableName + "/" + indexName; + return (subscr[part] || + (subscr[part] = new RangeSet())); + }; + var pkRangeSet_1 = getRangeSet(""); + var delsRangeSet_1 = getRangeSet(":dels"); + var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1]; + getRangeSet(queriedIndex.name || "").add(queriedRanges); + if (!queriedIndex.isPrimaryKey) { + if (method === "count") { + delsRangeSet_1.add(FULL_RANGE); + } + else { + var keysPromise_1 = method === "query" && + outbound && + req.values && + table.query(__assign(__assign({}, req), { values: false })); + return table[method].apply(this, arguments).then(function (res) { + if (method === "query") { + if (outbound && req.values) { + return keysPromise_1.then(function (_a) { + var resultingKeys = _a.result; + pkRangeSet_1.addKeys(resultingKeys); + return res; + }); + } + var pKeys = req.values + ? res.result.map(extractKey) + : res.result; + if (req.values) { + pkRangeSet_1.addKeys(pKeys); + } + else { + delsRangeSet_1.addKeys(pKeys); + } + } + else if (method === "openCursor") { + var cursor_1 = res; + var wantValues_1 = req.values; + return (cursor_1 && + Object.create(cursor_1, { + key: { + get: function () { + delsRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.key; + }, + }, + primaryKey: { + get: function () { + var pkey = cursor_1.primaryKey; + delsRangeSet_1.addKey(pkey); + return pkey; + }, + }, + value: { + get: function () { + wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.value; + }, + }, + })); + } + return res; + }); + } + } + } + return table[method].apply(this, arguments); + }; + }); + return tableClone; + } }); + }, +}; +function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { + function addAffectedIndex(ix) { + var rangeSet = getRangeSet(ix.name || ""); + function extractKey(obj) { + return obj != null ? ix.extractKey(obj) : null; + } + var addKeyOrKeys = function (key) { return ix.multiEntry && isArray(key) + ? key.forEach(function (key) { return rangeSet.addKey(key); }) + : rangeSet.addKey(key); }; + (oldObjs || newObjs).forEach(function (_, i) { + var oldKey = oldObjs && extractKey(oldObjs[i]); + var newKey = newObjs && extractKey(newObjs[i]); + if (cmp(oldKey, newKey) !== 0) { + if (oldKey != null) + addKeyOrKeys(oldKey); + if (newKey != null) + addKeyOrKeys(newKey); + } + }); + } + schema.indexes.forEach(addAffectedIndex); +} + +var Dexie$1 = (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; + this._novip = this; + var state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true, + PR1398_maxLoop: 3 + }; + 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", "close", { 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, _this._options.chromeTransactionDurability, 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); + this.use(observabilityMiddleware); + this.use(cacheExistingValuesMiddleware); + this.vip = Object.create(this, { _vip: { value: true } }); + 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.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise(function (resolve, reject) { + if (_this._state.openComplete) { + return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); + } + 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 state = this._state; + var idx = connections.indexOf(this); + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this._novip.idbdb = null; + } + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + }; + Dexie.prototype.close = function () { + this._close(); + var state = this._state; + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + }; + 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 () { + _onDatabaseDeleted(_this._deps, _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: false, + 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 symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol + ? Symbol.observable + : "@@observable"; +var Observable = (function () { + function Observable(subscribe) { + this._subscribe = subscribe; + } + Observable.prototype.subscribe = function (x, error, complete) { + return this._subscribe(!x || typeof x === "function" ? { next: x, error: error, complete: complete } : x); + }; + Observable.prototype[symbolObservable] = function () { + return this; + }; + return Observable; +}()); + +function extendObservabilitySet(target, newSet) { + keys(newSet).forEach(function (part) { + var rangeSet = target[part] || (target[part] = new RangeSet()); + mergeRanges(rangeSet, newSet[part]); + }); + return target; +} + +function liveQuery(querier) { + var hasValue = false; + var currentValue = undefined; + var observable = new Observable(function (observer) { + var scopeFuncIsAsync = isAsyncFunction(querier); + function execute(subscr) { + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var exec = function () { return newScope(querier, { subscr: subscr, trans: null }); }; + var rv = PSD.trans + ? + usePSD(PSD.transless, exec) + : exec(); + if (scopeFuncIsAsync) { + rv.then(decrementExpectedAwaits, decrementExpectedAwaits); + } + return rv; + } + var closed = false; + var accumMuts = {}; + var currentObs = {}; + var subscription = { + get closed() { + return closed; + }, + unsubscribe: function () { + closed = true; + globalEvents.storagemutated.unsubscribe(mutationListener); + }, + }; + observer.start && observer.start(subscription); + var querying = false, startedListening = false; + function shouldNotify() { + return keys(currentObs).some(function (key) { + return accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key]); + }); + } + var mutationListener = function (parts) { + extendObservabilitySet(accumMuts, parts); + if (shouldNotify()) { + doQuery(); + } + }; + var doQuery = function () { + if (querying || closed) + return; + accumMuts = {}; + var subscr = {}; + var ret = execute(subscr); + if (!startedListening) { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); + startedListening = true; + } + querying = true; + Promise.resolve(ret).then(function (result) { + hasValue = true; + currentValue = result; + querying = false; + if (closed) + return; + if (shouldNotify()) { + doQuery(); + } + else { + accumMuts = {}; + currentObs = subscr; + observer.next && observer.next(result); + } + }, function (err) { + querying = false; + hasValue = false; + observer.error && observer.error(err); + subscription.unsubscribe(); + }); + }; + doQuery(); + return subscription; + }); + observable.hasValue = function () { return hasValue; }; + observable.getValue = function () { return currentValue; }; + return observable; +} + +var domDeps; +try { + domDeps = { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; +} +catch (e) { + domDeps = { indexedDB: null, IDBKeyRange: null }; +} + +var Dexie = Dexie$1; +props(Dexie, __assign(__assign({}, fullNameExceptions), { + delete: function (databaseName) { + var db = new Dexie(databaseName, { addons: [] }); + return db.delete(); + }, + exists: function (name) { + return new Dexie(name, { addons: [] }).open().then(function (db) { + db.close(); + return true; + }).catch('NoSuchDatabaseError', function () { return false; }); + }, + getDatabaseNames: function (cb) { + try { + return getDatabaseNames(Dexie.dependencies).then(cb); + } + catch (_a) { + return rejection(new exceptions.MissingAPI()); + } + }, + 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.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, on: globalEvents, liveQuery: liveQuery, extendObservabilitySet: extendObservabilitySet, + getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, cmp: cmp, asap: asap$1, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: domDeps, + 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)); }) })); +Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); + +if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (updatedParts) { + if (!propagatingLocally) { + var event_1; + if (isIEOrEdge) { + event_1 = document.createEvent('CustomEvent'); + event_1.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts); + } + else { + event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { + detail: updatedParts + }); + } + propagatingLocally = true; + dispatchEvent(event_1); + propagatingLocally = false; + } + }); + addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function (_a) { + var detail = _a.detail; + if (!propagatingLocally) { + propagateLocally(detail); + } + }); +} +function propagateLocally(updateParts) { + var wasMe = propagatingLocally; + try { + propagatingLocally = true; + globalEvents.storagemutated.fire(updateParts); + } + finally { + propagatingLocally = wasMe; + } +} +var propagatingLocally = false; + +if (typeof BroadcastChannel !== 'undefined') { + var bc_1 = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); + if (typeof bc_1.unref === 'function') { + bc_1.unref(); + } + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + if (!propagatingLocally) { + bc_1.postMessage(changedParts); + } + }); + bc_1.onmessage = function (ev) { + if (ev.data) + propagateLocally(ev.data); + }; +} +else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + try { + if (!propagatingLocally) { + if (typeof localStorage !== 'undefined') { + localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({ + trig: Math.random(), + changedParts: changedParts, + })); + } + if (typeof self['clients'] === 'object') { + __spreadArray([], self['clients'].matchAll({ includeUncontrolled: true }), true).forEach(function (client) { + return client.postMessage({ + type: STORAGE_MUTATED_DOM_EVENT_NAME, + changedParts: changedParts, + }); + }); + } + } + } + catch (_a) { } + }); + if (typeof addEventListener !== 'undefined') { + addEventListener('storage', function (ev) { + if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) { + var data = JSON.parse(ev.newValue); + if (data) + propagateLocally(data.changedParts); + } + }); + } + var swContainer = self.document && navigator.serviceWorker; + if (swContainer) { + swContainer.addEventListener('message', propagateMessageLocally); + } +} +function propagateMessageLocally(_a) { + var data = _a.data; + if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) { + propagateLocally(data.changedParts); + } +} + +DexiePromise.rejectionMapper = mapError; +setDebug(debug, dexieStackFrameFilter); + +export { Dexie$1 as Dexie, RangeSet, Dexie$1 as default, liveQuery, mergeRanges, rangesOverlap }; +//# sourceMappingURL=dexie.mjs.map diff --git a/dist/dexie.mjs.map b/dist/dexie.mjs.map new file mode 100644 index 000000000..9ce9c2775 --- /dev/null +++ b/dist/dexie.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.mjs","sources":["../node_modules/tslib/tslib.es6.js","../src/globals/global.ts","../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/functions/workaround-undefined-primkey.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/functions/cmp.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/event-wrappers.ts","../src/globals/global-events.ts","../src/classes/transaction/transaction.ts","../src/classes/transaction/transaction-constructor.ts","../src/helpers/index-spec.ts","../src/helpers/table-schema.ts","../src/functions/quirks.ts","../src/dbcore/get-key-extractor.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","../node_modules/safari-14-idb-fix/dist/index.js","../src/classes/dexie/dexie-open.ts","../src/helpers/yield-support.ts","../src/classes/dexie/transaction-helpers.ts","../src/dbcore/virtual-index-middleware.ts","../src/functions/get-object-diff.ts","../src/dbcore/get-effective-keys.ts","../src/hooks/hooks-middleware.ts","../src/dbcore/cache-existing-values-middleware.ts","../src/helpers/rangeset.ts","../src/live-query/observability-middleware.ts","../src/classes/dexie/dexie.ts","../src/classes/observable/observable.ts","../src/live-query/extend-observability-set.ts","../src/live-query/live-query.ts","../src/classes/dexie/dexie-dom-dependencies.ts","../src/classes/dexie/dexie-static-props.ts","../src/live-query/propagate-locally.ts","../src/live-query/enable-broadcast.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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\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 var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, 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\n/** @deprecated */\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\n/** @deprecated */\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 __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\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\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\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 (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, 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, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n","import { _global } from \"../globals/global\";\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\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: T, extension: X): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\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 (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(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: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} {\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 (typeof keyPath === 'string' && 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 == null ? 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 || !hasOwn(obj, currentKeyPath)) 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 \"BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\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]);\nexport const intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, x=>[x,true]);\n\nlet circularRefs: null | WeakMap = null;\nexport function deepClone(any: T): T {\n circularRefs = typeof WeakMap !== 'undefined' && new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone(any: T): T {\n if (!any || typeof any !== 'object') return any;\n let rv = circularRefs && circularRefs.get(any); // Resolve circular references\n if (rv) return rv;\n if (isArray(any)) {\n rv = [];\n circularRefs && circularRefs.set(any, rv);\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(innerDeepClone(any[i]));\n }\n } else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n } else {\n const proto = getProto(any);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs && circularRefs.set(any, rv);\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = innerDeepClone(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\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nexport const getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nexport const asyncIteratorSymbol = typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\")\n : '@asyncIterator';\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 https://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 MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\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 = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = 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 { _global } from '../globals/global';\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend, getProto} 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, getProto(globalP), 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 getProto(nativeP),\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 const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\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() {\n if (!task.awaits) return false;\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 return true;\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, cleanup) {\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 if (cleanup) enqueueNativeMicroTask(decrementExpectedAwaits);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone),\n nativeAwaitCompatibleWrap(onRejected, zone));\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 { errnames, 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.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\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 {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(()=>tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\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: [[]],\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 { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(keyPath: string | ArrayLike) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === \"string\" && !/\\./.test(keyPath) \n ? (obj: object) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\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';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\n\n/** class Table\n * \n * https://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 * https://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 * https://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 if (\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {\n for (let i=0; i a.keyPath.length - b.keyPath.length)[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 const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));\n }\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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * https://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 * https://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * https://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\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 // object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly.\n try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }\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 * https://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * https://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 * https://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 * https://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 * https://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 {auto, keyPath} = this.schema.primKey;\n if (keyPath && 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 let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, 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`, failures);\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * https://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 {auto, keyPath} = this.schema.primKey;\n if (keyPath && 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 let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, 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`, failures);\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * https://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","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(\n a: Uint8Array,\n b: Uint8Array\n) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\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';\nimport { cmp } from \"../../functions/cmp\";\n\n/** class Collection\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * https://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 * https://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 = this.db._options.modifyChunkSize || 200;\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({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\" // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n }).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(()=>(putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>(deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\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 * https://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(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => ctx.value = null;\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 * https://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 * https://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 * https://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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();\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 { 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 Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME) as GlobalDexieEvents;\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';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n * \n * https://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: ChromeTransactionDurability;\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 ||\n (this.db.core \n ? this.db.core.transaction(this.storeNames, this.mode as 'readwrite' | 'readonly', { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n ) as IDBTransaction;\n\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 if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\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(): https://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 * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n * \n * https://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 chromeTransactionDurability: ChromeTransactionDurability,\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 chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\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 { 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 let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\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 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';\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 IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\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}) {\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 let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n \n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\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 reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()\n else\n reqs.push(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 reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\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 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, 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({_novip: 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 { _global } from \"../../globals/global\";\nimport { setProp, keys, slice, isArray, shallowClone, isAsyncFunction, defineProperty, getPropertyDescriptor } 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({_novip: db}: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\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({_novip: 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 {_novip: 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 trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\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 (\n (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n ''+(oldDef.primKey.keyPath||'')\n ) !== (\n ''+(newDef.primKey.keyPath||'')\n ) ||\n // Compare the autoIncrement flag also\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) // IE has bug reading autoIncrement prop.\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 [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\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({_novip: 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 verifyInstalledSchema(db: Dexie, tmpTrans: IDBTransaction): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\n\nexport function adjustToExistingIndexNames({_novip: 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';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\n\n/** class Version\n *\n * https://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 | null; }): 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 = promisableChain(this._cfg.contentUpgrade || nop, 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 { Dexie } from \"../classes/dexie/dexie\";\nimport { Table } from \"../public/types/table\";\nimport { DBNAMES_DB } from \"../globals/constants\";\nimport { DexieDOMDependencies } from \"../public/types/dexie-dom-dependencies\";\nimport { nop } from \"../functions/chaining-functions\";\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\") as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n 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 : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({name}).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\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","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\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, verifyInstalledSchema } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } 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';\nimport safari14Workaround from 'safari-14-idb-fix';\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 const openCanceller = state.openCanceller;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller) throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\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 wasCreated = false;\n\n const tryOpenDB = () => 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 throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\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(); // 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 wasCreated = oldVer < 1;\n db._novip.idbdb = req.result;// db._novip is because db can be an Object.create(origDb).\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._novip.idbdb = req.result; // db._novip is because db can be an Object.create(origDb).\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 {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\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 idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n\n }, reject);\n }).catch(err => {\n if (err && err.name === 'UnknownError' && state.PR1398_maxLoop > 0) {\n // Bug in Chrome after clearing site data\n // https://github.com/dexie/Dexie.js/issues/543#issuecomment-1795736695\n state.PR1398_maxLoop--;\n console.warn('Dexie: Workaround for Chrome UnknownError on open()');\n return tryOpenDB();\n } else {\n return Promise.reject(err);\n }\n });\n \n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([\n openCanceller,\n (typeof navigator === 'undefined' ? Promise.resolve() : safari14Workaround()).then(tryOpenDB)\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 throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>db.on.ready.fire(db.vip))).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(db.vip))).then(fireRemainders)\n }\n });\n }).finally(()=>{\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n return db;\n }).catch(err => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\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 { }\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection (err);\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 { errnames, 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 try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(\n db,\n mode,\n storeNames,\n null,\n scopeFunc\n ));\n }\n return rejection(ex);\n }\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 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(\n cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)\n ) :\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 primaryKey: {\n get() {\n return cursor.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 { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\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 // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) 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","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","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 { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from \"../functions/get-object-diff\";\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } 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} :\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 if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] = additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\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\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n","import { deepClone } from \"../functions/utils\";\nimport { DBCore } from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport Promise from \"../helpers/promise\";\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans[\"_cache\"],\n req.cache === \"clone\"\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== \"add\") req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { cmp } from \"../functions/cmp\";\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from \"../public/types/rangeset\";\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n * \n */\n\nfunction isEmptyRange(node: IntervalTree | {from: IndexableType, to: IndexableType}): node is EmptyRange {\n return !(\"from\" in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function(fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(this, arguments.length ? {d:1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree} : {d:0});\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n\n [iteratorSymbol](): Iterator {\n return getRangeSetIterator(this);\n }\n});\n\nfunction addRange(target: IntervalTree, from: IndexableType, to: IndexableType) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n \n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(target: IntervalTree, newSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n function _addRangeSet(\n target: IntervalTree,\n { from, to, l, r }: IntervalTreeNode | {from: IndexableType, to: IndexableType, l?: undefined, r?: undefined}\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if(!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator {\n let state: RangeSetIteratorState = isEmptyRange(node) ? null : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n // \n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n // \n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L] \n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === \"r\" ? \"l\" : \"r\"; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r]; \n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import { getFromTransactionCache } from \"../dbcore/cache-existing-values-middleware\";\nimport { cmp } from \"../functions/cmp\";\nimport { isArray, keys } from \"../functions/utils\";\nimport { PSD } from \"../helpers/promise\";\nimport { RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\n\nexport const observabilityMiddleware: Middleware = {\n stack: \"dbcore\",\n level: 0,\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts =\n trans.mutatedParts || (trans.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === \"deleteRange\"\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === \"delete\"\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [[], req.values] // keys = empty array - will be resolved in mutate().then(...).\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n const oldCache = req.trans[\"_cache\"];\n return table.mutate(req).then((res) => {\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n if (type !== \"delete\") keys = res.results;\n // individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs = getFromTransactionCache(keys, oldCache);\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs && type !== \"add\") {\n // delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(range.lower ?? core.MIN_KEY, range.upper ?? core.MAX_KEY),\n ];\n\n const readSubscribers: {[method in\n Exclude]: \n (req: any) => [DBCoreIndex, RangeSet]\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n }\n\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD;\n if (subscr) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (subscr[part] ||\n (subscr[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === \"count\") {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === \"query\" &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({ result: resultingKeys }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === \"openCursor\") {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest).values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: any[] | undefined,\n newObjs: any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) => ix.multiEntry && isArray(key)\n // multiEntry and the old property was an array - add each array entry to the rangeSet:\n ? key.forEach(key => rangeSet.addKey(key))\n // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n : rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\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 { _onDatabaseDeleted } 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';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\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 PR1398_maxLoop?: number;\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 _vip?: boolean;\n _novip?: Dexie;// db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\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 this._novip = this;\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 PR1398_maxLoop: 3\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\", \"close\", { 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, this._options.chromeTransactionDurability, 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 this.use(observabilityMiddleware);\n this.use(cacheExistingValuesMiddleware);\n\n this.vip = Object.create(this, {_vip: {value: true}}) as Dexie;\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.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\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 state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this._novip.idbdb = null; // db._novip is because db can be an Object.create(origDb).\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 close(): void {\n this._close();\n const state = this._state;\n this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\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 _onDatabaseDeleted(this._deps, 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 {\n Observable as IObservable,\n Observer,\n Subscription,\n} from \"../../public/types/observable\";\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\" as any;\n\nexport class Observable implements IObservable {\n private _subscribe: (observer: Observer) => Subscription;\n hasValue?: ()=>boolean;\n getValue?: ()=>T;\n\n constructor(subscribe: (observer: Observer) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === \"function\" ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { deepClone, keys } from \"../functions/utils\";\nimport { mergeRanges, RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach(part => {\n const rangeSet = target[part] || (target[part] = new RangeSet());\n mergeRanges(rangeSet, newSet[part]);\n });\n return target;\n}\n","import { isAsyncFunction, keys } from \"../functions/utils\";\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME } from \"../globals/global-events\";\nimport {\n decrementExpectedAwaits,\n incrementExpectedAwaits,\n newScope,\n PSD,\n usePSD,\n} from \"../helpers/promise\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n Observable as IObservable,\n Subscription,\n} from \"../public/types/observable\";\nimport { Observable } from \"../classes/observable/observable\";\nimport { extendObservabilitySet } from \"./extend-observability-set\";\nimport { rangesOverlap } from \"../helpers/rangeset\";\n\nexport function liveQuery(querier: () => T | Promise): IObservable {\n let hasValue = false;\n let currentValue: T = undefined as any;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(subscr: ObservabilitySet) {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const exec = () => newScope(querier, { subscr, trans: null });\n const rv = PSD.trans\n ? // Ignore current transaction if active when calling subscribe().\n usePSD(PSD.transless, exec)\n : exec();\n if (scopeFuncIsAsync) {\n (rv as Promise).then(\n decrementExpectedAwaits,\n decrementExpectedAwaits\n );\n }\n return rv;\n }\n\n let closed = false;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n closed = true;\n globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let querying = false,\n startedListening = false;\n\n function shouldNotify() {\n return keys(currentObs).some(\n (key) =>\n accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key])\n );\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const doQuery = () => {\n if (querying || closed) return;\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n const ret = execute(subscr);\n if (!startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n }\n querying = true;\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n querying = false;\n if (closed) return;\n if (shouldNotify()) {\n // Mutations has happened while we were querying. Redo query.\n doQuery();\n } else {\n accumMuts = {};\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n observer.next && observer.next(result);\n }\n },\n (err) => {\n querying = false;\n hasValue = false;\n observer.error && observer.error(err);\n subscription.unsubscribe();\n }\n );\n };\n\n doQuery();\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies\n\ntry {\n domDeps = {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, asap } from '../../functions/utils';\nimport { getObjectDiff } from \"../../functions/get-object-diff\";\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } 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';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\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, {addons: []});\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 try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\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 on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\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: domDeps,\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, // Commented because solved in index-umd.ts instead.\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 // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { isIEOrEdge } from '../globals/constants';\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME, STORAGE_MUTATED_DOM_EVENT_NAME } from '../globals/global-events';\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event: CustomEvent;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n } else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({detail}: CustomEvent) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\n\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n globalEvents.storagemutated.fire(updateParts);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n } \n \n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n bc.onmessage = (ev) => {\n if (ev.data) propagateLocally(ev.data);\n };\n} else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n // DOM verified - when typeof self !== \"undefined\", we are a window or worker. Not a Node process.\n\n //\n // Propagate local changes to remote tabs/windows via storage event and service worker\n // via messages. We have this code here because of https://bugs.webkit.org/show_bug.cgi?id=161472.\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n // We're a browsing window or tab. Propagate to other windows/tabs via storage event:\n localStorage.setItem(\n STORAGE_MUTATED_DOM_EVENT_NAME,\n JSON.stringify({\n trig: Math.random(),\n changedParts,\n })\n );\n }\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n })\n );\n }\n }\n } catch {}\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev: StorageEvent) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data) propagateLocally(data.changedParts);\n }\n });\n }\n\n //\n // Propagate messages from service worker\n //\n const swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\n if (swContainer) {\n // We're a browser window and want to propagate message from the SW:\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\n\nfunction propagateMessageLocally({ data }: MessageEvent) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\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';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport { liveQuery } from './live-query/live-query';\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 { RangeSet, mergeRanges, rangesOverlap } from \"./helpers/rangeset\";\nexport { Dexie, liveQuery }; // Comply with public/index.d.ts.\nexport default Dexie;\n"],"names":["asap","_a","Promise","Dexie","Debug.debug","Debug.getErrorWithStack","safari14Workaround","_Dexie","Debug.setDebug"],"mappings":";;;;;;;;;;;;;AAAA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAkBO,IAAI,QAAQ,GAAG,WAAW;AACjC,IAAI,QAAQ,GAAG,MAAM,CAAC,MAAM,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE;AACrD,QAAQ,KAAK,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC7D,YAAY,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AAC7B,YAAY,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;AACzF,SAAS;AACT,QAAQ,OAAO,CAAC,CAAC;AACjB,MAAK;AACL,IAAI,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AAC3C,EAAC;AA4HM,SAAS,aAAa,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;AAC9C,IAAI,IAAI,IAAI,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AACzF,QAAQ,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,IAAI,CAAC,EAAE;AACh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AEvC,kBAAI,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,EAAE,mBAAmB,EAAE,IAAI,EAAE,CAAC,QAAE,OAAO,CAClE,UAAC,MAAM;wBACL,OAAA,MAAM,CAAC,WAAW,CAAC;4BACjB,IAAI,EAAE,8BAA8B;4BACpC,YAAY,cAAA;yBACb,CAAC;qBAAA,CACL,CAAC;iBACH;aACF;SACF;QAAC,WAAM,GAAE;KACX,CAAC,CAAC;IAKH,IAAI,OAAO,gBAAgB,KAAK,WAAW,EAAE;QACzC,gBAAgB,CAAC,SAAS,EAAE,UAAC,EAAgB;YAC7C,IAAI,EAAE,CAAC,GAAG,KAAK,8BAA8B,EAAE;gBAC7C,IAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;gBACrC,IAAI,IAAI;oBAAE,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;aAC/C;SACF,CAAC,CAAC;KACJ;IAKD,IAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,IAAI,SAAS,CAAC,aAAa,CAAC;IAC7D,IAAI,WAAW,EAAE;QAEf,WAAW,CAAC,gBAAgB,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;KAClE;CACF;AAED,SAAS,uBAAuB,CAAC,EAAsB;QAApB,IAAI,UAAA;IACrC,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,8BAA8B,EAAE;QACxD,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;KACrC;AACH;;AChFA,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCQ,QAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC;;;;"} \ No newline at end of file diff --git a/dist/modern/dexie.min.mjs b/dist/modern/dexie.min.mjs new file mode 100644 index 000000000..087cf3b07 --- /dev/null +++ b/dist/modern/dexie.min.mjs @@ -0,0 +1,2 @@ +const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,t=Object.keys,n=Array.isArray;function r(e,n){return"object"!=typeof n||t(n).forEach((function(t){e[t]=n[t]})),e}"undefined"==typeof Promise||e.Promise||(e.Promise=Promise);const s=Object.getPrototypeOf,i={}.hasOwnProperty;function o(e,t){return i.call(e,t)}function a(e,n){"function"==typeof n&&(n=n(s(e))),("undefined"==typeof Reflect?t:Reflect.ownKeys)(n).forEach((t=>{l(e,t,n[t])}))}const u=Object.defineProperty;function l(e,t,n,s){u(e,t,r(n&&o(n,"get")&&"function"==typeof n.get?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},s))}function c(e){return{from:function(t){return e.prototype=Object.create(t.prototype),l(e.prototype,"constructor",e),{extend:a.bind(null,e.prototype)}}}}const h=Object.getOwnPropertyDescriptor;function d(e,t){let n;return h(e,t)||(n=s(e))&&d(n,t)}const f=[].slice;function p(e,t,n){return f.call(e,t,n)}function y(e,t){return t(e)}function m(e){if(!e)throw new Error("Assertion Failed")}function v(t){e.setImmediate?setImmediate(t):setTimeout(t,0)}function g(e,t){return e.reduce(((e,n,r)=>{var s=t(n,r);return s&&(e[s[0]]=s[1]),e}),{})}function b(e,t){if("string"==typeof t&&o(e,t))return e[t];if(!t)return e;if("string"!=typeof t){for(var n=[],r=0,s=t.length;r["Int","Uint","Float"].map((t=>t+e+"Array")))))).filter((t=>e[t])),P=E.map((t=>e[t]));g(E,(e=>[e,!0]));let K=null;function O(e){K="undefined"!=typeof WeakMap&&new WeakMap;const t=S(e);return K=null,t}function S(e){if(!e||"object"!=typeof e)return e;let t=K&&K.get(e);if(t)return t;if(n(e)){t=[],K&&K.set(e,t);for(var r=0,i=e.length;r=0)t=e;else{const n=s(e);for(var a in t=n===Object.prototype?{}:Object.create(n),K&&K.set(e,t),e)o(e,a)&&(t[a]=S(e[a]))}return t}const{toString:A}={};function C(e){return A.call(e).slice(8,-1)}const j="undefined"!=typeof Symbol?Symbol.iterator:"@@iterator",D="symbol"==typeof j?function(e){var t;return null!=e&&(t=e[j])&&t.apply(e)}:function(){return null},I={};function B(e){var t,r,s,i;if(1===arguments.length){if(n(e))return e.slice();if(this===I&&"string"==typeof e)return[e];if(i=D(e)){for(r=[];!(s=i.next()).done;)r.push(s.value);return r}if(null==e)return[e];if("number"==typeof(t=e.length)){for(r=new Array(t);t--;)r[t]=e[t];return r}return[e]}for(t=arguments.length,r=new Array(t);t--;)r[t]=arguments[t];return r}const T="undefined"!=typeof Symbol?e=>"AsyncFunction"===e[Symbol.toStringTag]:()=>!1;var R="undefined"!=typeof location&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function F(e,t){R=e,M=t}var M=()=>!0;const N=!new Error("").stack;function q(){if(N)try{throw q.arguments,new Error}catch(e){return e}return new Error}function $(e,t){var n=e.stack;return n?(t=t||0,0===n.indexOf(e.name)&&(t+=(e.name+e.message).split("\n").length),n.split("\n").slice(t).filter(M).map((e=>"\n"+e)).join("")):""}var U=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],L=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(U),V={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function W(e,t){this._e=q(),this.name=e,this.message=t}function Y(e,t){return e+". Errors: "+Object.keys(t).map((e=>t[e].toString())).filter(((e,t,n)=>n.indexOf(e)===t)).join("\n")}function z(e,t,n,r){this._e=q(),this.failures=t,this.failedKeys=r,this.successCount=n,this.message=Y(e,t)}function G(e,t){this._e=q(),this.name="BulkError",this.failures=Object.keys(t).map((e=>t[e])),this.failuresByPos=t,this.message=Y(e,t)}c(W).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+$(this._e,2))}},toString:function(){return this.name+": "+this.message}}),c(z).from(W),c(G).from(W);var H=L.reduce(((e,t)=>(e[t]=t+"Error",e)),{});const Q=W;var X=L.reduce(((e,t)=>{var n=t+"Error";function r(e,r){this._e=q(),this.name=n,e?"string"==typeof e?(this.message=`${e}${r?"\n "+r:""}`,this.inner=r||null):"object"==typeof e&&(this.message=`${e.name} ${e.message}`,this.inner=e):(this.message=V[t]||n,this.inner=null)}return c(r).from(Q),e[t]=r,e}),{});X.Syntax=SyntaxError,X.Type=TypeError,X.Range=RangeError;var J=U.reduce(((e,t)=>(e[t+"Error"]=X[t],e)),{});var Z=L.reduce(((e,t)=>(-1===["Syntax","Type","Range"].indexOf(t)&&(e[t+"Error"]=X[t]),e)),{});function ee(){}function te(e){return e}function ne(e,t){return null==e||e===te?t:function(n){return t(e(n))}}function re(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function se(e,t){return e===ee?t:function(){var n=e.apply(this,arguments);void 0!==n&&(arguments[0]=n);var r=this.onsuccess,s=this.onerror;this.onsuccess=null,this.onerror=null;var i=t.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?re(r,this.onsuccess):r),s&&(this.onerror=this.onerror?re(s,this.onerror):s),void 0!==i?i:n}}function ie(e,t){return e===ee?t:function(){e.apply(this,arguments);var n=this.onsuccess,r=this.onerror;this.onsuccess=this.onerror=null,t.apply(this,arguments),n&&(this.onsuccess=this.onsuccess?re(n,this.onsuccess):n),r&&(this.onerror=this.onerror?re(r,this.onerror):r)}}function oe(e,t){return e===ee?t:function(n){var s=e.apply(this,arguments);r(n,s);var i=this.onsuccess,o=this.onerror;this.onsuccess=null,this.onerror=null;var a=t.apply(this,arguments);return i&&(this.onsuccess=this.onsuccess?re(i,this.onsuccess):i),o&&(this.onerror=this.onerror?re(o,this.onerror):o),void 0===s?void 0===a?void 0:a:r(s,a)}}function ae(e,t){return e===ee?t:function(){return!1!==t.apply(this,arguments)&&e.apply(this,arguments)}}function ue(e,t){return e===ee?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,s=arguments.length,i=new Array(s);s--;)i[s]=arguments[s];return n.then((function(){return t.apply(r,i)}))}return t.apply(this,arguments)}}Z.ModifyError=z,Z.DexieError=W,Z.BulkError=G;var le={};const ce=100,[he,de,fe]="undefined"==typeof Promise?[]:(()=>{let e=Promise.resolve();if("undefined"==typeof crypto||!crypto.subtle)return[e,s(e),e];const t=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[t,s(t),e]})(),pe=de&&de.then,ye=he&&he.constructor,me=!!fe;var ve=!1,ge=fe?()=>{fe.then($e)}:e.setImmediate?setImmediate.bind(null,$e):e.MutationObserver?()=>{var e=document.createElement("div");new MutationObserver((()=>{$e(),e=null})).observe(e,{attributes:!0}),e.setAttribute("i","1")}:()=>{setTimeout($e,0)},be=function(e,t){Se.push([e,t]),we&&(ge(),we=!1)},_e=!0,we=!0,xe=[],ke=[],Ee=null,Pe=te,Ke={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:dt,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach((e=>{try{dt(e[0],e[1])}catch(e){}}))}},Oe=Ke,Se=[],Ae=0,Ce=[];function je(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");this._listeners=[],this.onuncatched=ee,this._lib=!1;var t=this._PSD=Oe;if(R&&(this._stackHolder=q(),this._prev=null,this._numPrev=0),"function"!=typeof e){if(e!==le)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(!1===this._state&&Te(this,this._value))}this._state=null,this._value=null,++t.ref,Be(this,e)}const De={get:function(){var e=Oe,t=Xe;function n(n,r){var s=!e.global&&(e!==Oe||t!==Xe);const i=s&&!tt();var o=new je(((t,o)=>{Fe(this,new Ie(lt(n,e,s,i),lt(r,e,s,i),t,o,e))}));return R&&qe(o,this),o}return n.prototype=le,n},set:function(e){l(this,"then",e&&e.prototype===le?De:{get:function(){return e},set:De.set})}};function Ie(e,t,n,r,s){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.resolve=n,this.reject=r,this.psd=s}function Be(e,t){try{t((t=>{if(null===e._state){if(t===e)throw new TypeError("A promise cannot be resolved with itself.");var n=e._lib&&Ue();t&&"function"==typeof t.then?Be(e,((e,n)=>{t instanceof je?t._then(e,n):t.then(e,n)})):(e._state=!0,e._value=t,Re(e)),n&&Le()}}),Te.bind(null,e))}catch(t){Te(e,t)}}function Te(e,t){if(ke.push(t),null===e._state){var n=e._lib&&Ue();t=Pe(t),e._state=!1,e._value=t,R&&null!==t&&"object"==typeof t&&!t._promise&&function(e,t,n){try{e.apply(null,n)}catch(e){t&&t(e)}}((()=>{var n=d(t,"stack");t._promise=e,l(t,"stack",{get:()=>ve?n&&(n.get?n.get.apply(t):n.value):e.stack})})),function(e){xe.some((t=>t._value===e._value))||xe.push(e)}(e),Re(e),n&&Le()}}function Re(e){var t=e._listeners;e._listeners=[];for(var n=0,r=t.length;n{0==--Ae&&Ve()}),[]))}function Fe(e,t){if(null!==e._state){var n=e._state?t.onFulfilled:t.onRejected;if(null===n)return(e._state?t.resolve:t.reject)(e._value);++t.psd.ref,++Ae,be(Me,[n,e,t])}else e._listeners.push(t)}function Me(e,t,n){try{Ee=t;var r,s=t._value;t._state?r=e(s):(ke.length&&(ke=[]),r=e(s),-1===ke.indexOf(s)&&function(e){var t=xe.length;for(;t;)if(xe[--t]._value===e._value)return void xe.splice(t,1)}(t)),n.resolve(r)}catch(e){n.reject(e)}finally{Ee=null,0==--Ae&&Ve(),--n.psd.ref||n.psd.finalize()}}function Ne(e,t,n){if(t.length===n)return t;var r="";if(!1===e._state){var s,i,o=e._value;null!=o?(s=o.name||"Error",i=o.message||o,r=$(o,0)):(s=o,i=""),t.push(s+(i?": "+i:"")+r)}return R&&((r=$(e._stackHolder,2))&&-1===t.indexOf(r)&&t.push(r),e._prev&&Ne(e._prev,t,n)),t}function qe(e,t){var n=t?t._numPrev+1:0;n<100&&(e._prev=t,e._numPrev=n)}function $e(){Ue()&&Le()}function Ue(){var e=_e;return _e=!1,we=!1,e}function Le(){var e,t,n;do{for(;Se.length>0;)for(e=Se,Se=[],n=e.length,t=0;t0);_e=!0,we=!0}function Ve(){var e=xe;xe=[],e.forEach((e=>{e._PSD.onunhandled.call(null,e._value,e)}));for(var t=Ce.slice(0),n=t.length;n;)t[--n]()}function We(e){return new je(le,!1,e)}function Ye(e,t){var n=Oe;return function(){var r=Ue(),s=Oe;try{return it(n,!0),e.apply(this,arguments)}catch(e){t&&t(e)}finally{it(s,!1),r&&Le()}}}a(je.prototype,{then:De,_then:function(e,t){Fe(this,new Ie(null,null,e,t,Oe))},catch:function(e){if(1===arguments.length)return this.then(null,e);var t=arguments[0],n=arguments[1];return"function"==typeof t?this.then(null,(e=>e instanceof t?n(e):We(e))):this.then(null,(e=>e&&e.name===t?n(e):We(e)))},finally:function(e){return this.then((t=>(e(),t)),(t=>(e(),We(t))))},stack:{get:function(){if(this._stack)return this._stack;try{ve=!0;var e=Ne(this,[],20).join("\nFrom previous: ");return null!==this._state&&(this._stack=e),e}finally{ve=!1}}},timeout:function(e,t){return e<1/0?new je(((n,r)=>{var s=setTimeout((()=>r(new X.Timeout(t))),e);this.then(n,r).finally(clearTimeout.bind(null,s))})):this}}),"undefined"!=typeof Symbol&&Symbol.toStringTag&&l(je.prototype,Symbol.toStringTag,"Dexie.Promise"),Ke.env=ot(),a(je,{all:function(){var e=B.apply(null,arguments).map(nt);return new je((function(t,n){0===e.length&&t([]);var r=e.length;e.forEach(((s,i)=>je.resolve(s).then((n=>{e[i]=n,--r||t(e)}),n)))}))},resolve:e=>{if(e instanceof je)return e;if(e&&"function"==typeof e.then)return new je(((t,n)=>{e.then(t,n)}));var t=new je(le,!0,e);return qe(t,Ee),t},reject:We,race:function(){var e=B.apply(null,arguments).map(nt);return new je(((t,n)=>{e.map((e=>je.resolve(e).then(t,n)))}))},PSD:{get:()=>Oe,set:e=>Oe=e},totalEchoes:{get:()=>Xe},newPSD:Ze,usePSD:at,scheduler:{get:()=>be,set:e=>{be=e}},rejectionMapper:{get:()=>Pe,set:e=>{Pe=e}},follow:(e,t)=>new je(((n,r)=>Ze(((t,n)=>{var r=Oe;r.unhandleds=[],r.onunhandled=n,r.finalize=re((function(){!function(e){function t(){e(),Ce.splice(Ce.indexOf(t),1)}Ce.push(t),++Ae,be((()=>{0==--Ae&&Ve()}),[])}((()=>{0===this.unhandleds.length?t():n(this.unhandleds[0])}))}),r.finalize),e()}),t,n,r)))}),ye&&(ye.allSettled&&l(je,"allSettled",(function(){const e=B.apply(null,arguments).map(nt);return new je((t=>{0===e.length&&t([]);let n=e.length;const r=new Array(n);e.forEach(((e,s)=>je.resolve(e).then((e=>r[s]={status:"fulfilled",value:e}),(e=>r[s]={status:"rejected",reason:e})).then((()=>--n||t(r)))))}))})),ye.any&&"undefined"!=typeof AggregateError&&l(je,"any",(function(){const e=B.apply(null,arguments).map(nt);return new je(((t,n)=>{0===e.length&&n(new AggregateError([]));let r=e.length;const s=new Array(r);e.forEach(((e,i)=>je.resolve(e).then((e=>t(e)),(e=>{s[i]=e,--r||n(new AggregateError(s))}))))}))})));const ze={awaits:0,echoes:0,id:0};var Ge=0,He=[],Qe=0,Xe=0,Je=0;function Ze(e,t,n,s){var i=Oe,o=Object.create(i);o.parent=i,o.ref=0,o.global=!1,o.id=++Je;var a=Ke.env;o.env=me?{Promise:je,PromiseProp:{value:je,configurable:!0,writable:!0},all:je.all,race:je.race,allSettled:je.allSettled,any:je.any,resolve:je.resolve,reject:je.reject,nthen:ct(a.nthen,o),gthen:ct(a.gthen,o)}:{},t&&r(o,t),++i.ref,o.finalize=function(){--this.parent.ref||this.parent.finalize()};var u=at(o,e,n,s);return 0===o.ref&&o.finalize(),u}function et(){return ze.id||(ze.id=++Ge),++ze.awaits,ze.echoes+=ce,ze.id}function tt(){return!!ze.awaits&&(0==--ze.awaits&&(ze.id=0),ze.echoes=ze.awaits*ce,!0)}function nt(e){return ze.echoes&&e&&e.constructor===ye?(et(),e.then((e=>(tt(),e)),(e=>(tt(),ft(e))))):e}function rt(e){++Xe,ze.echoes&&0!=--ze.echoes||(ze.echoes=ze.id=0),He.push(Oe),it(e,!0)}function st(){var e=He[He.length-1];He.pop(),it(e,!1)}function it(t,n){var r=Oe;if((n?!ze.echoes||Qe++&&t===Oe:!Qe||--Qe&&t===Oe)||ut(n?rt.bind(null,t):st),t!==Oe&&(Oe=t,r===Ke&&(Ke.env=ot()),me)){var s=Ke.env.Promise,i=t.env;de.then=i.nthen,s.prototype.then=i.gthen,(r.global||t.global)&&(Object.defineProperty(e,"Promise",i.PromiseProp),s.all=i.all,s.race=i.race,s.resolve=i.resolve,s.reject=i.reject,i.allSettled&&(s.allSettled=i.allSettled),i.any&&(s.any=i.any))}}function ot(){var t=e.Promise;return me?{Promise:t,PromiseProp:Object.getOwnPropertyDescriptor(e,"Promise"),all:t.all,race:t.race,allSettled:t.allSettled,any:t.any,resolve:t.resolve,reject:t.reject,nthen:de.then,gthen:t.prototype.then}:{}}function at(e,t,n,r,s){var i=Oe;try{return it(e,!0),t(n,r,s)}finally{it(i,!1)}}function ut(e){pe.call(he,e)}function lt(e,t,n,r){return"function"!=typeof e?e:function(){var s=Oe;n&&et(),it(t,!0);try{return e.apply(this,arguments)}finally{it(s,!1),r&&ut(tt)}}}function ct(e,t){return function(n,r){return e.call(this,lt(n,t),lt(r,t))}}-1===(""+pe).indexOf("[native code]")&&(et=tt=ee);const ht="unhandledrejection";function dt(t,n){var s;try{s=n.onuncatched(t)}catch(e){}if(!1!==s)try{var i,o={promise:n,reason:t};if(e.document&&document.createEvent?((i=document.createEvent("Event")).initEvent(ht,!0,!0),r(i,o)):e.CustomEvent&&r(i=new CustomEvent(ht,{detail:o}),o),i&&e.dispatchEvent&&(dispatchEvent(i),!e.PromiseRejectionEvent&&e.onunhandledrejection))try{e.onunhandledrejection(i)}catch(e){}R&&i&&!i.defaultPrevented&&console.warn(`Unhandled rejection: ${t.stack||t}`)}catch(e){}}var ft=je.reject;function pt(e,t,n,r){if(e.idbdb&&(e._state.openComplete||Oe.letThrough||e._vip)){var s=e._createTransaction(t,n,e._dbSchema);try{s.create(),e._state.PR1398_maxLoop=3}catch(s){return s.name===H.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then((()=>pt(e,t,n,r)))):ft(s)}return s._promise(t,((e,t)=>Ze((()=>(Oe.trans=s,r(e,t,s)))))).then((e=>s._completion.then((()=>e))))}if(e._state.openComplete)return ft(new X.DatabaseClosed(e._state.dbOpenError));if(!e._state.isBeingOpened){if(!e._options.autoOpen)return ft(new X.DatabaseClosed);e.open().catch(ee)}return e._state.dbReadyPromise.then((()=>pt(e,t,n,r)))}const yt="3.2.6",mt=String.fromCharCode(65535),vt=-1/0,gt="Invalid key provided. Keys must be of type string, number, Date or Array.",bt="String expected.",_t=[],wt="undefined"!=typeof navigator&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),xt=wt,kt=wt,Et=e=>!/(dexie\.js|dexie\.min\.js)/.test(e),Pt="__dbnames",Kt="readonly",Ot="readwrite";function St(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}const At={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Ct(e){return"string"!=typeof e||/\./.test(e)?e=>e:t=>(void 0===t[e]&&e in t&&delete(t=O(t))[e],t)}class jt{_trans(e,t,n){const r=this._tx||Oe.trans,s=this.name;function i(e,n,r){if(!r.schema[s])throw new X.NotFound("Table "+s+" not part of transaction");return t(r.idbtrans,r)}const o=Ue();try{return r&&r.db===this.db?r===Oe.trans?r._promise(e,i,n):Ze((()=>r._promise(e,i,n)),{trans:r,transless:Oe.transless||Oe}):pt(this.db,e,[this.name],i)}finally{o&&Le()}}get(e,t){return e&&e.constructor===Object?this.where(e).first(t):this._trans("readonly",(t=>this.core.get({trans:t,key:e}).then((e=>this.hook.reading.fire(e))))).then(t)}where(e){if("string"==typeof e)return new this.db.WhereClause(this,e);if(n(e))return new this.db.WhereClause(this,`[${e.join("+")}]`);const r=t(e);if(1===r.length)return this.where(r[0]).equals(e[r[0]]);const s=this.schema.indexes.concat(this.schema.primKey).filter((e=>{if(e.compound&&r.every((t=>e.keyPath.indexOf(t)>=0))){for(let t=0;te.keyPath.length-t.keyPath.length))[0];if(s&&this.db._maxKey!==mt){const t=s.keyPath.slice(0,r.length);return this.where(t).equals(t.map((t=>e[t])))}!s&&R&&console.warn(`The query ${JSON.stringify(e)} on ${this.name} would benefit of a compound index [${r.join("+")}]`);const{idxByName:i}=this.schema,o=this.db._deps.indexedDB;function a(e,t){try{return 0===o.cmp(e,t)}catch(e){return!1}}const[u,l]=r.reduce((([t,r],s)=>{const o=i[s],u=e[s];return[t||o,t||!o?St(r,o&&o.multi?e=>{const t=b(e,s);return n(t)&&t.some((e=>a(u,e)))}:e=>a(u,b(e,s))):r]}),[null,null]);return u?this.where(u.name).equals(e[u.keyPath]).filter(l):s?this.filter(l):this.where(r).equals("")}filter(e){return this.toCollection().and(e)}count(e){return this.toCollection().count(e)}offset(e){return this.toCollection().offset(e)}limit(e){return this.toCollection().limit(e)}each(e){return this.toCollection().each(e)}toArray(e){return this.toCollection().toArray(e)}toCollection(){return new this.db.Collection(new this.db.WhereClause(this))}orderBy(e){return new this.db.Collection(new this.db.WhereClause(this,n(e)?`[${e.join("+")}]`:e))}reverse(){return this.toCollection().reverse()}mapToClass(e){this.schema.mappedClass=e;const t=t=>{if(!t)return t;const n=Object.create(e.prototype);for(var r in t)if(o(t,r))try{n[r]=t[r]}catch(e){}return n};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=t,this.hook("reading",t),e}defineClass(){return this.mapToClass((function(e){r(this,e)}))}add(e,t){const{auto:n,keyPath:r}=this.schema.primKey;let s=e;return r&&n&&(s=Ct(r)(e)),this._trans("readwrite",(e=>this.core.mutate({trans:e,type:"add",keys:null!=t?[t]:null,values:[s]}))).then((e=>e.numFailures?je.reject(e.failures[0]):e.lastResult)).then((t=>{if(r)try{_(e,r,t)}catch(e){}return t}))}update(e,r){if("object"!=typeof e||n(e))return this.where(":id").equals(e).modify(r);{const n=b(e,this.schema.primKey.keyPath);if(void 0===n)return ft(new X.InvalidArgument("Given object does not contain its primary key"));try{"function"!=typeof r?t(r).forEach((t=>{_(e,t,r[t])})):r(e,{value:e,primKey:n})}catch(e){}return this.where(":id").equals(n).modify(r)}}put(e,t){const{auto:n,keyPath:r}=this.schema.primKey;let s=e;return r&&n&&(s=Ct(r)(e)),this._trans("readwrite",(e=>this.core.mutate({trans:e,type:"put",values:[s],keys:null!=t?[t]:null}))).then((e=>e.numFailures?je.reject(e.failures[0]):e.lastResult)).then((t=>{if(r)try{_(e,r,t)}catch(e){}return t}))}delete(e){return this._trans("readwrite",(t=>this.core.mutate({trans:t,type:"delete",keys:[e]}))).then((e=>e.numFailures?je.reject(e.failures[0]):void 0))}clear(){return this._trans("readwrite",(e=>this.core.mutate({trans:e,type:"deleteRange",range:At}))).then((e=>e.numFailures?je.reject(e.failures[0]):void 0))}bulkGet(e){return this._trans("readonly",(t=>this.core.getMany({keys:e,trans:t}).then((e=>e.map((e=>this.hook.reading.fire(e)))))))}bulkAdd(e,t,n){const r=Array.isArray(t)?t:void 0,s=(n=n||(r?void 0:t))?n.allKeys:void 0;return this._trans("readwrite",(t=>{const{auto:n,keyPath:i}=this.schema.primKey;if(i&&r)throw new X.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(r&&r.length!==e.length)throw new X.InvalidArgument("Arguments objects and keys must have the same length");const o=e.length;let a=i&&n?e.map(Ct(i)):e;return this.core.mutate({trans:t,type:"add",keys:r,values:a,wantResults:s}).then((({numFailures:e,results:t,lastResult:n,failures:r})=>{if(0===e)return s?t:n;throw new G(`${this.name}.bulkAdd(): ${e} of ${o} operations failed`,r)}))}))}bulkPut(e,t,n){const r=Array.isArray(t)?t:void 0,s=(n=n||(r?void 0:t))?n.allKeys:void 0;return this._trans("readwrite",(t=>{const{auto:n,keyPath:i}=this.schema.primKey;if(i&&r)throw new X.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(r&&r.length!==e.length)throw new X.InvalidArgument("Arguments objects and keys must have the same length");const o=e.length;let a=i&&n?e.map(Ct(i)):e;return this.core.mutate({trans:t,type:"put",keys:r,values:a,wantResults:s}).then((({numFailures:e,results:t,lastResult:n,failures:r})=>{if(0===e)return s?t:n;throw new G(`${this.name}.bulkPut(): ${e} of ${o} operations failed`,r)}))}))}bulkDelete(e){const t=e.length;return this._trans("readwrite",(t=>this.core.mutate({trans:t,type:"delete",keys:e}))).then((({numFailures:e,lastResult:n,failures:r})=>{if(0===e)return n;throw new G(`${this.name}.bulkDelete(): ${e} of ${t} operations failed`,r)}))}}function Dt(e){var r={},s=function(t,n){if(n){for(var s=arguments.length,i=new Array(s-1);--s;)i[s-1]=arguments[s];return r[t].subscribe.apply(null,i),e}if("string"==typeof t)return r[t]};s.addEventType=a;for(var i=1,o=arguments.length;iSt(r(),t()):t,e.justLimit=n&&!r}function Ft(e,t){if(e.isPrimKey)return t.primaryKey;const n=t.getIndexByKeyPath(e.index);if(!n)throw new X.Schema("KeyPath "+e.index+" on object store "+t.name+" is not indexed");return n}function Mt(e,t,n){const r=Ft(e,t.schema);return t.openCursor({trans:n,values:!e.keysOnly,reverse:"prev"===e.dir,unique:!!e.unique,query:{index:r,range:e.range}})}function Nt(e,t,n,r){const s=e.replayFilter?St(e.filter,e.replayFilter()):e.filter;if(e.or){const i={},a=(e,n,r)=>{if(!s||s(n,r,(e=>n.stop(e)),(e=>n.fail(e)))){var a=n.primaryKey,u=""+a;"[object ArrayBuffer]"===u&&(u=""+new Uint8Array(a)),o(i,u)||(i[u]=!0,t(e,n,r))}};return Promise.all([e.or._iterate(a,n),qt(Mt(e,r,n),e.algorithm,a,!e.keysOnly&&e.valueMapper)])}return qt(Mt(e,r,n),St(e.algorithm,s),t,!e.keysOnly&&e.valueMapper)}function qt(e,t,n,r){var s=Ye(r?(e,t,s)=>n(r(e),t,s):n);return e.then((e=>{if(e)return e.start((()=>{var n=()=>e.continue();t&&!t(e,(e=>n=e),(t=>{e.stop(t),n=ee}),(t=>{e.fail(t),n=ee}))||s(e.value,e,(e=>n=e)),n()}))}))}function $t(e,t){try{const n=Ut(e),r=Ut(t);if(n!==r)return"Array"===n?1:"Array"===r?-1:"binary"===n?1:"binary"===r?-1:"string"===n?1:"string"===r?-1:"Date"===n?1:"Date"!==r?NaN:-1;switch(n){case"number":case"Date":case"string":return e>t?1:eNt(t,e,n,t.table.core)))}count(e){return this._read((e=>{const t=this._ctx,n=t.table.core;if(Bt(t,!0))return n.count({trans:e,query:{index:Ft(t,n.schema),range:t.range}}).then((e=>Math.min(e,t.limit)));var r=0;return Nt(t,(()=>(++r,!1)),e,n).then((()=>r))})).then(e)}sortBy(e,t){const n=e.split(".").reverse(),r=n[0],s=n.length-1;function i(e,t){return t?i(e[n[t]],t-1):e[r]}var o="next"===this._ctx.dir?1:-1;function a(e,t){var n=i(e,s),r=i(t,s);return nr?o:0}return this.toArray((function(e){return e.sort(a)})).then(t)}toArray(e){return this._read((e=>{var t=this._ctx;if("next"===t.dir&&Bt(t,!0)&&t.limit>0){const{valueMapper:n}=t,r=Ft(t,t.table.core.schema);return t.table.core.query({trans:e,limit:t.limit,values:!0,query:{index:r,range:t.range}}).then((({result:e})=>n?e.map(n):e))}{const n=[];return Nt(t,(e=>n.push(e)),e,t.table.core).then((()=>n))}}),e)}offset(e){var t=this._ctx;return e<=0||(t.offset+=e,Bt(t)?Rt(t,(()=>{var t=e;return(e,n)=>0===t||(1===t?(--t,!1):(n((()=>{e.advance(t),t=0})),!1))})):Rt(t,(()=>{var t=e;return()=>--t<0}))),this}limit(e){return this._ctx.limit=Math.min(this._ctx.limit,e),Rt(this._ctx,(()=>{var t=e;return function(e,n,r){return--t<=0&&n(r),t>=0}}),!0),this}until(e,t){return Tt(this._ctx,(function(n,r,s){return!e(n.value)||(r(s),t)})),this}first(e){return this.limit(1).toArray((function(e){return e[0]})).then(e)}last(e){return this.reverse().first(e)}filter(e){var t,n;return Tt(this._ctx,(function(t){return e(t.value)})),t=this._ctx,n=e,t.isMatch=St(t.isMatch,n),this}and(e){return this.filter(e)}or(e){return new this.db.WhereClause(this._ctx.table,e,this)}reverse(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this}desc(){return this.reverse()}eachKey(e){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each((function(t,n){e(n.key,n)}))}eachUniqueKey(e){return this._ctx.unique="unique",this.eachKey(e)}eachPrimaryKey(e){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each((function(t,n){e(n.primaryKey,n)}))}keys(e){var t=this._ctx;t.keysOnly=!t.isMatch;var n=[];return this.each((function(e,t){n.push(t.key)})).then((function(){return n})).then(e)}primaryKeys(e){var t=this._ctx;if("next"===t.dir&&Bt(t,!0)&&t.limit>0)return this._read((e=>{var n=Ft(t,t.table.core.schema);return t.table.core.query({trans:e,values:!1,limit:t.limit,query:{index:n,range:t.range}})})).then((({result:e})=>e)).then(e);t.keysOnly=!t.isMatch;var n=[];return this.each((function(e,t){n.push(t.primaryKey)})).then((function(){return n})).then(e)}uniqueKeys(e){return this._ctx.unique="unique",this.keys(e)}firstKey(e){return this.limit(1).keys((function(e){return e[0]})).then(e)}lastKey(e){return this.reverse().firstKey(e)}distinct(){var e=this._ctx,t=e.index&&e.table.schema.idxByName[e.index];if(!t||!t.multi)return this;var n={};return Tt(this._ctx,(function(e){var t=e.primaryKey.toString(),r=o(n,t);return n[t]=!0,!r})),this}modify(e){var n=this._ctx;return this._write((r=>{var s;if("function"==typeof e)s=e;else{var i=t(e),o=i.length;s=function(t){for(var n=!1,r=0;r{const{failures:r,numFailures:s}=n;d+=e-s;for(let e of t(r))h.push(r[e])};return this.clone().primaryKeys().then((t=>{const i=o=>{const h=Math.min(c,t.length-o);return a.getMany({trans:r,keys:t.slice(o,o+h),cache:"immutable"}).then((d=>{const f=[],y=[],m=u?[]:null,v=[];for(let e=0;e0&&a.mutate({trans:r,type:"add",values:f}).then((e=>{for(let t in e.failures)v.splice(parseInt(t),1);p(f.length,e)}))).then((()=>(y.length>0||g&&"object"==typeof e)&&a.mutate({trans:r,type:"put",keys:m,values:y,criteria:g,changeSpec:"function"!=typeof e&&e}).then((e=>p(y.length,e))))).then((()=>(v.length>0||g&&e===Wt)&&a.mutate({trans:r,type:"delete",keys:v,criteria:g}).then((e=>p(v.length,e))))).then((()=>t.length>o+h&&i(o+c)))}))};return i(0).then((()=>{if(h.length>0)throw new z("Error modifying one or more objects",h,d,f);return t.length}))}))}))}delete(){var e=this._ctx,t=e.range;return Bt(e)&&(e.isPrimKey&&!kt||3===t.type)?this._write((n=>{const{primaryKey:r}=e.table.core.schema,s=t;return e.table.core.count({trans:n,query:{index:r,range:s}}).then((t=>e.table.core.mutate({trans:n,type:"deleteRange",range:s}).then((({failures:e,lastResult:n,results:r,numFailures:s})=>{if(s)throw new z("Could not delete some values",Object.keys(e).map((t=>e[t])),t-s);return t-s}))))})):this.modify(Wt)}}const Wt=(e,t)=>t.value=null;function Yt(e,t){return et?-1:e===t?0:1}function Gt(e,t,n){var r=e instanceof en?new e.Collection(e):e;return r._ctx.error=n?new n(t):new TypeError(t),r}function Ht(e){return new e.Collection(e,(()=>Zt(""))).limit(0)}function Qt(e,t,n,r,s,i){for(var o=Math.min(e.length,r.length),a=-1,u=0;u=0?e.substr(0,a)+t[a]+n.substr(a+1):null;s(e[u],l)<0&&(a=u)}return o"string"==typeof e)))return Gt(e,bt);function d(e){s=function(e){return"next"===e?e=>e.toUpperCase():e=>e.toLowerCase()}(e),i=function(e){return"next"===e?e=>e.toLowerCase():e=>e.toUpperCase()}(e),o="next"===e?Yt:zt;var t=n.map((function(e){return{lower:i(e),upper:s(e)}})).sort((function(e,t){return o(e.lower,t.lower)}));a=t.map((function(e){return e.upper})),u=t.map((function(e){return e.lower})),l=e,c="next"===e?"":r}d("next");var f=new e.Collection(e,(()=>Jt(a[0],u[h-1]+r)));f._ondirectionchange=function(e){d(e)};var p=0;return f._addAlgorithm((function(e,n,r){var s=e.key;if("string"!=typeof s)return!1;var d=i(s);if(t(d,u,p))return!0;for(var f=null,y=p;y0)&&(f=m)}return n(null!==f?function(){e.continue(f+c)}:r),!1})),f}function Jt(e,t,n,r){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:r}}function Zt(e){return{type:1,lower:e,upper:e}}class en{get Collection(){return this._ctx.table.db.Collection}between(e,t,n,r){n=!1!==n,r=!0===r;try{return this._cmp(e,t)>0||0===this._cmp(e,t)&&(n||r)&&(!n||!r)?Ht(this):new this.Collection(this,(()=>Jt(e,t,!n,!r)))}catch(e){return Gt(this,gt)}}equals(e){return null==e?Gt(this,gt):new this.Collection(this,(()=>Zt(e)))}above(e){return null==e?Gt(this,gt):new this.Collection(this,(()=>Jt(e,void 0,!0)))}aboveOrEqual(e){return null==e?Gt(this,gt):new this.Collection(this,(()=>Jt(e,void 0,!1)))}below(e){return null==e?Gt(this,gt):new this.Collection(this,(()=>Jt(void 0,e,!1,!0)))}belowOrEqual(e){return null==e?Gt(this,gt):new this.Collection(this,(()=>Jt(void 0,e)))}startsWith(e){return"string"!=typeof e?Gt(this,bt):this.between(e,e+mt,!0,!0)}startsWithIgnoreCase(e){return""===e?this.startsWith(e):Xt(this,((e,t)=>0===e.indexOf(t[0])),[e],mt)}equalsIgnoreCase(e){return Xt(this,((e,t)=>e===t[0]),[e],"")}anyOfIgnoreCase(){var e=B.apply(I,arguments);return 0===e.length?Ht(this):Xt(this,((e,t)=>-1!==t.indexOf(e)),e,"")}startsWithAnyOfIgnoreCase(){var e=B.apply(I,arguments);return 0===e.length?Ht(this):Xt(this,((e,t)=>t.some((t=>0===e.indexOf(t)))),e,mt)}anyOf(){const e=B.apply(I,arguments);let t=this._cmp;try{e.sort(t)}catch(e){return Gt(this,gt)}if(0===e.length)return Ht(this);const n=new this.Collection(this,(()=>Jt(e[0],e[e.length-1])));n._ondirectionchange=n=>{t="next"===n?this._ascending:this._descending,e.sort(t)};let r=0;return n._addAlgorithm(((n,s,i)=>{const o=n.key;for(;t(o,e[r])>0;)if(++r,r===e.length)return s(i),!1;return 0===t(o,e[r])||(s((()=>{n.continue(e[r])})),!1)})),n}notEqual(e){return this.inAnyRange([[vt,e],[e,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})}noneOf(){const e=B.apply(I,arguments);if(0===e.length)return new this.Collection(this);try{e.sort(this._ascending)}catch(e){return Gt(this,gt)}const t=e.reduce(((e,t)=>e?e.concat([[e[e.length-1][1],t]]):[[vt,t]]),null);return t.push([e[e.length-1],this.db._maxKey]),this.inAnyRange(t,{includeLowers:!1,includeUppers:!1})}inAnyRange(e,t){const n=this._cmp,r=this._ascending,s=this._descending,i=this._min,o=this._max;if(0===e.length)return Ht(this);if(!e.every((e=>void 0!==e[0]&&void 0!==e[1]&&r(e[0],e[1])<=0)))return Gt(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",X.InvalidArgument);const a=!t||!1!==t.includeLowers,u=t&&!0===t.includeUppers;let l,c=r;function h(e,t){return c(e[0],t[0])}try{l=e.reduce((function(e,t){let r=0,s=e.length;for(;r0){s[0]=i(s[0],t[0]),s[1]=o(s[1],t[1]);break}}return r===s&&e.push(t),e}),[]),l.sort(h)}catch(e){return Gt(this,gt)}let d=0;const f=u?e=>r(e,l[d][1])>0:e=>r(e,l[d][1])>=0,p=a?e=>s(e,l[d][0])>0:e=>s(e,l[d][0])>=0;let y=f;const m=new this.Collection(this,(()=>Jt(l[0][0],l[l.length-1][1],!a,!u)));return m._ondirectionchange=e=>{"next"===e?(y=f,c=r):(y=p,c=s),l.sort(h)},m._addAlgorithm(((e,t,n)=>{for(var s=e.key;y(s);)if(++d,d===l.length)return t(n),!1;return!!function(e){return!f(e)&&!p(e)}(s)||(0===this._cmp(s,l[d][1])||0===this._cmp(s,l[d][0])||t((()=>{c===r?e.continue(l[d][0]):e.continue(l[d][1])})),!1)})),m}startsWithAnyOf(){const e=B.apply(I,arguments);return e.every((e=>"string"==typeof e))?0===e.length?Ht(this):this.inAnyRange(e.map((e=>[e,e+mt]))):Gt(this,"startsWithAnyOf() only works with strings")}}function tn(e){return Ye((function(t){return nn(t),e(t.target.error),!1}))}function nn(e){e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}const rn="storagemutated",sn="x-storagemutated-1",on=Dt(null,rn);class an{_lock(){return m(!Oe.global),++this._reculock,1!==this._reculock||Oe.global||(Oe.lockOwnerFor=this),this}_unlock(){if(m(!Oe.global),0==--this._reculock)for(Oe.global||(Oe.lockOwnerFor=null);this._blockedFuncs.length>0&&!this._locked();){var e=this._blockedFuncs.shift();try{at(e[1],e[0])}catch(e){}}return this}_locked(){return this._reculock&&Oe.lockOwnerFor!==this}create(e){if(!this.mode)return this;const t=this.db.idbdb,n=this.db._state.dbOpenError;if(m(!this.idbtrans),!e&&!t)switch(n&&n.name){case"DatabaseClosedError":throw new X.DatabaseClosed(n);case"MissingAPIError":throw new X.MissingAPI(n.message,n);default:throw new X.OpenFailed(n)}if(!this.active)throw new X.TransactionInactive;return m(null===this._completion._state),(e=this.idbtrans=e||(this.db.core?this.db.core.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}):t.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}))).onerror=Ye((t=>{nn(t),this._reject(e.error)})),e.onabort=Ye((t=>{nn(t),this.active&&this._reject(new X.Abort(e.error)),this.active=!1,this.on("abort").fire(t)})),e.oncomplete=Ye((()=>{this.active=!1,this._resolve(),"mutatedParts"in e&&on.storagemutated.fire(e.mutatedParts)})),this}_promise(e,t,n){if("readwrite"===e&&"readwrite"!==this.mode)return ft(new X.ReadOnly("Transaction is readonly"));if(!this.active)return ft(new X.TransactionInactive);if(this._locked())return new je(((r,s)=>{this._blockedFuncs.push([()=>{this._promise(e,t,n).then(r,s)},Oe])}));if(n)return Ze((()=>{var e=new je(((e,n)=>{this._lock();const r=t(e,n,this);r&&r.then&&r.then(e,n)}));return e.finally((()=>this._unlock())),e._lib=!0,e}));var r=new je(((e,n)=>{var r=t(e,n,this);r&&r.then&&r.then(e,n)}));return r._lib=!0,r}_root(){return this.parent?this.parent._root():this}waitFor(e){var t=this._root();const n=je.resolve(e);if(t._waitingFor)t._waitingFor=t._waitingFor.then((()=>n));else{t._waitingFor=n,t._waitingQueue=[];var r=t.idbtrans.objectStore(t.storeNames[0]);!function e(){for(++t._spinCount;t._waitingQueue.length;)t._waitingQueue.shift()();t._waitingFor&&(r.get(-1/0).onsuccess=e)}()}var s=t._waitingFor;return new je(((e,r)=>{n.then((n=>t._waitingQueue.push(Ye(e.bind(null,n)))),(e=>t._waitingQueue.push(Ye(r.bind(null,e))))).finally((()=>{t._waitingFor===s&&(t._waitingFor=null)}))}))}abort(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new X.Abort))}table(e){const t=this._memoizedTables||(this._memoizedTables={});if(o(t,e))return t[e];const n=this.schema[e];if(!n)throw new X.NotFound("Table "+e+" not part of transaction");const r=new this.db.Table(e,n,this);return r.core=this.db.core.table(e),t[e]=r,r}}function un(e,t,n,r,s,i,o){return{name:e,keyPath:t,unique:n,multi:r,auto:s,compound:i,src:(n&&!o?"&":"")+(r?"*":"")+(s?"++":"")+ln(t)}}function ln(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}function cn(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:g(n,(e=>[e.name,e]))}}let hn=e=>{try{return e.only([[]]),hn=()=>[[]],[[]]}catch(e){return hn=()=>mt,mt}};function dn(e){return null==e?()=>{}:"string"==typeof e?function(e){const t=e.split(".");return 1===t.length?t=>t[e]:t=>b(t,e)}(e):t=>b(t,e)}function fn(e){return[].slice.call(e)}let pn=0;function yn(e){return null==e?":id":"string"==typeof e?e:`[${e.join("+")}]`}function mn(e,t,r){function s(e){if(3===e.type)return null;if(4===e.type)throw new Error("Cannot convert never type to IDBKeyRange");const{lower:n,upper:r,lowerOpen:s,upperOpen:i}=e;return void 0===n?void 0===r?null:t.upperBound(r,!!i):void 0===r?t.lowerBound(n,!!s):t.bound(n,r,!!s,!!i)}const{schema:i,hasGetAll:o}=function(e,t){const r=fn(e.objectStoreNames);return{schema:{name:e.name,tables:r.map((e=>t.objectStore(e))).map((e=>{const{keyPath:t,autoIncrement:r}=e,s=n(t),i=null==t,o={},a={name:e.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:i,compound:s,keyPath:t,autoIncrement:r,unique:!0,extractKey:dn(t)},indexes:fn(e.indexNames).map((t=>e.index(t))).map((e=>{const{name:t,unique:r,multiEntry:s,keyPath:i}=e,a={name:t,compound:n(i),keyPath:i,unique:r,multiEntry:s,extractKey:dn(i)};return o[yn(i)]=a,a})),getIndexByKeyPath:e=>o[yn(e)]};return o[":id"]=a.primaryKey,null!=t&&(o[yn(t)]=a.primaryKey),a}))},hasGetAll:r.length>0&&"getAll"in t.objectStore(r[0])&&!("undefined"!=typeof navigator&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(e,r),a=i.tables.map((e=>function(e){const t=e.name;return{name:t,schema:e,mutate:function({trans:e,type:n,keys:r,values:i,range:o}){return new Promise(((a,u)=>{a=Ye(a);const l=e.objectStore(t),c=null==l.keyPath,h="put"===n||"add"===n;if(!h&&"delete"!==n&&"deleteRange"!==n)throw new Error("Invalid operation type: "+n);const{length:d}=r||i||{length:1};if(r&&i&&r.length!==i.length)throw new Error("Given keys array must have same length as given values array.");if(0===d)return a({numFailures:0,failures:{},results:[],lastResult:void 0});let f;const p=[],y=[];let m=0;const v=e=>{++m,nn(e)};if("deleteRange"===n){if(4===o.type)return a({numFailures:m,failures:y,results:[],lastResult:void 0});3===o.type?p.push(f=l.clear()):p.push(f=l.delete(s(o)))}else{const[e,t]=h?c?[i,r]:[i,null]:[r,null];if(h)for(let r=0;r{const t=e.target.result;p.forEach(((e,t)=>null!=e.error&&(y[t]=e.error))),a({numFailures:m,failures:y,results:"delete"===n?r:p.map((e=>e.result)),lastResult:t})};f.onerror=e=>{v(e),g(e)},f.onsuccess=g}))},getMany:({trans:e,keys:n})=>new Promise(((r,s)=>{r=Ye(r);const i=e.objectStore(t),o=n.length,a=new Array(o);let u,l=0,c=0;const h=e=>{const t=e.target;a[t._pos]=t.result,++c===l&&r(a)},d=tn(s);for(let e=0;enew Promise(((r,s)=>{r=Ye(r);const i=e.objectStore(t).get(n);i.onsuccess=e=>r(e.target.result),i.onerror=tn(s)})),query:function(e){return n=>new Promise(((r,i)=>{r=Ye(r);const{trans:o,values:a,limit:u,query:l}=n,c=u===1/0?void 0:u,{index:h,range:d}=l,f=o.objectStore(t),p=h.isPrimaryKey?f:f.index(h.name),y=s(d);if(0===u)return r({result:[]});if(e){const e=a?p.getAll(y,c):p.getAllKeys(y,c);e.onsuccess=e=>r({result:e.target.result}),e.onerror=tn(i)}else{let e=0;const t=a||!("openKeyCursor"in p)?p.openCursor(y):p.openKeyCursor(y),n=[];t.onsuccess=s=>{const i=t.result;return i?(n.push(a?i.value:i.primaryKey),++e===u?r({result:n}):void i.continue()):r({result:n})},t.onerror=tn(i)}}))}(o),openCursor:function({trans:e,values:n,query:r,reverse:i,unique:o}){return new Promise(((a,u)=>{a=Ye(a);const{index:l,range:c}=r,h=e.objectStore(t),d=l.isPrimaryKey?h:h.index(l.name),f=i?o?"prevunique":"prev":o?"nextunique":"next",p=n||!("openKeyCursor"in d)?d.openCursor(s(c),f):d.openKeyCursor(s(c),f);p.onerror=tn(u),p.onsuccess=Ye((t=>{const n=p.result;if(!n)return void a(null);n.___id=++pn,n.done=!1;const r=n.continue.bind(n);let s=n.continuePrimaryKey;s&&(s=s.bind(n));const i=n.advance.bind(n),o=()=>{throw new Error("Cursor not stopped")};n.trans=e,n.stop=n.continue=n.continuePrimaryKey=n.advance=()=>{throw new Error("Cursor not started")},n.fail=Ye(u),n.next=function(){let e=1;return this.start((()=>e--?this.continue():this.stop())).then((()=>this))},n.start=e=>{const t=new Promise(((e,t)=>{e=Ye(e),p.onerror=tn(t),n.fail=t,n.stop=t=>{n.stop=n.continue=n.continuePrimaryKey=n.advance=o,e(t)}})),a=()=>{if(p.result)try{e()}catch(e){n.fail(e)}else n.done=!0,n.start=()=>{throw new Error("Cursor behind last entry")},n.stop()};return p.onsuccess=Ye((e=>{p.onsuccess=a,a()})),n.continue=r,n.continuePrimaryKey=s,n.advance=i,a(),t},a(n)}),u)}))},count({query:e,trans:n}){const{index:r,range:i}=e;return new Promise(((e,o)=>{const a=n.objectStore(t),u=r.isPrimaryKey?a:a.index(r.name),l=s(i),c=l?u.count(l):u.count();c.onsuccess=Ye((t=>e(t.target.result))),c.onerror=tn(o)}))}}}(e))),u={};return a.forEach((e=>u[e.name]=e)),{stack:"dbcore",transaction:e.transaction.bind(e),table(e){if(!u[e])throw new Error(`Table '${e}' not found`);return u[e]},MIN_KEY:-1/0,MAX_KEY:hn(t),schema:i}}function vn({_novip:e},t){const n=t.db,r=function(e,t,{IDBKeyRange:n,indexedDB:r},s){const i=function(e,t){return t.reduce(((e,{create:t})=>({...e,...t(e)})),e)}(mn(t,n,s),e.dbcore);return{dbcore:i}}(e._middlewares,n,e._deps,t);e.core=r.dbcore,e.tables.forEach((t=>{const n=t.name;e.core.schema.tables.some((e=>e.name===n))&&(t.core=e.core.table(n),e[n]instanceof e.Table&&(e[n].core=t.core))}))}function gn({_novip:e},t,n,r){n.forEach((n=>{const s=r[n];t.forEach((t=>{const r=d(t,n);(!r||"value"in r&&void 0===r.value)&&(t===e.Transaction.prototype||t instanceof e.Transaction?l(t,n,{get(){return this.table(n)},set(e){u(this,n,{value:e,writable:!0,configurable:!0,enumerable:!0})}}):t[n]=new e.Table(n,s))}))}))}function bn({_novip:e},t){t.forEach((t=>{for(let n in t)t[n]instanceof e.Table&&delete t[n]}))}function _n(e,t){return e._cfg.version-t._cfg.version}function wn(e,n,r,s){const i=e._dbSchema,o=e._createTransaction("readwrite",e._storeNames,i);o.create(r),o._completion.catch(s);const a=o._reject.bind(o),u=Oe.transless||Oe;Ze((()=>{Oe.trans=o,Oe.transless=u,0===n?(t(i).forEach((e=>{kn(r,e,i[e].primKey,i[e].indexes)})),vn(e,r),je.follow((()=>e.on.populate.fire(o))).catch(a)):function({_novip:e},n,r,s){const i=[],o=e._versions;let a=e._dbSchema=Pn(e,e.idbdb,s),u=!1;const l=o.filter((e=>e._cfg.version>=n));function c(){return i.length?je.resolve(i.shift()(r.idbtrans)).then(c):je.resolve()}return l.forEach((o=>{i.push((()=>{const i=a,l=o._cfg.dbschema;Kn(e,i,s),Kn(e,l,s),a=e._dbSchema=l;const c=xn(i,l);c.add.forEach((e=>{kn(s,e[0],e[1].primKey,e[1].indexes)})),c.change.forEach((e=>{if(e.recreate)throw new X.Upgrade("Not yet support for changing primary key");{const t=s.objectStore(e.name);e.add.forEach((e=>En(t,e))),e.change.forEach((e=>{t.deleteIndex(e.name),En(t,e)})),e.del.forEach((e=>t.deleteIndex(e)))}}));const h=o._cfg.contentUpgrade;if(h&&o._cfg.version>n){vn(e,s),r._memoizedTables={},u=!0;let n=w(l);c.del.forEach((e=>{n[e]=i[e]})),bn(e,[e.Transaction.prototype]),gn(e,[e.Transaction.prototype],t(n),n),r.schema=n;const o=T(h);let a;o&&et();const d=je.follow((()=>{if(a=h(r),a&&o){var e=tt.bind(null,null);a.then(e,e)}}));return a&&"function"==typeof a.then?je.resolve(a):d.then((()=>a))}})),i.push((t=>{if(!u||!xt){!function(e,t){[].slice.call(t.db.objectStoreNames).forEach((n=>null==e[n]&&t.db.deleteObjectStore(n)))}(o._cfg.dbschema,t)}bn(e,[e.Transaction.prototype]),gn(e,[e.Transaction.prototype],e._storeNames,e._dbSchema),r.schema=e._dbSchema}))})),c().then((()=>{var e,n;n=s,t(e=a).forEach((t=>{n.db.objectStoreNames.contains(t)||kn(n,t,e[t].primKey,e[t].indexes)}))}))}(e,n,o,r).catch(a)}))}function xn(e,t){const n={del:[],add:[],change:[]};let r;for(r in e)t[r]||n.del.push(r);for(r in t){const s=e[r],i=t[r];if(s){const e={name:r,def:i,recreate:!1,del:[],add:[],change:[]};if(""+(s.primKey.keyPath||"")!=""+(i.primKey.keyPath||"")||s.primKey.auto!==i.primKey.auto&&!wt)e.recreate=!0,n.change.push(e);else{const t=s.idxByName,r=i.idxByName;let o;for(o in t)r[o]||e.del.push(o);for(o in r){const n=t[o],s=r[o];n?n.src!==s.src&&e.change.push(s):e.add.push(s)}(e.del.length>0||e.add.length>0||e.change.length>0)&&n.change.push(e)}}else n.add.push([r,i])}return n}function kn(e,t,n,r){const s=e.db.createObjectStore(t,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return r.forEach((e=>En(s,e))),s}function En(e,t){e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multi})}function Pn(e,t,n){const r={};return p(t.objectStoreNames,0).forEach((e=>{const t=n.objectStore(e);let s=t.keyPath;const i=un(ln(s),s||"",!1,!1,!!t.autoIncrement,s&&"string"!=typeof s,!0),o=[];for(let e=0;e{if(null!==e[t]){var s=e[t].split(",").map(((e,t)=>{const r=(e=e.trim()).replace(/([&*]|\+\+)/g,""),s=/^\[/.test(r)?r.match(/^\[(.*)\]$/)[1].split("+"):r;return un(r,s||null,/\&/.test(e),/\*/.test(e),/\+\+/.test(e),n(s),0===t)})),i=s.shift();if(i.multi)throw new X.Schema("Primary key cannot be multi-valued");s.forEach((e=>{if(e.auto)throw new X.Schema("Only primary key can be marked as autoIncrement (++)");if(!e.keyPath)throw new X.Schema("Index must have a name and cannot be an empty string")})),r[t]=cn(t,i,s)}}))}stores(e){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?r(this._cfg.storesSource,e):e;const s=n._versions,i={};let o={};return s.forEach((e=>{r(i,e._cfg.storesSource),o=e._cfg.dbschema={},e._parseStoresSpec(i,o)})),n._dbSchema=o,bn(n,[n._allTables,n,n.Transaction.prototype]),gn(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],t(o),o),n._storeNames=t(o),this}upgrade(e){return this._cfg.contentUpgrade=ue(this._cfg.contentUpgrade||ee,e),this}}function Sn(e,t){let n=e._dbNamesDB;return n||(n=e._dbNamesDB=new Xn(Pt,{addons:[],indexedDB:e,IDBKeyRange:t}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function An(e){return e&&"function"==typeof e.databases}function Cn(e){return Ze((function(){return Oe.letThrough=!0,e()}))}function jn(){var e;return!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise((function(t){var n=function(){return indexedDB.databases().finally(t)};e=setInterval(n,100),n()})).finally((function(){return clearInterval(e)})):Promise.resolve()}function Dn(e){const n=e._state,{indexedDB:r}=e._deps;if(n.isBeingOpened||e.idbdb)return n.dbReadyPromise.then((()=>n.dbOpenError?ft(n.dbOpenError):e));R&&(n.openCanceller._stackHolder=q()),n.isBeingOpened=!0,n.dbOpenError=null,n.openComplete=!1;const s=n.openCanceller;function i(){if(n.openCanceller!==s)throw new X.DatabaseClosed("db.open() was cancelled")}let o=n.dbReadyResolve,a=null,u=!1;const l=()=>new je(((s,o)=>{if(i(),!r)throw new X.MissingAPI;const l=e.name,c=n.autoSchema?r.open(l):r.open(l,Math.round(10*e.verno));if(!c)throw new X.MissingAPI;c.onerror=tn(o),c.onblocked=Ye(e._fireOnBlocked),c.onupgradeneeded=Ye((t=>{if(a=c.transaction,n.autoSchema&&!e._options.allowEmptyDB){c.onerror=nn,a.abort(),c.result.close();const e=r.deleteDatabase(l);e.onsuccess=e.onerror=Ye((()=>{o(new X.NoSuchDatabase(`Database ${l} doesnt exist`))}))}else{a.onerror=tn(o);var s=t.oldVersion>Math.pow(2,62)?0:t.oldVersion;u=s<1,e._novip.idbdb=c.result,wn(e,s/10,a,o)}}),o),c.onsuccess=Ye((()=>{a=null;const r=e._novip.idbdb=c.result,i=p(r.objectStoreNames);if(i.length>0)try{const s=r.transaction(1===(o=i).length?o[0]:o,"readonly");n.autoSchema?function({_novip:e},n,r){e.verno=n.version/10;const s=e._dbSchema=Pn(0,n,r);e._storeNames=p(n.objectStoreNames,0),gn(e,[e._allTables],t(s),s)}(e,r,s):(Kn(e,e._dbSchema,s),function(e,t){const n=xn(Pn(0,e.idbdb,t),e._dbSchema);return!(n.add.length||n.change.some((e=>e.add.length||e.change.length)))}(e,s)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),vn(e,s)}catch(e){}var o;_t.push(e),r.onversionchange=Ye((t=>{n.vcFired=!0,e.on("versionchange").fire(t)})),r.onclose=Ye((t=>{e.on("close").fire(t)})),u&&function({indexedDB:e,IDBKeyRange:t},n){!An(e)&&n!==Pt&&Sn(e,t).put({name:n}).catch(ee)}(e._deps,l),s()}),o)})).catch((e=>e&&"UnknownError"===e.name&&n.PR1398_maxLoop>0?(n.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),l()):je.reject(e)));return je.race([s,("undefined"==typeof navigator?je.resolve():jn()).then(l)]).then((()=>(i(),n.onReadyBeingFired=[],je.resolve(Cn((()=>e.on.ready.fire(e.vip)))).then((function t(){if(n.onReadyBeingFired.length>0){let r=n.onReadyBeingFired.reduce(ue,ee);return n.onReadyBeingFired=[],je.resolve(Cn((()=>r(e.vip)))).then(t)}}))))).finally((()=>{n.onReadyBeingFired=null,n.isBeingOpened=!1})).then((()=>e)).catch((t=>{n.dbOpenError=t;try{a&&a.abort()}catch(e){}return s===n.openCanceller&&e._close(),ft(t)})).finally((()=>{n.openComplete=!0,o()}))}function In(e){var t=t=>e.next(t),r=i(t),s=i((t=>e.throw(t)));function i(e){return t=>{var i=e(t),o=i.value;return i.done?o:o&&"function"==typeof o.then?o.then(r,s):n(o)?Promise.all(o).then(r,s):r(o)}}return i(t)()}function Bn(e,t,n){var r=arguments.length;if(r<2)throw new X.InvalidArgument("Too few arguments");for(var s=new Array(r-1);--r;)s[r-1]=arguments[r];return n=s.pop(),[e,k(s),n]}function Tn(e,t,n,r,s){return je.resolve().then((()=>{const i=Oe.transless||Oe,o=e._createTransaction(t,n,e._dbSchema,r),a={trans:o,transless:i};if(r)o.idbtrans=r.idbtrans;else try{o.create(),e._state.PR1398_maxLoop=3}catch(r){return r.name===H.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then((()=>Tn(e,t,n,null,s)))):ft(r)}const u=T(s);let l;u&&et();const c=je.follow((()=>{if(l=s.call(o,o),l)if(u){var e=tt.bind(null,null);l.then(e,e)}else"function"==typeof l.next&&"function"==typeof l.throw&&(l=In(l))}),a);return(l&&"function"==typeof l.then?je.resolve(l).then((e=>o.active?e:ft(new X.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")))):c.then((()=>l))).then((e=>(r&&o._resolve(),o._completion.then((()=>e))))).catch((e=>(o._reject(e),ft(e))))}))}function Rn(e,t,r){const s=n(e)?e.slice():[e];for(let e=0;e0,c={...n,isVirtual:l,keyTail:t,keyLength:u,extractKey:dn(e),unique:!l&&n.unique};if(a.push(c),c.isPrimaryKey||i.push(c),u>1){o(2===u?e[0]:e.slice(0,u-1),t+1,n)}return a.sort(((e,t)=>e.keyTail-t.keyTail)),c}const a=o(r.primaryKey.keyPath,0,r.primaryKey);s[":id"]=[a];for(const e of r.indexes)o(e.keyPath,0,e);function u(t){const n=t.query.index;return n.isVirtual?{...t,query:{index:n,range:(r=t.query.range,s=n.keyTail,{type:1===r.type?2:r.type,lower:Rn(r.lower,r.lowerOpen?e.MAX_KEY:e.MIN_KEY,s),lowerOpen:!0,upper:Rn(r.upper,r.upperOpen?e.MIN_KEY:e.MAX_KEY,s),upperOpen:!0})}}:t;var r,s}const l={...n,schema:{...r,primaryKey:a,indexes:i,getIndexByKeyPath:function(e){const t=s[yn(e)];return t&&t[0]}},count:e=>n.count(u(e)),query:e=>n.query(u(e)),openCursor(t){const{keyTail:r,isVirtual:s,keyLength:i}=t.query.index;if(!s)return n.openCursor(t);return n.openCursor(u(t)).then((n=>n&&function(n){const s=Object.create(n,{continue:{value:function(s){null!=s?n.continue(Rn(s,t.reverse?e.MAX_KEY:e.MIN_KEY,r)):t.unique?n.continue(n.key.slice(0,i).concat(t.reverse?e.MIN_KEY:e.MAX_KEY,r)):n.continue()}},continuePrimaryKey:{value(t,s){n.continuePrimaryKey(Rn(t,e.MAX_KEY,r),s)}},primaryKey:{get:()=>n.primaryKey},key:{get(){const e=n.key;return 1===i?e[0]:e.slice(0,i)}},value:{get:()=>n.value}});return s}(n)))}};return l}}}};function Mn(e,n,r,s){return r=r||{},s=s||"",t(e).forEach((t=>{if(o(n,t)){var i=e[t],a=n[t];if("object"==typeof i&&"object"==typeof a&&i&&a){const e=C(i);e!==C(a)?r[s+t]=n[t]:"Object"===e?Mn(i,a,r,s+t+"."):i!==a&&(r[s+t]=n[t])}else i!==a&&(r[s+t]=n[t])}else r[s+t]=void 0})),t(n).forEach((t=>{o(e,t)||(r[s+t]=n[t])})),r}const Nn={stack:"dbcore",name:"HooksMiddleware",level:2,create:e=>({...e,table(t){const n=e.table(t),{primaryKey:r}=n.schema,s={...n,mutate(e){const s=Oe.trans,{deleting:i,creating:a,updating:u}=s.table(t).hook;switch(e.type){case"add":if(a.fire===ee)break;return s._promise("readwrite",(()=>l(e)),!0);case"put":if(a.fire===ee&&u.fire===ee)break;return s._promise("readwrite",(()=>l(e)),!0);case"delete":if(i.fire===ee)break;return s._promise("readwrite",(()=>l(e)),!0);case"deleteRange":if(i.fire===ee)break;return s._promise("readwrite",(()=>function(e){return c(e.trans,e.range,1e4)}(e)),!0)}return n.mutate(e);function l(e){const t=Oe.trans,s=e.keys||function(e,t){return"delete"===t.type?t.keys:t.keys||t.values.map(e.extractKey)}(r,e);if(!s)throw new Error("Keys missing");return"delete"!==(e="add"===e.type||"put"===e.type?{...e,keys:s}:{...e}).type&&(e.values=[...e.values]),e.keys&&(e.keys=[...e.keys]),function(e,t,n){return"add"===t.type?Promise.resolve([]):e.getMany({trans:t.trans,keys:n,cache:"immutable"})}(n,e,s).then((l=>{const c=s.map(((n,s)=>{const c=l[s],h={onerror:null,onsuccess:null};if("delete"===e.type)i.fire.call(h,n,c,t);else if("add"===e.type||void 0===c){const i=a.fire.call(h,n,e.values[s],t);null==n&&null!=i&&(n=i,e.keys[s]=n,r.outbound||_(e.values[s],r.keyPath,n))}else{const r=Mn(c,e.values[s]),i=u.fire.call(h,r,n,c,t);if(i){const t=e.values[s];Object.keys(i).forEach((e=>{o(t,e)?t[e]=i[e]:_(t,e,i[e])}))}}return h}));return n.mutate(e).then((({failures:t,results:n,numFailures:r,lastResult:i})=>{for(let r=0;r(c.forEach((t=>t.onerror&&t.onerror(e))),Promise.reject(e))))}))}function c(e,t,s){return n.query({trans:e,values:!1,query:{index:r,range:t},limit:s}).then((({result:n})=>l({type:"delete",keys:n,trans:e}).then((r=>r.numFailures>0?Promise.reject(r.failures[0]):n.length({table:t=>{const n=e.table(t);return{...n,getMany:e=>{if(!e.cache)return n.getMany(e);const t=qn(e.keys,e.trans._cache,"clone"===e.cache);return t?je.resolve(t):n.getMany(e).then((t=>(e.trans._cache={keys:e.keys,values:"clone"===e.cache?O(t):t},t)))},mutate:e=>("add"!==e.type&&(e.trans._cache=null),n.mutate(e))}}})};function Un(e){return!("from"in e)}const Ln=function(e,t){if(!this){const t=new Ln;return e&&"d"in e&&r(t,e),t}r(this,arguments.length?{d:1,from:e,to:arguments.length>1?t:e}:{d:0})};function Vn(e,t,n){const s=$t(t,n);if(isNaN(s))return;if(s>0)throw RangeError();if(Un(e))return r(e,{from:t,to:n,d:1});const i=e.l,o=e.r;if($t(n,e.from)<0)return i?Vn(i,t,n):e.l={from:t,to:n,d:1,l:null,r:null},Gn(e);if($t(t,e.to)>0)return o?Vn(o,t,n):e.r={from:t,to:n,d:1,l:null,r:null},Gn(e);$t(t,e.from)<0&&(e.from=t,e.l=null,e.d=o?o.d+1:1),$t(n,e.to)>0&&(e.to=n,e.r=null,e.d=e.l?e.l.d+1:1);const a=!e.r;i&&!e.l&&Wn(e,i),o&&a&&Wn(e,o)}function Wn(e,t){Un(t)||function e(t,{from:n,to:r,l:s,r:i}){Vn(t,n,r),s&&e(t,s),i&&e(t,i)}(e,t)}function Yn(e,t){const n=zn(t);let r=n.next();if(r.done)return!1;let s=r.value;const i=zn(e);let o=i.next(s.from),a=o.value;for(;!r.done&&!o.done;){if($t(a.from,s.to)<=0&&$t(a.to,s.from)>=0)return!0;$t(s.from,a.from)<0?s=(r=n.next(a.from)).value:a=(o=i.next(s.from)).value}return!1}function zn(e){let t=Un(e)?null:{s:0,n:e};return{next(e){const n=arguments.length>0;for(;t;)switch(t.s){case 0:if(t.s=1,n)for(;t.n.l&&$t(e,t.n.from)<0;)t={up:t,n:t.n.l,s:1};else for(;t.n.l;)t={up:t,n:t.n.l,s:1};case 1:if(t.s=2,!n||$t(e,t.n.to)<=0)return{value:t.n,done:!1};case 2:if(t.n.r){t.s=3,t={up:t,n:t.n.r,s:0};continue}case 3:t=t.up}return{done:!0}}}}function Gn(e){var t,n;const r=((null===(t=e.r)||void 0===t?void 0:t.d)||0)-((null===(n=e.l)||void 0===n?void 0:n.d)||0),s=r>1?"r":r<-1?"l":"";if(s){const t="r"===s?"l":"r",n={...e},r=e[s];e.from=r.from,e.to=r.to,e[s]=r[s],n[s]=r[t],e[t]=n,n.d=Hn(n)}e.d=Hn(e)}function Hn({r:e,l:t}){return(e?t?Math.max(e.d,t.d):e.d:t?t.d:0)+1}a(Ln.prototype,{add(e){return Wn(this,e),this},addKey(e){return Vn(this,e,e),this},addKeys(e){return e.forEach((e=>Vn(this,e,e))),this},[j](){return zn(this)}});const Qn={stack:"dbcore",level:0,create:e=>{const r=e.schema.name,s=new Ln(e.MIN_KEY,e.MAX_KEY);return{...e,table:i=>{const o=e.table(i),{schema:a}=o,{primaryKey:u}=a,{extractKey:l,outbound:c}=u,h={...o,mutate:e=>{const t=e.trans,u=t.mutatedParts||(t.mutatedParts={}),l=e=>{const t=`idb://${r}/${i}/${e}`;return u[t]||(u[t]=new Ln)},c=l(""),h=l(":dels"),{type:d}=e;let[f,p]="deleteRange"===e.type?[e.range]:"delete"===e.type?[e.keys]:e.values.length<50?[[],e.values]:[];const y=e.trans._cache;return o.mutate(e).then((e=>{if(n(f)){"delete"!==d&&(f=e.results),c.addKeys(f);const t=qn(f,y);t||"add"===d||h.addKeys(f),(t||p)&&function(e,t,r,s){function i(t){const i=e(t.name||"");function o(e){return null!=e?t.extractKey(e):null}const a=e=>t.multiEntry&&n(e)?e.forEach((e=>i.addKey(e))):i.addKey(e);(r||s).forEach(((e,t)=>{const n=r&&o(r[t]),i=s&&o(s[t]);0!==$t(n,i)&&(null!=n&&a(n),null!=i&&a(i))}))}t.indexes.forEach(i)}(l,a,t,p)}else if(f){const e={from:f.lower,to:f.upper};h.add(e),c.add(e)}else c.add(s),h.add(s),a.indexes.forEach((e=>l(e.name).add(s)));return e}))}},d=({query:{index:t,range:n}})=>{var r,s;return[t,new Ln(null!==(r=n.lower)&&void 0!==r?r:e.MIN_KEY,null!==(s=n.upper)&&void 0!==s?s:e.MAX_KEY)]},f={get:e=>[u,new Ln(e.key)],getMany:e=>[u,(new Ln).addKeys(e.keys)],count:d,query:d,openCursor:d};return t(f).forEach((e=>{h[e]=function(t){const{subscr:n}=Oe;if(n){const a=e=>{const t=`idb://${r}/${i}/${e}`;return n[t]||(n[t]=new Ln)},u=a(""),h=a(":dels"),[d,p]=f[e](t);if(a(d.name||"").add(p),!d.isPrimaryKey){if("count"!==e){const n="query"===e&&c&&t.values&&o.query({...t,values:!1});return o[e].apply(this,arguments).then((r=>{if("query"===e){if(c&&t.values)return n.then((({result:e})=>(u.addKeys(e),r)));const e=t.values?r.result.map(l):r.result;t.values?u.addKeys(e):h.addKeys(e)}else if("openCursor"===e){const e=r,n=t.values;return e&&Object.create(e,{key:{get:()=>(h.addKey(e.primaryKey),e.key)},primaryKey:{get(){const t=e.primaryKey;return h.addKey(t),t}},value:{get:()=>(n&&u.addKey(e.primaryKey),e.value)}})}return r}))}h.add(s)}}return o[e].apply(this,arguments)}})),h}}}};class Xn{constructor(e,t){this._middlewares={},this.verno=0;const n=Xn.dependencies;this._options=t={addons:Xn.addons,autoOpen:!0,indexedDB:n.indexedDB,IDBKeyRange:n.IDBKeyRange,...t},this._deps={indexedDB:t.indexedDB,IDBKeyRange:t.IDBKeyRange};const{addons:r}=t;this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;const s={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:ee,dbReadyPromise:null,cancelOpen:ee,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3};var i;s.dbReadyPromise=new je((e=>{s.dbReadyResolve=e})),s.openCanceller=new je(((e,t)=>{s.cancelOpen=t})),this._state=s,this.name=e,this.on=Dt(this,"populate","blocked","versionchange","close",{ready:[ue,ee]}),this.on.ready.subscribe=y(this.on.ready.subscribe,(e=>(t,n)=>{Xn.vip((()=>{const r=this._state;if(r.openComplete)r.dbOpenError||je.resolve().then(t),n&&e(t);else if(r.onReadyBeingFired)r.onReadyBeingFired.push(t),n&&e(t);else{e(t);const r=this;n||e((function e(){r.on.ready.unsubscribe(t),r.on.ready.unsubscribe(e)}))}}))})),this.Collection=(i=this,It(Vt.prototype,(function(e,t){this.db=i;let n=At,r=null;if(t)try{n=t()}catch(e){r=e}const s=e._ctx,o=s.table,a=o.hook.reading.fire;this._ctx={table:o,index:s.index,isPrimKey:!s.index||o.schema.primKey.keyPath&&s.index===o.schema.primKey.name,range:n,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:r,or:s.or,valueMapper:a!==te?a:null}}))),this.Table=function(e){return It(jt.prototype,(function(t,n,r){this.db=e,this._tx=r,this.name=t,this.schema=n,this.hook=e._allTables[t]?e._allTables[t].hook:Dt(null,{creating:[se,ee],reading:[ne,te],updating:[oe,ee],deleting:[ie,ee]})}))}(this),this.Transaction=function(e){return It(an.prototype,(function(t,n,r,s,i){this.db=e,this.mode=t,this.storeNames=n,this.schema=r,this.chromeTransactionDurability=s,this.idbtrans=null,this.on=Dt(this,"complete","error","abort"),this.parent=i||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new je(((e,t)=>{this._resolve=e,this._reject=t})),this._completion.then((()=>{this.active=!1,this.on.complete.fire()}),(e=>{var t=this.active;return this.active=!1,this.on.error.fire(e),this.parent?this.parent._reject(e):t&&this.idbtrans&&this.idbtrans.abort(),ft(e)}))}))}(this),this.Version=function(e){return It(On.prototype,(function(t){this.db=e,this._cfg={version:t,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}}))}(this),this.WhereClause=function(e){return It(en.prototype,(function(t,n,r){this.db=e,this._ctx={table:t,index:":id"===n?null:n,or:r};const s=e._deps.indexedDB;if(!s)throw new X.MissingAPI;this._cmp=this._ascending=s.cmp.bind(s),this._descending=(e,t)=>s.cmp(t,e),this._max=(e,t)=>s.cmp(e,t)>0?e:t,this._min=(e,t)=>s.cmp(e,t)<0?e:t,this._IDBKeyRange=e._deps.IDBKeyRange}))}(this),this.on("versionchange",(e=>{e.newVersion>0?console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`):console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`),this.close()})),this.on("blocked",(e=>{!e.newVersion||e.newVersionnew this.Transaction(e,t,n,this._options.chromeTransactionDurability,r),this._fireOnBlocked=e=>{this.on("blocked").fire(e),_t.filter((e=>e.name===this.name&&e!==this&&!e._state.vcFired)).map((t=>t.on("versionchange").fire(e)))},this.use(Fn),this.use(Nn),this.use(Qn),this.use($n),this.vip=Object.create(this,{_vip:{value:!0}}),r.forEach((e=>e(this)))}version(e){if(isNaN(e)||e<.1)throw new X.Type("Given version is not a positive number");if(e=Math.round(10*e)/10,this.idbdb||this._state.isBeingOpened)throw new X.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,e);const t=this._versions;var n=t.filter((t=>t._cfg.version===e))[0];return n||(n=new this.Version(e),t.push(n),t.sort(_n),n.stores({}),this._state.autoSchema=!1,n)}_whenReady(e){return this.idbdb&&(this._state.openComplete||Oe.letThrough||this._vip)?e():new je(((e,t)=>{if(this._state.openComplete)return t(new X.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void t(new X.DatabaseClosed);this.open().catch(ee)}this._state.dbReadyPromise.then(e,t)})).then(e)}use({stack:e,create:t,level:n,name:r}){r&&this.unuse({stack:e,name:r});const s=this._middlewares[e]||(this._middlewares[e]=[]);return s.push({stack:e,create:t,level:null==n?10:n,name:r}),s.sort(((e,t)=>e.level-t.level)),this}unuse({stack:e,name:t,create:n}){return e&&this._middlewares[e]&&(this._middlewares[e]=this._middlewares[e].filter((e=>n?e.create!==n:!!t&&e.name!==t))),this}open(){return Dn(this)}_close(){const e=this._state,t=_t.indexOf(this);if(t>=0&&_t.splice(t,1),this.idbdb){try{this.idbdb.close()}catch(e){}this._novip.idbdb=null}e.dbReadyPromise=new je((t=>{e.dbReadyResolve=t})),e.openCanceller=new je(((t,n)=>{e.cancelOpen=n}))}close(){this._close();const e=this._state;this._options.autoOpen=!1,e.dbOpenError=new X.DatabaseClosed,e.isBeingOpened&&e.cancelOpen(e.dbOpenError)}delete(){const e=arguments.length>0,t=this._state;return new je(((n,r)=>{const s=()=>{this.close();var e=this._deps.indexedDB.deleteDatabase(this.name);e.onsuccess=Ye((()=>{!function({indexedDB:e,IDBKeyRange:t},n){!An(e)&&n!==Pt&&Sn(e,t).delete(n).catch(ee)}(this._deps,this.name),n()})),e.onerror=tn(r),e.onblocked=this._fireOnBlocked};if(e)throw new X.InvalidArgument("Arguments not allowed in db.delete()");t.isBeingOpened?t.dbReadyPromise.then(s):s()}))}backendDB(){return this.idbdb}isOpen(){return null!==this.idbdb}hasBeenClosed(){const e=this._state.dbOpenError;return e&&"DatabaseClosed"===e.name}hasFailed(){return null!==this._state.dbOpenError}dynamicallyOpened(){return this._state.autoSchema}get tables(){return t(this._allTables).map((e=>this._allTables[e]))}transaction(){const e=Bn.apply(this,arguments);return this._transaction.apply(this,e)}_transaction(e,t,n){let r=Oe.trans;r&&r.db===this&&-1===e.indexOf("!")||(r=null);const s=-1!==e.indexOf("?");let i,o;e=e.replace("!","").replace("?","");try{if(o=t.map((e=>{var t=e instanceof this.Table?e.name:e;if("string"!=typeof t)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return t})),"r"==e||e===Kt)i=Kt;else{if("rw"!=e&&e!=Ot)throw new X.InvalidArgument("Invalid transaction mode: "+e);i=Ot}if(r){if(r.mode===Kt&&i===Ot){if(!s)throw new X.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");r=null}r&&o.forEach((e=>{if(r&&-1===r.storeNames.indexOf(e)){if(!s)throw new X.SubTransaction("Table "+e+" not included in parent transaction.");r=null}})),s&&r&&!r.active&&(r=null)}}catch(e){return r?r._promise(null,((t,n)=>{n(e)})):ft(e)}const a=Tn.bind(null,this,i,o,r,n);return r?r._promise(i,a,"lock"):Oe.trans?at(Oe.transless,(()=>this._whenReady(a))):this._whenReady(a)}table(e){if(!o(this._allTables,e))throw new X.InvalidTable(`Table ${e} does not exist`);return this._allTables[e]}}const Jn="undefined"!=typeof Symbol&&"observable"in Symbol?Symbol.observable:"@@observable";class Zn{constructor(e){this._subscribe=e}subscribe(e,t,n){return this._subscribe(e&&"function"!=typeof e?e:{next:e,error:t,complete:n})}[Jn](){return this}}function er(e,n){return t(n).forEach((t=>{Wn(e[t]||(e[t]=new Ln),n[t])})),e}function tr(e){let n,r=!1;const s=new Zn((s=>{const i=T(e);let o=!1,a={},u={};const l={get closed(){return o},unsubscribe:()=>{o=!0,on.storagemutated.unsubscribe(f)}};s.start&&s.start(l);let c=!1,h=!1;function d(){return t(u).some((e=>a[e]&&Yn(a[e],u[e])))}const f=e=>{er(a,e),d()&&p()},p=()=>{if(c||o)return;a={};const t={},y=function(t){i&&et();const n=()=>Ze(e,{subscr:t,trans:null}),r=Oe.trans?at(Oe.transless,n):n();return i&&r.then(tt,tt),r}(t);h||(on(rn,f),h=!0),c=!0,Promise.resolve(y).then((e=>{r=!0,n=e,c=!1,o||(d()?p():(a={},u=t,s.next&&s.next(e)))}),(e=>{c=!1,r=!1,s.error&&s.error(e),l.unsubscribe()}))};return p(),l}));return s.hasValue=()=>r,s.getValue=()=>n,s}let nr;try{nr={indexedDB:e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB,IDBKeyRange:e.IDBKeyRange||e.webkitIDBKeyRange}}catch(e){nr={indexedDB:null,IDBKeyRange:null}}const rr=Xn;function sr(e){let t=ir;try{ir=!0,on.storagemutated.fire(e)}finally{ir=t}}a(rr,{...Z,delete:e=>new rr(e,{addons:[]}).delete(),exists:e=>new rr(e,{addons:[]}).open().then((e=>(e.close(),!0))).catch("NoSuchDatabaseError",(()=>!1)),getDatabaseNames(e){try{return function({indexedDB:e,IDBKeyRange:t}){return An(e)?Promise.resolve(e.databases()).then((e=>e.map((e=>e.name)).filter((e=>e!==Pt)))):Sn(e,t).toCollection().primaryKeys()}(rr.dependencies).then(e)}catch(e){return ft(new X.MissingAPI)}},defineClass:()=>function(e){r(this,e)},ignoreTransaction:e=>Oe.trans?at(Oe.transless,e):e(),vip:Cn,async:function(e){return function(){try{var t=In(e.apply(this,arguments));return t&&"function"==typeof t.then?t:je.resolve(t)}catch(e){return ft(e)}}},spawn:function(e,t,n){try{var r=In(e.apply(n,t||[]));return r&&"function"==typeof r.then?r:je.resolve(r)}catch(e){return ft(e)}},currentTransaction:{get:()=>Oe.trans||null},waitFor:function(e,t){const n=je.resolve("function"==typeof e?rr.ignoreTransaction(e):e).timeout(t||6e4);return Oe.trans?Oe.trans.waitFor(n):n},Promise:je,debug:{get:()=>R,set:e=>{F(e,"dexie"===e?()=>!0:Et)}},derive:c,extend:r,props:a,override:y,Events:Dt,on:on,liveQuery:tr,extendObservabilitySet:er,getByKeyPath:b,setByKeyPath:_,delByKeyPath:function(e,t){"string"==typeof t?_(e,t,void 0):"length"in t&&[].map.call(t,(function(t){_(e,t,void 0)}))},shallowClone:w,deepClone:O,getObjectDiff:Mn,cmp:$t,asap:v,minKey:vt,addons:[],connections:_t,errnames:H,dependencies:nr,semVer:yt,version:yt.split(".").map((e=>parseInt(e))).reduce(((e,t,n)=>e+t/Math.pow(10,2*n)))}),rr.maxKey=hn(rr.dependencies.IDBKeyRange),"undefined"!=typeof dispatchEvent&&"undefined"!=typeof addEventListener&&(on(rn,(e=>{if(!ir){let t;wt?(t=document.createEvent("CustomEvent"),t.initCustomEvent(sn,!0,!0,e)):t=new CustomEvent(sn,{detail:e}),ir=!0,dispatchEvent(t),ir=!1}})),addEventListener(sn,(({detail:e})=>{ir||sr(e)})));let ir=!1;if("undefined"!=typeof BroadcastChannel){const e=new BroadcastChannel(sn);"function"==typeof e.unref&&e.unref(),on(rn,(t=>{ir||e.postMessage(t)})),e.onmessage=e=>{e.data&&sr(e.data)}}else if("undefined"!=typeof self&&"undefined"!=typeof navigator){on(rn,(e=>{try{ir||("undefined"!=typeof localStorage&&localStorage.setItem(sn,JSON.stringify({trig:Math.random(),changedParts:e})),"object"==typeof self.clients&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:sn,changedParts:e}))))}catch(e){}})),"undefined"!=typeof addEventListener&&addEventListener("storage",(e=>{if(e.key===sn){const t=JSON.parse(e.newValue);t&&sr(t.changedParts)}}));const e=self.document&&navigator.serviceWorker;e&&e.addEventListener("message",(function({data:e}){e&&e.type===sn&&sr(e.changedParts)}))}je.rejectionMapper=function(e,t){if(!e||e instanceof W||e instanceof TypeError||e instanceof SyntaxError||!e.name||!J[e.name])return e;var n=new J[e.name](t||e.message,e);return"stack"in e&&l(n,"stack",{get:function(){return this.inner.stack}}),n},F(R,Et);export{Xn as Dexie,Ln as RangeSet,Xn as default,tr as liveQuery,Wn as mergeRanges,Yn as rangesOverlap}; +//# sourceMappingURL=dexie.min.mjs.map \ No newline at end of file diff --git a/dist/modern/dexie.min.mjs.map b/dist/modern/dexie.min.mjs.map new file mode 100644 index 000000000..24b78151a --- /dev/null +++ b/dist/modern/dexie.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"names":["_global","globalThis","self","window","global","keys","Object","isArray","Array","extend","obj","extension","forEach","key","Promise","getProto","getPrototypeOf","_hasOwn","hasOwnProperty","hasOwn","prop","call","props","proto","Reflect","ownKeys","setProp","defineProperty","functionOrGetSet","options","get","set","configurable","value","writable","derive","Child","from","Parent","prototype","create","bind","getOwnPropertyDescriptor","getPropertyDescriptor","_slice","slice","args","start","end","override","origFunc","overridedFactory","assert","b","Error","asap$1","fn","setImmediate","setTimeout","arrayToObject","array","extractor","reduce","result","item","i","nameAndValue","getByKeyPath","keyPath","rv","l","length","val","push","period","indexOf","innerObj","substr","undefined","setByKeyPath","isFrozen","currentKeyPath","remainingKeyPath","isNaN","parseInt","splice","shallowClone","m","concat","flatten","a","apply","intrinsicTypeNames","split","map","num","t","filter","intrinsicTypes","x","circularRefs","deepClone","any","WeakMap","innerDeepClone","constructor","toString","toStringTag","o","iteratorSymbol","Symbol","iterator","getIteratorOf","NO_CHAR_ARRAY","getArrayOf","arrayLike","it","arguments","this","next","done","isAsyncFunction","debug","location","test","href","setDebug","libraryFilter","NEEDS_THROW_FOR_STACK","stack","getErrorWithStack","e","prettyStack","exception","numIgnoredFrames","name","message","frame","join","idbDomErrorNames","errorList","defaultTexts","VersionChanged","DatabaseClosed","Abort","TransactionInactive","MissingAPI","DexieError","msg","_e","getMultiErrorMessage","failures","v","s","ModifyError","successCount","failedKeys","BulkError","pos","failuresByPos","_stack","errnames","BaseException","exceptions","fullName","msgOrInner","inner","Syntax","SyntaxError","Type","TypeError","Range","RangeError","exceptionMap","fullNameExceptions","nop","mirror","pureFunctionChain","f1","f2","callBoth","on1","on2","hookCreatingChain","res","onsuccess","onerror","res2","hookDeletingChain","hookUpdatingChain","modifications","reverseStoppableEventChain","promisableChain","then","thiz","INTERNAL","ZONE_ECHO_LIMIT","resolvedNativePromise","nativePromiseProto","resolvedGlobalPromise","globalP","resolve","crypto","subtle","nativeP","digest","Uint8Array","nativePromiseThen","NativePromise","patchGlobalPromise","stack_being_generated","schedulePhysicalTick","physicalTick","MutationObserver","hiddenDiv","document","createElement","observe","attributes","setAttribute","asap","callback","microtickQueue","needsNewPhysicalTick","isOutsideMicroTick","unhandledErrors","rejectingErrors","currentFulfiller","rejectionMapper","globalPSD","id","ref","unhandleds","onunhandled","globalError","pgp","env","finalize","uh","PSD","numScheduledCalls","tickFinalizers","DexiePromise","_listeners","onuncatched","_lib","psd","_PSD","_stackHolder","_prev","_numPrev","_state","_value","handleRejection","executePromiseTask","thenProp","microTaskId","totalEchoes","onFulfilled","onRejected","possibleAwait","cleanup","decrementExpectedAwaits","reject","propagateToListener","Listener","nativeAwaitCompatibleWrap","linkToPreviousPromise","zone","promise","shouldExecuteTick","beginMicroTickScope","_then","propagateAllListeners","endMicroTickScope","ex","reason","_promise","tryCatch","origProp","some","p","addPossiblyUnhandledError","listeners","len","finalizePhysicalTick","listener","cb","callListener","ret","markErrorAsHandled","getStack","stacks","limit","errorName","failure","prev","numPrev","wasRootExec","callbacks","unhandledErrs","finalizers","PromiseReject","wrap","errorCatcher","outerScope","switchToZone","catch","type","handler","err","finally","onFinally","timeout","ms","Infinity","handle","Timeout","clearTimeout","snapShot","all","values","onPossibleParallellAsync","remaining","race","newPSD","newScope","usePSD","scheduler","follow","zoneProps","finalizer","run_at_end_of_this_or_next_physical_tick","allSettled","possiblePromises","results","status","AggregateError","task","awaits","echoes","taskCounter","zoneStack","zoneEchoes","zone_id_counter","a1","a2","parent","globalEnv","PromiseProp","nthen","getPatchedPromiseThen","gthen","incrementExpectedAwaits","possiblePromise","rejection","zoneEnterEcho","targetZone","zoneLeaveEcho","pop","bEnteringZone","currentZone","enqueueNativeMicroTask","GlobalPromise","targetEnv","a3","job","outerZone","origThen","onResolved","UNHANDLEDREJECTION","event","eventData","createEvent","initEvent","CustomEvent","detail","dispatchEvent","PromiseRejectionEvent","onunhandledrejection","_","defaultPrevented","console","warn","tempTransaction","db","mode","storeNames","idbdb","openComplete","letThrough","_vip","trans","_createTransaction","_dbSchema","PR1398_maxLoop","InvalidState","isOpen","_close","open","_completion","dbOpenError","isBeingOpened","_options","autoOpen","dbReadyPromise","DEXIE_VERSION","maxString","String","fromCharCode","minKey","INVALID_KEY_ARGUMENT","STRING_EXPECTED","connections","isIEOrEdge","navigator","userAgent","hasIEDeleteObjectStoreBug","hangsOnDeleteLargeKeyRange","dexieStackFrameFilter","DBNAMES_DB","READONLY","READWRITE","combine","filter1","filter2","AnyRange","lower","lowerOpen","upper","upperOpen","workaroundForUndefinedPrimKey","Table","_trans","writeLocked","_tx","tableName","checkTableInTransaction","schema","NotFound","idbtrans","transless","keyOrCrit","where","first","core","hook","reading","fire","indexOrCrit","WhereClause","keyPaths","equals","compoundIndex","indexes","primKey","ix","compound","every","sort","_maxKey","keyPathsInValidOrder","kp","JSON","stringify","idxByName","idb","_deps","indexedDB","cmp","idx","filterFunction","prevIndex","prevFilterFn","index","multi","toCollection","and","count","thenShortcut","offset","numRows","each","toArray","Collection","orderBy","reverse","mapToClass","mappedClass","readHook","unsubscribe","defineClass","content","add","auto","objToAdd","mutate","numFailures","lastResult","update","keyOrObject","modify","InvalidArgument","_a","put","delete","clear","range","bulkGet","getMany","bulkAdd","objects","keysOrOptions","wantResults","allKeys","numObjects","objectsToAdd","bulkPut","objectsToPut","bulkDelete","numKeys","Events","ctx","evs","eventName","subscriber","subscribe","addEventType","chainFunction","defaultFunction","cfg","context","subscribers","makeClassConstructor","isPlainKeyRange","ignoreLimitFilter","algorithm","or","justLimit","replayFilter","addFilter","addReplayFilter","factory","isLimitFilter","curr","getIndexOrStore","coreSchema","isPrimKey","primaryKey","getIndexByKeyPath","Schema","openCursor","coreTable","keysOnly","dir","unique","query","iter","coreTrans","union","cursor","advance","stop","fail","_iterate","iterate","valueMapper","cursorPromise","wrappedFn","c","continue","advancer","ta","tb","NaN","al","bl","compareUint8Arrays","getUint8Array","compareArrays","ArrayBuffer","isView","tsTag","buffer","byteOffset","byteLength","_read","_ctx","error","table","_write","_addAlgorithm","clone","raw","Math","min","sortBy","parts","lastPart","lastIndex","getval","order","sorter","aVal","bVal","offsetLeft","rowsLeft","until","bIncludeStopEntry","last","isMatch","indexName","_ondirectionchange","desc","eachKey","eachUniqueKey","eachPrimaryKey","primaryKeys","uniqueKeys","firstKey","lastKey","distinct","strKey","found","changes","modifyer","anythingModified","outbound","extractKey","modifyChunkSize","totalFailures","applyMutateResult","expectedCount","nextChunk","cache","addValues","putValues","putKeys","deleteKeys","origValue","criteria","deleteCallback","changeSpec","coreRange","simpleCompare","simpleCompareReverse","collectionOrWhereClause","T","collection","emptyCollection","whereClause","rangeEqual","nextCasing","lowerKey","upperNeedle","lowerNeedle","llp","lwrKeyChar","addIgnoreCaseAlgorithm","match","needles","suffix","compare","upperNeedles","lowerNeedles","direction","nextKeySuffix","needlesLen","initDirection","toUpperCase","toLowerCase","upperFactory","lowerFactory","needleBounds","needle","nb","createRange","firstPossibleNeedle","lowestPossibleCasing","casing","between","includeLower","includeUpper","_cmp","above","aboveOrEqual","below","belowOrEqual","startsWith","str","startsWithIgnoreCase","equalsIgnoreCase","anyOfIgnoreCase","startsWithAnyOfIgnoreCase","n","anyOf","_ascending","_descending","notEqual","inAnyRange","includeLowers","includeUppers","noneOf","ranges","ascending","descending","_min","max","_max","sortDirection","rangeSorter","newRange","rangePos","keyIsBeyondCurrentEntry","keyIsBeforeCurrentEntry","checkKey","keyWithinCurrentRange","startsWithAnyOf","eventRejectHandler","preventDefault","target","stopPropagation","DEXIE_STORAGE_MUTATED_EVENT_NAME","STORAGE_MUTATED_DOM_EVENT_NAME","globalEvents","Transaction","_lock","_reculock","lockOwnerFor","_unlock","_blockedFuncs","_locked","fnAndPSD","shift","OpenFailed","active","transaction","durability","chromeTransactionDurability","ev","_reject","onabort","on","oncomplete","_resolve","storagemutated","bWriteLock","ReadOnly","_root","waitFor","promiseLike","root","_waitingFor","_waitingQueue","store","objectStore","spin","_spinCount","currentWaitPromise","abort","memoizedTables","_memoizedTables","tableSchema","transactionBoundTable","createIndexSpec","src","nameFromKeyPath","createTableSchema","getMaxKey","IdbKeyRange","only","getKeyExtractor","getSinglePathKeyExtractor","arrayify","_id_counter","getKeyPathAlias","createDBCore","tmpTrans","makeIDBKeyRange","upperBound","lowerBound","bound","hasGetAll","tables","objectStoreNames","autoIncrement","indexByKeyPath","isPrimaryKey","indexNames","multiEntry","extractSchema","isAddOrPut","req","reqs","errorHandler","args1","args2","keyCount","callbackCount","successHandler","_pos","request","nonInfinitLimit","source","idbKeyRange","getAll","getAllKeys","openKeyCursor","___id","_cursorContinue","_cursorContinuePrimaryKey","continuePrimaryKey","_cursorAdvance","doThrowCursorIsStopped","gotOne","iterationPromise","resolveIteration","rejectIteration","guardedCallback","createDbCoreTable","tableMap","MIN_KEY","MAX_KEY","generateMiddlewareStacks","_novip","middlewares","IDBKeyRange","dbcore","stackImpl","down","createMiddlewareStack","createMiddlewareStacks","_middlewares","tbl","setApiOnPlace","objs","tableNames","dbschema","propDesc","enumerable","removeTablesApi","lowerVersionFirst","_cfg","version","runUpgraders","oldVersion","idbUpgradeTrans","globalSchema","_storeNames","rejectTransaction","createTable","populate","queue","versions","_versions","buildGlobalSchema","anyContentUpgraderHasRun","versToRun","runQueue","oldSchema","newSchema","adjustToExistingIndexNames","diff","getSchemaDiff","tuple","change","recreate","Upgrade","addIndex","deleteIndex","del","idxName","contentUpgrade","upgradeSchema","contentUpgradeIsAsync","returnValue","promiseFollowed","decrementor","storeName","deleteObjectStore","deleteRemovedTables","contains","updateTablesAndIndexes","oldDef","newDef","def","oldIndexes","newIndexes","oldIdx","newIdx","createObjectStore","createIndex","j","idbindex","_hasGetAll","dexieName","indexSpec","WorkerGlobalScope","Version","_parseStoresSpec","stores","outSchema","indexNum","trim","replace","storesSource","storesSpec","_allTables","upgrade","upgradeFunction","getDbNamesTable","dbNamesDB","Dexie$1","addons","dbnames","hasDatabasesNative","databases","vip","idbReady","intervalId","userAgentData","tryIdb","setInterval","clearInterval","dexieOpen","state","openCanceller","throwIfCancelled","resolveDbReady","dbReadyResolve","upgradeTransaction","wasCreated","tryOpenDB","dbName","autoSchema","round","verno","onblocked","_fireOnBlocked","onupgradeneeded","allowEmptyDB","close","delreq","deleteDatabase","NoSuchDatabase","oldVer","pow","readGlobalSchema","ch","verifyInstalledSchema","onversionchange","vcFired","onclose","_onDatabaseCreated","onReadyBeingFired","ready","fireRemainders","remainders","awaitIterator","callNext","onSuccess","step","onError","throw","getNext","extractTransactionArgs","_tableArgs_","scopeFunc","enterTransactionScope","parentTransaction","scopeFuncIsAsync","PrematureCommit","pad","virtualIndexMiddleware","level","indexLookup","allVirtualIndexes","addVirtualIndexes","keyTail","lowLevelIndex","keyPathAlias","indexList","keyLength","isVirtual","virtualIndex","translateRequest","virtualCursor","createVirtualCursor","getObjectDiff","prfx","ap","bp","apTypeName","hooksMiddleware","downCore","downTable","tableMiddleware","dxTrans","deleting","creating","updating","addPutOrDelete","deleteNextChunk","deleteRange","getEffectiveKeys","effectiveKeys","getExistingValues","existingValues","contexts","existingValue","generatedPrimaryKey","objectDiff","additionalChanges","requestedValue","getFromTransactionCache","cacheExistingValuesMiddleware","cachedResult","isEmptyRange","node","RangeSet","fromOrTree","to","d","addRange","left","right","r","rebalance","rightWasCutOff","mergeRanges","newSet","_addRangeSet","rangesOverlap","rangeSet1","rangeSet2","i1","getRangeSetIterator","nextResult1","i2","nextResult2","keyProvided","up","_b","rootClone","oldRootRight","computeDepth","rangeSet","addKey","addKeys","observabilityMiddleware","FULL_RANGE","tableClone","mutatedParts","getRangeSet","part","pkRangeSet","delsRangeSet","newObjs","oldCache","oldObjs","addAffectedIndex","addKeyOrKeys","oldKey","newKey","trackAffectedIndexes","getRange","readSubscribers","method","subscr","queriedIndex","queriedRanges","keysPromise","resultingKeys","pKeys","wantValues","pkey","deps","dependencies","cancelOpen","bSticky","keyRangeGenerator","keyRange","whereCtx","readingHook","createTableConstructor","complete","wasActive","createTransactionConstructor","versionNumber","createVersionConstructor","orCollection","_IDBKeyRange","createWhereClauseConstructor","newVersion","use","addon","versionInstance","_whenReady","unuse","mw","hasArguments","doDelete","_onDatabaseDeleted","backendDB","hasBeenClosed","hasFailed","dynamicallyOpened","_transaction","onlyIfCompatible","idbMode","SubTransaction","enterTransaction","InvalidTable","symbolObservable","observable","Observable","_subscribe","extendObservabilitySet","liveQuery","querier","currentValue","hasValue","observer","closed","accumMuts","currentObs","subscription","mutationListener","querying","startedListening","shouldNotify","doQuery","exec","execute","getValue","domDeps","mozIndexedDB","webkitIndexedDB","msIndexedDB","webkitIDBKeyRange","Dexie","propagateLocally","updateParts","wasMe","propagatingLocally","databaseName","exists","getDatabaseNames","infos","info","ignoreTransaction","async","generatorFn","spawn","currentTransaction","promiseOrFunction","optionalTimeout","delByKeyPath","semVer","maxKey","addEventListener","updatedParts","initCustomEvent","BroadcastChannel","bc","unref","changedParts","postMessage","onmessage","data","localStorage","setItem","trig","random","matchAll","includeUncontrolled","client","parse","newValue","swContainer","serviceWorker","domError"],"sources":["dexie.mjs"],"mappings":"AAaA,MAAMA,EAAgC,oBAAfC,WAA6BA,WAChC,oBAATC,KAAuBA,KACR,oBAAXC,OAAyBA,OAC5BC,OAENC,EAAOC,OAAOD,KACdE,EAAUC,MAAMD,QAItB,SAASE,EAAOC,EA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KAAKgD,MAAMrC,KACtB,IAED5D,CACX,EAgmJAyD,EAASJ,EAAOyS,WAEP6e,YAAkB2G,eAAU3G,cAAoB8M,gBAAWzF,kBAAaG"} \ No newline at end of file diff --git a/dist/modern/dexie.mjs b/dist/modern/dexie.mjs new file mode 100644 index 000000000..602ded4c2 --- /dev/null +++ b/dist/modern/dexie.mjs @@ -0,0 +1,5128 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 3.2.6, Tue Feb 13 2024 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + +const _global = typeof globalThis !== 'undefined' ? globalThis : + typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; + +const keys = Object.keys; +const isArray = Array.isArray; +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; +} +const getProto = Object.getPrototypeOf; +const _hasOwn = {}.hasOwnProperty; +function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); +} +function props(proto, extension) { + if (typeof extension === 'function') + extension = extension(getProto(proto)); + (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(key => { + setProp(proto, key, extension[key]); + }); +} +const 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) + }; + } + }; +} +const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +function getPropertyDescriptor(obj, prop) { + const pd = getOwnPropertyDescriptor(obj, prop); + let proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); +} +const _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$1(fn) { + if (_global.setImmediate) + setImmediate(fn); + else + setTimeout(fn, 0); +} +function arrayToObject(array, extractor) { + return array.reduce((result, item, i) => { + var nameAndValue = extractor(item, i); + if (nameAndValue) + result[nameAndValue[0]] = nameAndValue[1]; + return result; + }, {}); +} +function tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } + catch (ex) { + onerror && onerror(ex); + } +} +function getByKeyPath(obj, keyPath) { + if (typeof keyPath === 'string' && 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 == null ? 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 || !hasOwn(obj, currentKeyPath)) + 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; +} +const concat = [].concat; +function flatten(a) { + return concat.apply([], a); +} +const intrinsicTypeNames = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" + .split(',').concat(flatten([8, 16, 32, 64].map(num => ["Int", "Uint", "Float"].map(t => t + num + "Array")))).filter(t => _global[t]); +const intrinsicTypes = intrinsicTypeNames.map(t => _global[t]); +arrayToObject(intrinsicTypeNames, x => [x, true]); +let circularRefs = null; +function deepClone(any) { + circularRefs = typeof WeakMap !== 'undefined' && new WeakMap(); + const rv = innerDeepClone(any); + circularRefs = null; + return rv; +} +function innerDeepClone(any) { + if (!any || typeof any !== 'object') + return any; + let rv = circularRefs && circularRefs.get(any); + if (rv) + return rv; + if (isArray(any)) { + rv = []; + circularRefs && circularRefs.set(any, rv); + for (var i = 0, l = any.length; i < l; ++i) { + rv.push(innerDeepClone(any[i])); + } + } + else if (intrinsicTypes.indexOf(any.constructor) >= 0) { + rv = any; + } + else { + const proto = getProto(any); + rv = proto === Object.prototype ? {} : Object.create(proto); + circularRefs && circularRefs.set(any, rv); + for (var prop in any) { + if (hasOwn(any, prop)) { + rv[prop] = innerDeepClone(any[prop]); + } + } + } + return rv; +} +const { toString } = {}; +function toStringTag(o) { + return toString.call(o).slice(8, -1); +} +const iteratorSymbol = typeof Symbol !== 'undefined' ? + Symbol.iterator : + '@@iterator'; +const getIteratorOf = typeof iteratorSymbol === "symbol" ? function (x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); +} : function () { return null; }; +const 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; +} +const isAsyncFunction = typeof Symbol !== 'undefined' + ? (fn) => fn[Symbol.toStringTag] === 'AsyncFunction' + : () => 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 = () => true; +const NEEDS_THROW_FOR_STACK = !new Error("").stack; +function getErrorWithStack() { + if (NEEDS_THROW_FOR_STACK) + try { + getErrorWithStack.arguments; + 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(frame => "\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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" +}; +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(key => failures[key].toString()) + .filter((v, i, s) => 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 = Object.keys(failures).map(pos => failures[pos]); + this.failuresByPos = failures; + this.message = getMultiErrorMessage(msg, failures); +} +derive(BulkError).from(DexieError); +var errnames = errorList.reduce((obj, name) => (obj[name] = name + "Error", obj), {}); +const BaseException = DexieError; +var exceptions = errorList.reduce((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((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((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 = {}; +const LONG_STACKS_CLIP_LIMIT = 100, +MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ? + [] : + (() => { + let globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + const nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; +const patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +var schedulePhysicalTick = resolvedGlobalPromise ? + () => { resolvedGlobalPromise.then(physicalTick); } + : + _global.setImmediate ? + setImmediate.bind(null, physicalTick) : + _global.MutationObserver ? + () => { + var hiddenDiv = document.createElement("div"); + (new MutationObserver(() => { + physicalTick(); + hiddenDiv = null; + })).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); + } : + () => { setTimeout(physicalTick, 0); }; +var asap = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; +var isOutsideMicroTick = true, +needsNewPhysicalTick = true, +unhandledErrors = [], +rejectingErrors = [], +currentFulfiller = null, rejectionMapper = mirror; +var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + pgp: false, + env: {}, + finalize: function () { + this.unhandleds.forEach(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); +} +const thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + const cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise((resolve, reject) => { + propagateToListener(this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), 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, err => + err instanceof type ? handler(err) : PromiseReject(err)) + : this.then(null, err => + err && err.name === type ? handler(err) : PromiseReject(err)); + }, + finally: function (onFinally) { + return this.then(value => { + onFinally(); + return value; + }, 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) { + return ms < Infinity ? + new DexiePromise((resolve, reject) => { + var handle = setTimeout(() => 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((a, i) => DexiePromise.resolve(a).then(x => { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject)); + }); + }, + resolve: value => { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise((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((resolve, reject) => { + values.map(value => DexiePromise.resolve(value).then(resolve, reject)); + }); + }, + PSD: { + get: () => PSD, + set: value => PSD = value + }, + totalEchoes: { get: () => totalEchoes }, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: () => asap, + set: value => { asap = value; } + }, + rejectionMapper: { + get: () => rejectionMapper, + set: value => { rejectionMapper = value; } + }, + follow: (fn, zoneProps) => { + return new DexiePromise((resolve, reject) => { + return newScope((resolve, reject) => { + var psd = PSD; + psd.unhandleds = []; + psd.onunhandled = reject; + psd.finalize = callBoth(function () { + run_at_end_of_this_or_next_physical_tick(() => { + this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } +}); +if (NativePromise) { + if (NativePromise.allSettled) + setProp(DexiePromise, "allSettled", function () { + const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(resolve => { + if (possiblePromises.length === 0) + resolve([]); + let remaining = possiblePromises.length; + const results = new Array(remaining); + possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => results[i] = { status: "fulfilled", value }, reason => results[i] = { status: "rejected", reason }) + .then(() => --remaining || resolve(results))); + }); + }); + if (NativePromise.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise((resolve, reject) => { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + let remaining = possiblePromises.length; + const failures = new Array(remaining); + possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => resolve(value), failure => { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + })); + }); + }); +} +function executePromiseTask(promise, fn) { + try { + fn(value => { + if (promise._state !== null) + return; + if (value === promise) + throw new TypeError('A promise cannot be resolved with itself.'); + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + if (value && typeof value.then === 'function') { + executePromiseTask(promise, (resolve, reject) => { + value instanceof 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(() => { + var origProp = getPropertyDescriptor(reason, "stack"); + reason._promise = promise; + setProp(reason, "stack", { + get: () => stack_being_generated ? + origProp && (origProp.get ? + origProp.get.apply(reason) : + origProp.value) : + promise.stack + }); + }); + 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(() => { + 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(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(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(() => { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); +} +function addPossiblyUnhandledError(promise) { + if (!unhandledErrors.some(p => 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(); + } + }; +} +const 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, 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) + extend(psd, props); + ++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() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; + return true; +} +if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + incrementExpectedAwaits = decrementExpectedAwaits = nop; +} +function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { + incrementExpectedAwaits(); + return possiblePromise.then(x => { + decrementExpectedAwaits(); + return x; + }, 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 = globalPSD.env.Promise; + var targetEnv = targetZone.env; + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + GlobalPromise.all = targetEnv.all; + GlobalPromise.race = targetEnv.race; + GlobalPromise.resolve = targetEnv.resolve; + GlobalPromise.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise.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, cleanup) { + 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); + if (cleanup) + enqueueNativeMicroTask(decrementExpectedAwaits); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; +} +const UNHANDLEDREJECTION = "unhandledrejection"; +function globalError(err, promise) { + var rv; + try { + rv = promise.onuncatched(err); + } + catch (e) { } + if (rv !== false) + try { + var event, eventData = { promise: promise, reason: err }; + if (_global.document && document.createEvent) { + event = document.createEvent('Event'); + event.initEvent(UNHANDLEDREJECTION, true, true); + extend(event, eventData); + } + else if (_global.CustomEvent) { + event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData }); + extend(event, eventData); + } + if (event && _global.dispatchEvent) { + dispatchEvent(event); + if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) + 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.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { + if (db._state.openComplete) { + return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); + } + if (!db._state.isBeingOpened) { + if (!db._options.autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); + } + return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn)); + } + else { + var trans = db._createTransaction(mode, storeNames, db._dbSchema); + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(() => tempTransaction(db, mode, storeNames, fn)); + } + return rejection(ex); + } + return trans._promise(mode, (resolve, reject) => { + return newScope(() => { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(result => { + return trans._completion.then(() => result); + }); + } +} + +const DEXIE_VERSION = '3.2.6'; +const maxString = String.fromCharCode(65535); +const minKey = -Infinity; +const INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; +const STRING_EXPECTED = "String expected."; +const connections = []; +const isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); +const hasIEDeleteObjectStoreBug = isIEOrEdge; +const hangsOnDeleteLargeKeyRange = isIEOrEdge; +const dexieStackFrameFilter = frame => !/(dexie\.js|dexie\.min\.js)/.test(frame); +const DBNAMES_DB = '__dbnames'; +const READONLY = 'readonly'; +const READWRITE = 'readwrite'; + +function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; +} + +const AnyRange = { + type: 3 , + lower: -Infinity, + lowerOpen: false, + upper: [[]], + upperOpen: false +}; + +function workaroundForUndefinedPrimKey(keyPath) { + return typeof keyPath === "string" && !/\./.test(keyPath) + ? (obj) => { + if (obj[keyPath] === undefined && (keyPath in obj)) { + obj = deepClone(obj); + delete obj[keyPath]; + } + return obj; + } + : (obj) => obj; +} + +class Table { + _trans(mode, fn, writeLocked) { + const trans = this._tx || PSD.trans; + const 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); + } + const wasRootExec = beginMicroTickScope(); + try { + return trans && trans.db === this.db ? + trans === PSD.trans ? + trans._promise(mode, checkTableInTransaction, writeLocked) : + newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(this.db, mode, [this.name], checkTableInTransaction); + } + finally { + if (wasRootExec) + endMicroTickScope(); + } + } + get(keyOrCrit, cb) { + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + return this._trans('readonly', (trans) => { + return this.core.get({ trans, key: keyOrCrit }) + .then(res => this.hook.reading.fire(res)); + }).then(cb); + } + where(indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new this.db.WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`); + const keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => { + if (ix.compound && + keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) { + for (let i = 0; i < keyPaths.length; ++i) { + if (keyPaths.indexOf(ix.keyPath[i]) === -1) + return false; + } + return true; + } + return false; + }).sort((a, b) => a.keyPath.length - b.keyPath.length)[0]; + if (compoundIndex && this.db._maxKey !== maxString) { + const keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); + return this + .where(keyPathsInValidOrder) + .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp])); + } + if (!compoundIndex && debug) + console.warn(`The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` + + `compound index [${keyPaths.join('+')}]`); + const { idxByName } = this.schema; + const idb = this.db._deps.indexedDB; + function equals(a, b) { + try { + return idb.cmp(a, b) === 0; + } + catch (e) { + return false; + } + } + const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => { + const index = idxByName[keyPath]; + const value = indexOrCrit[keyPath]; + return [ + prevIndex || index, + prevIndex || !index ? + combine(prevFilterFn, index && index.multi ? + x => { + const prop = getByKeyPath(x, keyPath); + return isArray(prop) && prop.some(item => equals(value, item)); + } : x => equals(value, getByKeyPath(x, keyPath))) + : prevFilterFn + ]; + }, [null, null]); + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(filterFunction) : + compoundIndex ? + this.filter(filterFunction) : + this.where(keyPaths).equals(''); + } + filter(filterFunction) { + return this.toCollection().and(filterFunction); + } + count(thenShortcut) { + return this.toCollection().count(thenShortcut); + } + offset(offset) { + return this.toCollection().offset(offset); + } + limit(numRows) { + return this.toCollection().limit(numRows); + } + each(callback) { + return this.toCollection().each(callback); + } + toArray(thenShortcut) { + return this.toCollection().toArray(thenShortcut); + } + toCollection() { + return new this.db.Collection(new this.db.WhereClause(this)); + } + orderBy(index) { + return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? + `[${index.join('+')}]` : + index)); + } + reverse() { + return this.toCollection().reverse(); + } + mapToClass(constructor) { + this.schema.mappedClass = constructor; + const readHook = obj => { + if (!obj) + return obj; + const 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; + } + defineClass() { + function Class(content) { + extend(this, content); + } + return this.mapToClass(Class); + } + add(obj, key) { + const { auto, keyPath } = this.schema.primKey; + let objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', trans => { + return this.core.mutate({ trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); + }).then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult) + .then(lastResult => { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + } + update(keyOrObject, modifications) { + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === undefined) + return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); + try { + if (typeof modifications !== "function") { + keys(modifications).forEach(keyPath => { + setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); + }); + } + else { + modifications(keyOrObject, { value: keyOrObject, primKey: key }); + } + } + catch (_a) { + } + return this.where(":id").equals(key).modify(modifications); + } + else { + return this.where(":id").equals(keyOrObject).modify(modifications); + } + } + put(obj, key) { + const { auto, keyPath } = this.schema.primKey; + let objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null })) + .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult) + .then(lastResult => { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + } + delete(key) { + return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'delete', keys: [key] })) + .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined); + } + clear() { + return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'deleteRange', range: AnyRange })) + .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined); + } + bulkGet(keys) { + return this._trans('readonly', trans => { + return this.core.getMany({ + keys, + trans + }).then(result => result.map(res => this.hook.reading.fire(res))); + }); + } + bulkAdd(objects, keysOrOptions, options) { + const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + const wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', trans => { + const { auto, keyPath } = this.schema.primKey; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + const numObjects = objects.length; + let objectsToAdd = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return this.core.mutate({ trans, type: 'add', keys: keys, values: objectsToAdd, wantResults }) + .then(({ numFailures, results, lastResult, failures }) => { + const result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(`${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures); + }); + }); + } + bulkPut(objects, keysOrOptions, options) { + const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + const wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', trans => { + const { auto, keyPath } = this.schema.primKey; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + const numObjects = objects.length; + let objectsToPut = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return this.core.mutate({ trans, type: 'put', keys: keys, values: objectsToPut, wantResults }) + .then(({ numFailures, results, lastResult, failures }) => { + const result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(`${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures); + }); + }); + } + bulkDelete(keys) { + const numKeys = keys.length; + return this._trans('readwrite', trans => { + return this.core.mutate({ trans, type: 'delete', keys: keys }); + }).then(({ numFailures, lastResult, failures }) => { + if (numFailures === 0) + return lastResult; + throw new BulkError(`${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures); + }); + } +} + +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$1(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +function makeClassConstructor(prototype, constructor) { + derive(constructor).from({ prototype }); + return constructor; +} + +function createTableConstructor(db) { + return makeClassConstructor(Table.prototype, function Table(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 ? () => 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; + const 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) { + const index = getIndexOrStore(ctx, coreTable.schema); + return coreTable.openCursor({ + trans, + values: !ctx.keysOnly, + reverse: ctx.dir === 'prev', + unique: !!ctx.unique, + query: { + index, + range: ctx.range + } + }); +} +function iter(ctx, fn, coreTrans, coreTable) { + const 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 { + const set = {}; + const union = (item, cursor, advance) => { + if (!filter || filter(cursor, advance, result => cursor.stop(result), err => cursor.fail(err))) { + var primaryKey = cursor.primaryKey; + var key = '' + primaryKey; + if (key === '[object ArrayBuffer]') + key = '' + new Uint8Array(primaryKey); + if (!hasOwn(set, key)) { + set[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 ? (x, c, a) => fn(valueMapper(x), c, a) : fn; + var wrappedFn = wrap(mappedFn); + return cursorPromise.then(cursor => { + if (cursor) { + return cursor.start(() => { + var c = () => cursor.continue(); + if (!filter || filter(cursor, advancer => c = advancer, val => { cursor.stop(val); c = nop; }, e => { cursor.fail(e); c = nop; })) + wrappedFn(cursor.value, cursor, advancer => c = advancer); + c(); + }); + } + }); +} + +function cmp(a, b) { + try { + const ta = type(a); + const tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; +} +function compareArrays(a, b) { + const al = a.length; + const bl = b.length; + const l = al < bl ? al : bl; + for (let i = 0; i < l; ++i) { + const res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function compareUint8Arrays(a, b) { + const al = a.length; + const bl = b.length; + const l = al < bl ? al : bl; + for (let i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function type(x) { + const t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + const tsTag = toStringTag(x); + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; +} +function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); +} + +class Collection { + _read(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); + } + _write(fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readwrite', fn, "locked"); + } + _addAlgorithm(fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + } + _iterate(fn, coreTrans) { + return iter(this._ctx, fn, coreTrans, this._ctx.table.core); + } + clone(props) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props) + extend(ctx, props); + rv._ctx = ctx; + return rv; + } + raw() { + this._ctx.valueMapper = null; + return this; + } + each(fn) { + var ctx = this._ctx; + return this._read(trans => iter(ctx, fn, trans, ctx.table.core)); + } + count(cb) { + return this._read(trans => { + const ctx = this._ctx; + const coreTable = ctx.table.core; + if (isPlainKeyRange(ctx, true)) { + return coreTable.count({ + trans, + query: { + index: getIndexOrStore(ctx, coreTable.schema), + range: ctx.range + } + }).then(count => Math.min(count, ctx.limit)); + } + else { + var count = 0; + return iter(ctx, () => { ++count; return false; }, trans, coreTable) + .then(() => count); + } + }).then(cb); + } + sortBy(keyPath, cb) { + const parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; + function getval(obj, i) { + if (i) + return getval(obj[parts[i]], i - 1); + return obj[lastPart]; + } + var order = this._ctx.dir === "next" ? 1 : -1; + function sorter(a, b) { + var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); + return aVal < bVal ? -order : aVal > bVal ? order : 0; + } + return this.toArray(function (a) { + return a.sort(sorter); + }).then(cb); + } + toArray(cb) { + return this._read(trans => { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + const { valueMapper } = ctx; + const index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans, + limit: ctx.limit, + values: true, + query: { + index, + range: ctx.range + } + }).then(({ result }) => valueMapper ? result.map(valueMapper) : result); + } + else { + const a = []; + return iter(ctx, item => a.push(item), trans, ctx.table.core).then(() => a); + } + }, cb); + } + offset(offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; + if (isPlainKeyRange(ctx)) { + addReplayFilter(ctx, () => { + var offsetLeft = offset; + return (cursor, advance) => { + if (offsetLeft === 0) + return true; + if (offsetLeft === 1) { + --offsetLeft; + return false; + } + advance(() => { + cursor.advance(offsetLeft); + offsetLeft = 0; + }); + return false; + }; + }); + } + else { + addReplayFilter(ctx, () => { + var offsetLeft = offset; + return () => (--offsetLeft < 0); + }); + } + return this; + } + limit(numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); + addReplayFilter(this._ctx, () => { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); + return rowsLeft >= 0; + }; + }, true); + return this; + } + until(filterFunction, bIncludeStopEntry) { + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + } + first(cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + } + last(cb) { + return this.reverse().first(cb); + } + filter(filterFunction) { + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + addMatchFilter(this._ctx, filterFunction); + return this; + } + and(filter) { + return this.filter(filter); + } + or(indexName) { + return new this.db.WhereClause(this._ctx.table, indexName, this); + } + reverse() { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + } + desc() { + return this.reverse(); + } + eachKey(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + } + eachUniqueKey(cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + } + eachPrimaryKey(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + } + keys(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.key); + }).then(function () { + return a; + }).then(cb); + } + primaryKeys(cb) { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + return this._read(trans => { + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans, + values: false, + limit: ctx.limit, + query: { + index, + range: ctx.range + } + }); + }).then(({ result }) => 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); + } + uniqueKeys(cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + } + firstKey(cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + } + lastKey(cb) { + return this.reverse().firstKey(cb); + } + distinct() { + 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; + } + modify(changes) { + var ctx = this._ctx; + return this._write(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; + }; + } + const coreTable = ctx.table.core; + const { outbound, extractKey } = coreTable.schema.primaryKey; + const limit = this.db._options.modifyChunkSize || 200; + const totalFailures = []; + let successCount = 0; + const failedKeys = []; + const applyMutateResult = (expectedCount, res) => { + const { failures, numFailures } = res; + successCount += expectedCount - numFailures; + for (let pos of keys(failures)) { + totalFailures.push(failures[pos]); + } + }; + return this.clone().primaryKeys().then(keys => { + const nextChunk = (offset) => { + const count = Math.min(limit, keys.length - offset); + return coreTable.getMany({ + trans, + keys: keys.slice(offset, offset + count), + cache: "immutable" + }).then(values => { + const addValues = []; + const putValues = []; + const putKeys = outbound ? [] : null; + const deleteKeys = []; + for (let i = 0; i < count; ++i) { + const origValue = values[i]; + const ctx = { + value: deepClone(origValue), + primKey: keys[offset + i] + }; + if (modifyer.call(ctx, ctx.value, ctx) !== false) { + if (ctx.value == null) { + deleteKeys.push(keys[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx.value)) !== 0) { + deleteKeys.push(keys[offset + i]); + addValues.push(ctx.value); + } + else { + putValues.push(ctx.value); + if (outbound) + putKeys.push(keys[offset + i]); + } + } + } + const criteria = isPlainKeyRange(ctx) && + ctx.limit === Infinity && + (typeof changes !== 'function' || changes === deleteCallback) && { + index: ctx.index, + range: ctx.range + }; + return Promise.resolve(addValues.length > 0 && + coreTable.mutate({ trans, type: 'add', values: addValues }) + .then(res => { + for (let pos in res.failures) { + deleteKeys.splice(parseInt(pos), 1); + } + applyMutateResult(addValues.length, res); + })).then(() => (putValues.length > 0 || (criteria && typeof changes === 'object')) && + coreTable.mutate({ + trans, + type: 'put', + keys: putKeys, + values: putValues, + criteria, + changeSpec: typeof changes !== 'function' + && changes + }).then(res => applyMutateResult(putValues.length, res))).then(() => (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && + coreTable.mutate({ + trans, + type: 'delete', + keys: deleteKeys, + criteria + }).then(res => applyMutateResult(deleteKeys.length, res))).then(() => { + return keys.length > offset + count && nextChunk(offset + limit); + }); + }); + }; + return nextChunk(0).then(() => { + if (totalFailures.length > 0) + throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); + return keys.length; + }); + }); + }); + } + delete() { + var ctx = this._ctx, range = ctx.range; + if (isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 )) + { + return this._write(trans => { + const { primaryKey } = ctx.table.core.schema; + const coreRange = range; + return ctx.table.core.count({ trans, query: { index: primaryKey, range: coreRange } }).then(count => { + return ctx.table.core.mutate({ trans, type: 'deleteRange', range: coreRange }) + .then(({ failures, lastResult, results, numFailures }) => { + if (numFailures) + throw new ModifyError("Could not delete some values", Object.keys(failures).map(pos => failures[pos]), count - numFailures); + return count - numFailures; + }); + }); + }); + } + return this.modify(deleteCallback); + } +} +const deleteCallback = (value, ctx) => ctx.value = null; + +function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) { + this.db = db; + let keyRange = AnyRange, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + const whereCtx = whereClause._ctx; + const table = whereCtx.table; + const 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, () => rangeEqual("")).limit(0); +} +function upperFactory(dir) { + return dir === "next" ? + (s) => s.toUpperCase() : + (s) => s.toLowerCase(); +} +function lowerFactory(dir) { + return dir === "next" ? + (s) => s.toLowerCase() : + (s) => s.toUpperCase(); +} +function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { + var length = Math.min(key.length, lowerNeedle.length); + var llp = -1; + for (var i = 0; i < length; ++i) { + var lwrKeyChar = lowerKey[i]; + if (lwrKeyChar !== lowerNeedle[i]) { + if (cmp(key[i], upperNeedle[i]) < 0) + return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); + if (cmp(key[i], lowerNeedle[i]) < 0) + return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); + if (llp >= 0) + return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); + return null; + } + if (cmp(key[i], lwrKeyChar) < 0) + llp = i; + } + if (length < lowerNeedle.length && dir === "next") + return key + upperNeedle.substr(key.length); + if (length < key.length && dir === "prev") + return key.substr(0, upperNeedle.length); + return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1)); +} +function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { + var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; + if (!needles.every(s => typeof s === 'string')) { + return fail(whereClause, STRING_EXPECTED); + } + function initDirection(dir) { + upper = upperFactory(dir); + lower = lowerFactory(dir); + compare = (dir === "next" ? simpleCompare : simpleCompareReverse); + var needleBounds = needles.map(function (needle) { + return { lower: lower(needle), upper: upper(needle) }; + }).sort(function (a, b) { + return compare(a.lower, b.lower); + }); + upperNeedles = needleBounds.map(function (nb) { return nb.upper; }); + lowerNeedles = needleBounds.map(function (nb) { return nb.lower; }); + direction = dir; + nextKeySuffix = (dir === "next" ? "" : suffix); + } + initDirection("next"); + var c = new whereClause.Collection(whereClause, () => 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, + upper, + lowerOpen, + upperOpen + }; +} +function rangeEqual(value) { + return { + type: 1 , + lower: value, + upper: value + }; +} + +class WhereClause { + get Collection() { + return this._ctx.table.db.Collection; + } + between(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, () => createRange(lower, upper, !includeLower, !includeUpper)); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + } + equals(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => rangeEqual(value)); + } + above(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(value, undefined, true)); + } + aboveOrEqual(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(value, undefined, false)); + } + below(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(undefined, value, false, true)); + } + belowOrEqual(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(undefined, value)); + } + startsWith(str) { + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + } + startsWithIgnoreCase(str) { + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString); + } + equalsIgnoreCase(str) { + return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], ""); + } + anyOfIgnoreCase() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, ""); + } + startsWithAnyOfIgnoreCase() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString); + } + anyOf() { + const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + let compare = this._cmp; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1])); + c._ondirectionchange = direction => { + compare = (direction === "next" ? + this._ascending : + this._descending); + set.sort(compare); + }; + let i = 0; + c._addAlgorithm((cursor, advance, resolve) => { + const 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(() => { cursor.continue(set[i]); }); + return false; + } + }); + return c; + } + notEqual(value) { + return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); + } + noneOf() { + const 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); + } + const ranges = set.reduce((res, val) => 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 }); + } + inAnyRange(ranges, options) { + const 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(range => 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); + } + const includeLowers = !options || options.includeLowers !== false; + const includeUppers = options && options.includeUppers === true; + function addRange(ranges, newRange) { + let i = 0, l = ranges.length; + for (; i < l; ++i) { + const 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; + } + let sortDirection = ascending; + function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } + let set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + let rangePos = 0; + const keyIsBeyondCurrentEntry = includeUppers ? + key => ascending(key, set[rangePos][1]) > 0 : + key => ascending(key, set[rangePos][1]) >= 0; + const keyIsBeforeCurrentEntry = includeLowers ? + key => descending(key, set[rangePos][0]) > 0 : + key => descending(key, set[rangePos][0]) >= 0; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + let checkKey = keyIsBeyondCurrentEntry; + const c = new this.Collection(this, () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers)); + c._ondirectionchange = direction => { + if (direction === "next") { + checkKey = keyIsBeyondCurrentEntry; + sortDirection = ascending; + } + else { + checkKey = keyIsBeforeCurrentEntry; + sortDirection = descending; + } + set.sort(rangeSorter); + }; + c._addAlgorithm((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(() => { + if (sortDirection === ascending) + cursor.continue(set[rangePos][0]); + else + cursor.continue(set[rangePos][1]); + }); + return false; + } + }); + return c; + } + startsWithAnyOf() { + const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (!set.every(s => typeof s === 'string')) { + return fail(this, "startsWithAnyOf() only works with strings"); + } + if (set.length === 0) + return emptyCollection(this); + return this.inAnyRange(set.map((str) => [str, str + maxString])); + } +} + +function createWhereClauseConstructor(db) { + return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) { + this.db = db; + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + const indexedDB = db._deps.indexedDB; + if (!indexedDB) + throw new exceptions.MissingAPI(); + this._cmp = this._ascending = indexedDB.cmp.bind(indexedDB); + this._descending = (a, b) => indexedDB.cmp(b, a); + this._max = (a, b) => indexedDB.cmp(a, b) > 0 ? a : b; + this._min = (a, b) => indexedDB.cmp(a, b) < 0 ? a : b; + this._IDBKeyRange = db._deps.IDBKeyRange; + }); +} + +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(); +} + +const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; +const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; +const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); + +class Transaction { + _lock() { + assert(!PSD.global); + ++this._reculock; + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + } + _unlock() { + 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; + } + _locked() { + return this._reculock && PSD.lockOwnerFor !== this; + } + create(idbtrans) { + if (!this.mode) + return this; + const idbdb = this.db.idbdb; + const 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 || + (this.db.core + ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) + : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); + idbtrans.onerror = wrap(ev => { + preventDefault(ev); + this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(ev => { + preventDefault(ev); + this.active && this._reject(new exceptions.Abort(idbtrans.error)); + this.active = false; + this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(() => { + this.active = false; + this._resolve(); + if ('mutatedParts' in idbtrans) { + globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); + } + }); + return this; + } + _promise(mode, fn, bWriteLock) { + 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((resolve, reject) => { + this._blockedFuncs.push([() => { + this._promise(mode, fn, bWriteLock).then(resolve, reject); + }, PSD]); + }); + } + else if (bWriteLock) { + return newScope(() => { + var p = new DexiePromise((resolve, reject) => { + this._lock(); + const rv = fn(resolve, reject, this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p.finally(() => this._unlock()); + p._lib = true; + return p; + }); + } + else { + var p = new DexiePromise((resolve, reject) => { + var rv = fn(resolve, reject, this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + } + _root() { + return this.parent ? this.parent._root() : this; + } + waitFor(promiseLike) { + var root = this._root(); + const promise = DexiePromise.resolve(promiseLike); + if (root._waitingFor) { + root._waitingFor = root._waitingFor.then(() => 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((resolve, reject) => { + promise.then(res => root._waitingQueue.push(wrap(resolve.bind(null, res))), err => root._waitingQueue.push(wrap(reject.bind(null, err)))).finally(() => { + if (root._waitingFor === currentWaitPromise) { + root._waitingFor = null; + } + }); + }); + } + abort() { + if (this.active) { + this.active = false; + if (this.idbtrans) + this.idbtrans.abort(); + this._reject(new exceptions.Abort()); + } + } + table(tableName) { + const memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); + if (hasOwn(memoizedTables, tableName)) + return memoizedTables[tableName]; + const tableSchema = this.schema[tableName]; + if (!tableSchema) { + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + } + const transactionBoundTable = new this.db.Table(tableName, tableSchema, this); + transactionBoundTable.core = this.db.core.table(tableName); + memoizedTables[tableName] = transactionBoundTable; + return transactionBoundTable; + } +} + +function createTransactionConstructor(db) { + return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) { + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.chromeTransactionDurability = chromeTransactionDurability; + 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((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + this._completion.then(() => { + this.active = false; + this.on.complete.fire(); + }, 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, + keyPath, + unique, + multi, + auto, + 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, + primKey, + indexes, + mappedClass: null, + idxByName: arrayToObject(indexes, index => [index.name, index]) + }; +} + +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} +let getMaxKey = (IdbKeyRange) => { + try { + IdbKeyRange.only([[]]); + getMaxKey = () => [[]]; + return [[]]; + } + catch (e) { + getMaxKey = () => maxString; + return maxString; + } +}; + +function getKeyExtractor(keyPath) { + if (keyPath == null) { + return () => undefined; + } + else if (typeof keyPath === 'string') { + return getSinglePathKeyExtractor(keyPath); + } + else { + return obj => getByKeyPath(obj, keyPath); + } +} +function getSinglePathKeyExtractor(keyPath) { + const split = keyPath.split('.'); + if (split.length === 1) { + return obj => obj[keyPath]; + } + else { + return obj => getByKeyPath(obj, keyPath); + } +} + +function arrayify(arrayLike) { + return [].slice.call(arrayLike); +} +let _id_counter = 0; +function getKeyPathAlias(keyPath) { + return keyPath == null ? + ":id" : + typeof keyPath === 'string' ? + keyPath : + `[${keyPath.join('+')}]`; +} +function createDBCore(db, IdbKeyRange, tmpTrans) { + function extractSchema(db, trans) { + const tables = arrayify(db.objectStoreNames); + return { + schema: { + name: db.name, + tables: tables.map(table => trans.objectStore(table)).map(store => { + const { keyPath, autoIncrement } = store; + const compound = isArray(keyPath); + const outbound = keyPath == null; + const indexByKeyPath = {}; + const result = { + name: store.name, + primaryKey: { + name: null, + isPrimaryKey: true, + outbound, + compound, + keyPath, + autoIncrement, + unique: true, + extractKey: getKeyExtractor(keyPath) + }, + indexes: arrayify(store.indexNames).map(indexName => store.index(indexName)) + .map(index => { + const { name, unique, multiEntry, keyPath } = index; + const compound = isArray(keyPath); + const result = { + name, + compound, + keyPath, + unique, + multiEntry, + extractKey: getKeyExtractor(keyPath) + }; + indexByKeyPath[getKeyPathAlias(keyPath)] = result; + return result; + }), + getIndexByKeyPath: (keyPath) => 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"); + const { lower, upper, lowerOpen, upperOpen } = range; + const 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) { + const tableName = tableSchema.name; + function mutate({ trans, type, keys, values, range }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const store = trans.objectStore(tableName); + const outbound = store.keyPath == null; + const isAddOrPut = type === "put" || type === "add"; + if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') + throw new Error("Invalid operation type: " + type); + const { length } = keys || values || { length: 1 }; + if (keys && values && keys.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 }); + let req; + const reqs = []; + const failures = []; + let numFailures = 0; + const errorHandler = event => { + ++numFailures; + preventDefault(event); + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures, failures, results: [], lastResult: undefined }); + if (range.type === 3 ) + reqs.push(req = store.clear()); + else + reqs.push(req = store.delete(makeIDBKeyRange(range))); + } + else { + const [args1, args2] = isAddOrPut ? + outbound ? + [values, keys] : + [values, null] : + [keys, null]; + if (isAddOrPut) { + for (let i = 0; i < length; ++i) { + reqs.push(req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i]))); + req.onerror = errorHandler; + } + } + else { + for (let i = 0; i < length; ++i) { + reqs.push(req = store[type](args1[i])); + req.onerror = errorHandler; + } + } + } + const done = event => { + const lastResult = event.target.result; + reqs.forEach((req, i) => req.error != null && (failures[i] = req.error)); + resolve({ + numFailures, + failures, + results: type === "delete" ? keys : reqs.map(req => req.result), + lastResult + }); + }; + req.onerror = event => { + errorHandler(event); + done(event); + }; + req.onsuccess = done; + }); + } + function openCursor({ trans, values, query, reverse, unique }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const { index, range } = query; + const store = trans.objectStore(tableName); + const source = index.isPrimaryKey ? + store : + store.index(index.name); + const direction = reverse ? + unique ? + "prevunique" : + "prev" : + unique ? + "nextunique" : + "next"; + const req = values || !('openKeyCursor' in source) ? + source.openCursor(makeIDBKeyRange(range), direction) : + source.openKeyCursor(makeIDBKeyRange(range), direction); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(ev => { + const cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + cursor.___id = ++_id_counter; + cursor.done = false; + const _cursorContinue = cursor.continue.bind(cursor); + let _cursorContinuePrimaryKey = cursor.continuePrimaryKey; + if (_cursorContinuePrimaryKey) + _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); + const _cursorAdvance = cursor.advance.bind(cursor); + const doThrowCursorIsNotStarted = () => { throw new Error("Cursor not started"); }; + const doThrowCursorIsStopped = () => { 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 () { + let gotOne = 1; + return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this); + }; + cursor.start = (callback) => { + const iterationPromise = new Promise((resolveIteration, rejectIteration) => { + resolveIteration = wrap(resolveIteration); + req.onerror = eventRejectHandler(rejectIteration); + cursor.fail = rejectIteration; + cursor.stop = value => { + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; + resolveIteration(value); + }; + }); + const guardedCallback = () => { + if (req.result) { + try { + callback(); + } + catch (err) { + cursor.fail(err); + } + } + else { + cursor.done = true; + cursor.start = () => { throw new Error("Cursor behind last entry"); }; + cursor.stop(); + } + }; + req.onsuccess = wrap(ev => { + req.onsuccess = guardedCallback; + guardedCallback(); + }); + cursor.continue = _cursorContinue; + cursor.continuePrimaryKey = _cursorContinuePrimaryKey; + cursor.advance = _cursorAdvance; + guardedCallback(); + return iterationPromise; + }; + resolve(cursor); + }, reject); + }); + } + function query(hasGetAll) { + return (request) => { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const { trans, values, limit, query } = request; + const nonInfinitLimit = limit === Infinity ? undefined : limit; + const { index, range } = query; + const store = trans.objectStore(tableName); + const source = index.isPrimaryKey ? store : store.index(index.name); + const idbKeyRange = makeIDBKeyRange(range); + if (limit === 0) + return resolve({ result: [] }); + if (hasGetAll) { + const req = values ? + source.getAll(idbKeyRange, nonInfinitLimit) : + source.getAllKeys(idbKeyRange, nonInfinitLimit); + req.onsuccess = event => resolve({ result: event.target.result }); + req.onerror = eventRejectHandler(reject); + } + else { + let count = 0; + const req = values || !('openKeyCursor' in source) ? + source.openCursor(idbKeyRange) : + source.openKeyCursor(idbKeyRange); + const result = []; + req.onsuccess = event => { + const cursor = req.result; + if (!cursor) + return resolve({ result }); + result.push(values ? cursor.value : cursor.primaryKey); + if (++count === limit) + return resolve({ result }); + cursor.continue(); + }; + req.onerror = eventRejectHandler(reject); + } + }); + }; + } + return { + name: tableName, + schema: tableSchema, + mutate, + getMany({ trans, keys }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const store = trans.objectStore(tableName); + const length = keys.length; + const result = new Array(length); + let keyCount = 0; + let callbackCount = 0; + let req; + const successHandler = event => { + const req = event.target; + if ((result[req._pos] = req.result) != null) + ; + if (++callbackCount === keyCount) + resolve(result); + }; + const errorHandler = eventRejectHandler(reject); + for (let i = 0; i < length; ++i) { + const key = keys[i]; + if (key != null) { + req = store.get(keys[i]); + req._pos = i; + req.onsuccess = successHandler; + req.onerror = errorHandler; + ++keyCount; + } + } + if (keyCount === 0) + resolve(result); + }); + }, + get({ trans, key }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const store = trans.objectStore(tableName); + const req = store.get(key); + req.onsuccess = event => resolve(event.target.result); + req.onerror = eventRejectHandler(reject); + }); + }, + query: query(hasGetAll), + openCursor, + count({ query, trans }) { + const { index, range } = query; + return new Promise((resolve, reject) => { + const store = trans.objectStore(tableName); + const source = index.isPrimaryKey ? store : store.index(index.name); + const idbKeyRange = makeIDBKeyRange(range); + const req = idbKeyRange ? source.count(idbKeyRange) : source.count(); + req.onsuccess = wrap(ev => resolve(ev.target.result)); + req.onerror = eventRejectHandler(reject); + }); + } + }; + } + const { schema, hasGetAll } = extractSchema(db, tmpTrans); + const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema)); + const tableMap = {}; + tables.forEach(table => tableMap[table.name] = table); + return { + stack: "dbcore", + transaction: db.transaction.bind(db), + table(name) { + const result = tableMap[name]; + if (!result) + throw new Error(`Table '${name}' not found`); + return tableMap[name]; + }, + MIN_KEY: -Infinity, + MAX_KEY: getMaxKey(IdbKeyRange), + schema + }; +} + +function createMiddlewareStack(stackImpl, middlewares) { + return middlewares.reduce((down, { create }) => ({ ...down, ...create(down) }), stackImpl); +} +function createMiddlewareStacks(middlewares, idbdb, { IDBKeyRange, indexedDB }, tmpTrans) { + const dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore + }; +} +function generateMiddlewareStacks({ _novip: db }, tmpTrans) { + const idbdb = tmpTrans.db; + const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); + db.core = stacks.dbcore; + db.tables.forEach(table => { + const tableName = table.name; + if (db.core.schema.tables.some(tbl => tbl.name === tableName)) { + table.core = db.core.table(tableName); + if (db[tableName] instanceof db.Table) { + db[tableName].core = table.core; + } + } + }); +} + +function setApiOnPlace({ _novip: db }, objs, tableNames, dbschema) { + tableNames.forEach(tableName => { + const schema = dbschema[tableName]; + objs.forEach(obj => { + const propDesc = getPropertyDescriptor(obj, tableName); + if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { + if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { + setProp(obj, tableName, { + get() { return this.table(tableName); }, + set(value) { + defineProperty(this, tableName, { value, writable: true, configurable: true, enumerable: true }); + } + }); + } + else { + obj[tableName] = new db.Table(tableName, schema); + } + } + }); + }); +} +function removeTablesApi({ _novip: db }, objs) { + objs.forEach(obj => { + for (let 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) { + const globalSchema = db._dbSchema; + const trans = db._createTransaction('readwrite', db._storeNames, globalSchema); + trans.create(idbUpgradeTrans); + trans._completion.catch(reject); + const rejectTransaction = trans._reject.bind(trans); + const transless = PSD.transless || PSD; + newScope(() => { + PSD.trans = trans; + PSD.transless = transless; + if (oldVersion === 0) { + keys(globalSchema).forEach(tableName => { + createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + generateMiddlewareStacks(db, idbUpgradeTrans); + DexiePromise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction); + } + else + updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction); + }); +} +function updateTablesAndIndexes({ _novip: db }, oldVersion, trans, idbUpgradeTrans) { + const queue = []; + const versions = db._versions; + let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); + let anyContentUpgraderHasRun = false; + const versToRun = versions.filter(v => v._cfg.version >= oldVersion); + versToRun.forEach(version => { + queue.push(() => { + const oldSchema = globalSchema; + const newSchema = version._cfg.dbschema; + adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans); + adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); + globalSchema = db._dbSchema = newSchema; + const diff = getSchemaDiff(oldSchema, newSchema); + diff.add.forEach(tuple => { + createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + diff.change.forEach(change => { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + const store = idbUpgradeTrans.objectStore(change.name); + change.add.forEach(idx => addIndex(store, idx)); + change.change.forEach(idx => { + store.deleteIndex(idx.name); + addIndex(store, idx); + }); + change.del.forEach(idxName => store.deleteIndex(idxName)); + } + }); + const contentUpgrade = version._cfg.contentUpgrade; + if (contentUpgrade && version._cfg.version > oldVersion) { + generateMiddlewareStacks(db, idbUpgradeTrans); + trans._memoizedTables = {}; + anyContentUpgraderHasRun = true; + let upgradeSchema = shallowClone(newSchema); + diff.del.forEach(table => { + upgradeSchema[table] = oldSchema[table]; + }); + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema); + trans.schema = upgradeSchema; + const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade); + if (contentUpgradeIsAsync) { + incrementExpectedAwaits(); + } + let returnValue; + const promiseFollowed = DexiePromise.follow(() => { + returnValue = contentUpgrade(trans); + if (returnValue) { + if (contentUpgradeIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + } + }); + return (returnValue && typeof returnValue.then === 'function' ? + DexiePromise.resolve(returnValue) : promiseFollowed.then(() => returnValue)); + } + }); + queue.push(idbtrans => { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + const 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(() => { + createMissingTables(globalSchema, idbUpgradeTrans); + }); +} +function getSchemaDiff(oldSchema, newSchema) { + const diff = { + del: [], + add: [], + change: [] + }; + let table; + for (table in oldSchema) { + if (!newSchema[table]) + diff.del.push(table); + } + for (table in newSchema) { + const oldDef = oldSchema[table], newDef = newSchema[table]; + if (!oldDef) { + diff.add.push([table, newDef]); + } + else { + const change = { + name: table, + def: newDef, + recreate: false, + del: [], + add: [], + change: [] + }; + if (( + '' + (oldDef.primKey.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || + (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) + { + change.recreate = true; + diff.change.push(change); + } + else { + const oldIndexes = oldDef.idxByName; + const newIndexes = newDef.idxByName; + let idxName; + for (idxName in oldIndexes) { + if (!newIndexes[idxName]) + change.del.push(idxName); + } + for (idxName in newIndexes) { + const 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) { + const store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? + { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : + { autoIncrement: primKey.auto }); + indexes.forEach(idx => addIndex(store, idx)); + return store; +} +function createMissingTables(newSchema, idbtrans) { + keys(newSchema).forEach(tableName => { + if (!idbtrans.db.objectStoreNames.contains(tableName)) { + createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); + } + }); +} +function deleteRemovedTables(newSchema, idbtrans) { + [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName => 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) { + const globalSchema = {}; + const dbStoreNames = slice(idbdb.objectStoreNames, 0); + dbStoreNames.forEach(storeName => { + const store = tmpTrans.objectStore(storeName); + let keyPath = store.keyPath; + const primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); + const indexes = []; + for (let j = 0; j < store.indexNames.length; ++j) { + const 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({ _novip: db }, idbdb, tmpTrans) { + db.verno = idbdb.version / 10; + const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); + db._storeNames = slice(idbdb.objectStoreNames, 0); + setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); +} +function verifyInstalledSchema(db, tmpTrans) { + const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); + const diff = getSchemaDiff(installedSchema, db._dbSchema); + return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length)); +} +function adjustToExistingIndexNames({ _novip: db }, schema, idbtrans) { + const storeNames = idbtrans.db.objectStoreNames; + for (let i = 0; i < storeNames.length; ++i) { + const storeName = storeNames[i]; + const store = idbtrans.objectStore(storeName); + db._hasGetAll = 'getAll' in store; + for (let j = 0; j < store.indexNames.length; ++j) { + const indexName = store.indexNames[j]; + const keyPath = store.index(indexName).keyPath; + const dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; + if (schema[storeName]) { + const 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((index, indexNum) => { + index = index.trim(); + const name = index.replace(/([&*]|\+\+)/g, ""); + const keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); + }); +} + +class Version { + _parseStoresSpec(stores, outSchema) { + keys(stores).forEach(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(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); + } + }); + } + stores(stores) { + const db = this.db; + this._cfg.storesSource = this._cfg.storesSource ? + extend(this._cfg.storesSource, stores) : + stores; + const versions = db._versions; + const storesSpec = {}; + let dbschema = {}; + versions.forEach(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; + } + upgrade(upgradeFunction) { + this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); + return this; + } +} + +function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); +} + +function getDbNamesTable(indexedDB, IDBKeyRange) { + let dbNamesDB = indexedDB["_dbNamesDB"]; + if (!dbNamesDB) { + dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { + addons: [], + indexedDB, + IDBKeyRange, + }); + dbNamesDB.version(1).stores({ dbnames: "name" }); + } + return dbNamesDB.table("dbnames"); +} +function hasDatabasesNative(indexedDB) { + return indexedDB && typeof indexedDB.databases === "function"; +} +function getDatabaseNames({ indexedDB, IDBKeyRange, }) { + return hasDatabasesNative(indexedDB) + ? Promise.resolve(indexedDB.databases()).then((infos) => infos + .map((info) => info.name) + .filter((name) => name !== DBNAMES_DB)) + : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); +} +function _onDatabaseCreated({ indexedDB, IDBKeyRange }, name) { + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).put({ name }).catch(nop); +} +function _onDatabaseDeleted({ indexedDB, IDBKeyRange }, name) { + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); +} + +function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); +} + +function idbReady() { + var isSafari = !navigator.userAgentData && + /Safari\//.test(navigator.userAgent) && + !/Chrom(e|ium)\//.test(navigator.userAgent); + if (!isSafari || !indexedDB.databases) + return Promise.resolve(); + var intervalId; + return new Promise(function (resolve) { + var tryIdb = function () { return indexedDB.databases().finally(resolve); }; + intervalId = setInterval(tryIdb, 100); + tryIdb(); + }).finally(function () { return clearInterval(intervalId); }); +} + +function dexieOpen(db) { + const state = db._state; + const { indexedDB } = db._deps; + if (state.isBeingOpened || db.idbdb) + return state.dbReadyPromise.then(() => state.dbOpenError ? + rejection(state.dbOpenError) : + db); + debug && (state.openCanceller._stackHolder = getErrorWithStack()); + state.isBeingOpened = true; + state.dbOpenError = null; + state.openComplete = false; + const openCanceller = state.openCanceller; + function throwIfCancelled() { + if (state.openCanceller !== openCanceller) + throw new exceptions.DatabaseClosed('db.open() was cancelled'); + } + let resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null, wasCreated = false; + const tryOpenDB = () => new DexiePromise((resolve, reject) => { + throwIfCancelled(); + if (!indexedDB) + throw new exceptions.MissingAPI(); + const dbName = db.name; + const req = state.autoSchema ? + indexedDB.open(dbName) : + indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI(); + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(db._fireOnBlocked); + req.onupgradeneeded = wrap(e => { + upgradeTransaction = req.transaction; + if (state.autoSchema && !db._options.allowEmptyDB) { + req.onerror = preventDefault; + upgradeTransaction.abort(); + req.result.close(); + const delreq = indexedDB.deleteDatabase(dbName); + delreq.onsuccess = delreq.onerror = wrap(() => { + reject(new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`)); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; + wasCreated = oldVer < 1; + db._novip.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(() => { + upgradeTransaction = null; + const idbdb = db._novip.idbdb = req.result; + const objectStoreNames = slice(idbdb.objectStoreNames); + if (objectStoreNames.length > 0) + try { + const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); + if (state.autoSchema) + readGlobalSchema(db, idbdb, tmpTrans); + else { + adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); + if (!verifyInstalledSchema(db, tmpTrans)) { + console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`); + } + } + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(ev => { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + idbdb.onclose = wrap(ev => { + db.on("close").fire(ev); + }); + if (wasCreated) + _onDatabaseCreated(db._deps, dbName); + resolve(); + }, reject); + }).catch(err => { + if (err && err.name === 'UnknownError' && state.PR1398_maxLoop > 0) { + state.PR1398_maxLoop--; + console.warn('Dexie: Workaround for Chrome UnknownError on open()'); + return tryOpenDB(); + } + else { + return DexiePromise.reject(err); + } + }); + return DexiePromise.race([ + openCanceller, + (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) + ]).then(() => { + throwIfCancelled(); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(() => db.on.ready.fire(db.vip))).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + let remainders = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(() => remainders(db.vip))).then(fireRemainders); + } + }); + }).finally(() => { + state.onReadyBeingFired = null; + state.isBeingOpened = false; + }).then(() => { + return db; + }).catch(err => { + state.dbOpenError = err; + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (_a) { } + if (openCanceller === state.openCanceller) { + db._close(); + } + return rejection(err); + }).finally(() => { + state.openComplete = true; + resolveDbReady(); + }); +} + +function awaitIterator(iterator) { + var callNext = result => iterator.next(result), doThrow = error => iterator.throw(error), onSuccess = step(callNext), onError = step(doThrow); + function step(getNext) { + return (val) => { + var next = getNext(val), value = next.value; + return next.done ? value : + (!value || typeof value.then !== 'function' ? + isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : + value.then(onSuccess, onError)); + }; + } + return step(callNext)(); +} + +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(() => { + const transless = PSD.transless || PSD; + const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); + const zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + trans.idbtrans = parentTransaction.idbtrans; + } + else { + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(() => enterTransactionScope(db, mode, storeNames, null, scopeFunc)); + } + return rejection(ex); + } + } + const scopeFuncIsAsync = isAsyncFunction(scopeFunc); + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + let returnValue; + const promiseFollowed = DexiePromise.follow(() => { + 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(x => trans.active ? + x + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))) + : promiseFollowed.then(() => returnValue)).then(x => { + if (parentTransaction) + trans._resolve(); + return trans._completion.then(() => x); + }).catch(e => { + trans._reject(e); + return rejection(e); + }); + }); +} + +function pad(a, value, count) { + const result = isArray(a) ? a.slice() : [a]; + for (let i = 0; i < count; ++i) + result.push(value); + return result; +} +function createVirtualIndexMiddleware(down) { + return { + ...down, + table(tableName) { + const table = down.table(tableName); + const { schema } = table; + const indexLookup = {}; + const allVirtualIndexes = []; + function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { + const keyPathAlias = getKeyPathAlias(keyPath); + const indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); + const keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; + const isVirtual = keyTail > 0; + const virtualIndex = { + ...lowLevelIndex, + isVirtual, + keyTail, + keyLength, + extractKey: getKeyExtractor(keyPath), + unique: !isVirtual && lowLevelIndex.unique + }; + indexList.push(virtualIndex); + if (!virtualIndex.isPrimaryKey) { + allVirtualIndexes.push(virtualIndex); + } + if (keyLength > 1) { + const virtualKeyPath = keyLength === 2 ? + keyPath[0] : + keyPath.slice(0, keyLength - 1); + addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); + } + indexList.sort((a, b) => a.keyTail - b.keyTail); + return virtualIndex; + } + const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); + indexLookup[":id"] = [primaryKey]; + for (const index of schema.indexes) { + addVirtualIndexes(index.keyPath, 0, index); + } + function findBestIndex(keyPath) { + const 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) { + const index = req.query.index; + return index.isVirtual ? { + ...req, + query: { + index, + range: translateRange(req.query.range, index.keyTail) + } + } : req; + } + const result = { + ...table, + schema: { + ...schema, + primaryKey, + indexes: allVirtualIndexes, + getIndexByKeyPath: findBestIndex + }, + count(req) { + return table.count(translateRequest(req)); + }, + query(req) { + return table.query(translateRequest(req)); + }, + openCursor(req) { + const { keyTail, isVirtual, keyLength } = req.query.index; + 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(cursor.key.slice(0, keyLength) + .concat(req.reverse + ? down.MIN_KEY + : down.MAX_KEY, keyTail)) : + cursor.continue(); + } + const virtualCursor = Object.create(cursor, { + continue: { value: _continue }, + continuePrimaryKey: { + value(key, primaryKey) { + cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); + } + }, + primaryKey: { + get() { + return cursor.primaryKey; + } + }, + key: { + get() { + const key = cursor.key; + return keyLength === 1 ? + key[0] : + key.slice(0, keyLength); + } + }, + value: { + get() { + return cursor.value; + } + } + }); + return virtualCursor; + } + return table.openCursor(translateRequest(req)) + .then(cursor => cursor && createVirtualCursor(cursor)); + } + }; + return result; + } + }; +} +const virtualIndexMiddleware = { + stack: "dbcore", + name: "VirtualIndexMiddleware", + level: 1, + create: createVirtualIndexMiddleware +}; + +function getObjectDiff(a, b, rv, prfx) { + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach((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) { + const apTypeName = toStringTag(ap); + const bpTypeName = toStringTag(bp); + if (apTypeName !== bpTypeName) { + rv[prfx + prop] = b[prop]; + } + else if (apTypeName === 'Object') { + getObjectDiff(ap, bp, rv, prfx + prop + '.'); + } + else if (ap !== bp) { + rv[prfx + prop] = b[prop]; + } + } + else if (ap !== bp) + rv[prfx + prop] = b[prop]; + } + }); + keys(b).forEach((prop) => { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; + } + }); + return rv; +} + +function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); +} + +const hooksMiddleware = { + stack: "dbcore", + name: "HooksMiddleware", + level: 2, + create: (downCore) => ({ + ...downCore, + table(tableName) { + const downTable = downCore.table(tableName); + const { primaryKey } = downTable.schema; + const tableMiddleware = { + ...downTable, + mutate(req) { + const dxTrans = PSD.trans; + const { deleting, creating, updating } = dxTrans.table(tableName).hook; + switch (req.type) { + case 'add': + if (creating.fire === nop) + break; + return dxTrans._promise('readwrite', () => addPutOrDelete(req), true); + case 'put': + if (creating.fire === nop && updating.fire === nop) + break; + return dxTrans._promise('readwrite', () => addPutOrDelete(req), true); + case 'delete': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', () => addPutOrDelete(req), true); + case 'deleteRange': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', () => deleteRange(req), true); + } + return downTable.mutate(req); + function addPutOrDelete(req) { + const dxTrans = PSD.trans; + const keys = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? + { ...req, keys } : + { ...req }; + if (req.type !== 'delete') + req.values = [...req.values]; + if (req.keys) + req.keys = [...req.keys]; + return getExistingValues(downTable, req, keys).then(existingValues => { + const contexts = keys.map((key, i) => { + const existingValue = existingValues[i]; + const ctx = { onerror: null, onsuccess: null }; + if (req.type === 'delete') { + deleting.fire.call(ctx, key, existingValue, dxTrans); + } + else if (req.type === 'add' || existingValue === undefined) { + const 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 { + const objectDiff = getObjectDiff(existingValue, req.values[i]); + const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); + if (additionalChanges) { + const requestedValue = req.values[i]; + Object.keys(additionalChanges).forEach(keyPath => { + if (hasOwn(requestedValue, keyPath)) { + requestedValue[keyPath] = additionalChanges[keyPath]; + } + else { + setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]); + } + }); + } + } + return ctx; + }); + return downTable.mutate(req).then(({ failures, results, numFailures, lastResult }) => { + for (let i = 0; i < keys.length; ++i) { + const primKey = results ? results[i] : keys[i]; + const 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, results, numFailures, lastResult }; + }).catch(error => { + contexts.forEach(ctx => 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, values: false, query: { index: primaryKey, range }, limit }) + .then(({ result }) => { + return addPutOrDelete({ type: 'delete', keys: result, trans }).then(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, { ...range, lower: result[result.length - 1], lowerOpen: true }, limit); + } + }); + }); + } + } + }; + return tableMiddleware; + }, + }) +}; +function getExistingValues(table, req, effectiveKeys) { + return req.type === "add" + ? Promise.resolve([]) + : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); +} + +function getFromTransactionCache(keys, cache, clone) { + try { + if (!cache) + return null; + if (cache.keys.length < keys.length) + return null; + const result = []; + for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { + if (cmp(cache.keys[i], keys[j]) !== 0) + continue; + result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); + ++j; + } + return result.length === keys.length ? result : null; + } + catch (_a) { + return null; + } +} +const cacheExistingValuesMiddleware = { + stack: "dbcore", + level: -1, + create: (core) => { + return { + table: (tableName) => { + const table = core.table(tableName); + return { + ...table, + getMany: (req) => { + if (!req.cache) { + return table.getMany(req); + } + const cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); + if (cachedResult) { + return DexiePromise.resolve(cachedResult); + } + return table.getMany(req).then((res) => { + req.trans["_cache"] = { + keys: req.keys, + values: req.cache === "clone" ? deepClone(res) : res, + }; + return res; + }); + }, + mutate: (req) => { + if (req.type !== "add") + req.trans["_cache"] = null; + return table.mutate(req); + }, + }; + }, + }; + }, +}; + +function isEmptyRange(node) { + return !("from" in node); +} +const RangeSet = function (fromOrTree, to) { + if (this) { + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + const rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } +}; +props(RangeSet.prototype, { + add(rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey(key) { + addRange(this, key, key); + return this; + }, + addKeys(keys) { + keys.forEach(key => addRange(this, key, key)); + return this; + }, + [iteratorSymbol]() { + return getRangeSetIterator(this); + } +}); +function addRange(target, from, to) { + const diff = cmp(from, to); + if (isNaN(diff)) + return; + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from, to, d: 1 }); + const left = target.l; + const right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from, to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from, to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; + target.d = right ? right.d + 1 : 1; + } + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; + target.d = target.l ? target.l.d + 1 : 1; + } + const rightWasCutOff = !target.r; + if (left && !target.l) { + mergeRanges(target, left); + } + if (right && rightWasCutOff) { + mergeRanges(target, right); + } +} +function mergeRanges(target, newSet) { + function _addRangeSet(target, { from, to, l, r }) { + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); +} +function rangesOverlap(rangeSet1, rangeSet2) { + const i1 = getRangeSetIterator(rangeSet2); + let nextResult1 = i1.next(); + if (nextResult1.done) + return false; + let a = nextResult1.value; + const i2 = getRangeSetIterator(rangeSet1); + let nextResult2 = i2.next(a.from); + let b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) + : (b = (nextResult2 = i2.next(a.from)).value); + } + return false; +} +function getRangeSetIterator(node) { + let state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next(key) { + const keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + case 1: + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + if (state.n.r) { + state.s = 3; + state = { up: state, n: state.n.r, s: 0 }; + continue; + } + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; +} +function rebalance(target) { + var _a, _b; + const diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + const r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + const l = r === "r" ? "l" : "r"; + const rootClone = { ...target }; + const oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); +} +function computeDepth({ r, l }) { + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; +} + +const observabilityMiddleware = { + stack: "dbcore", + level: 0, + create: (core) => { + const dbName = core.schema.name; + const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); + return { + ...core, + table: (tableName) => { + const table = core.table(tableName); + const { schema } = table; + const { primaryKey } = schema; + const { extractKey, outbound } = primaryKey; + const tableClone = { + ...table, + mutate: (req) => { + const trans = req.trans; + const mutatedParts = trans.mutatedParts || (trans.mutatedParts = {}); + const getRangeSet = (indexName) => { + const part = `idb://${dbName}/${tableName}/${indexName}`; + return (mutatedParts[part] || + (mutatedParts[part] = new RangeSet())); + }; + const pkRangeSet = getRangeSet(""); + const delsRangeSet = getRangeSet(":dels"); + const { type } = req; + let [keys, newObjs] = req.type === "deleteRange" + ? [req.range] + : req.type === "delete" + ? [req.keys] + : req.values.length < 50 + ? [[], req.values] + : []; + const oldCache = req.trans["_cache"]; + return table.mutate(req).then((res) => { + if (isArray(keys)) { + if (type !== "delete") + keys = res.results; + pkRangeSet.addKeys(keys); + const oldObjs = getFromTransactionCache(keys, oldCache); + if (!oldObjs && type !== "add") { + delsRangeSet.addKeys(keys); + } + if (oldObjs || newObjs) { + trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); + } + } + else if (keys) { + const range = { from: keys.lower, to: keys.upper }; + delsRangeSet.add(range); + pkRangeSet.add(range); + } + else { + pkRangeSet.add(FULL_RANGE); + delsRangeSet.add(FULL_RANGE); + schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE)); + } + return res; + }); + }, + }; + const getRange = ({ query: { index, range }, }) => { + var _a, _b; + return [ + index, + new RangeSet((_a = range.lower) !== null && _a !== void 0 ? _a : core.MIN_KEY, (_b = range.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY), + ]; + }; + const readSubscribers = { + get: (req) => [primaryKey, new RangeSet(req.key)], + getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)], + count: getRange, + query: getRange, + openCursor: getRange, + }; + keys(readSubscribers).forEach(method => { + tableClone[method] = function (req) { + const { subscr } = PSD; + if (subscr) { + const getRangeSet = (indexName) => { + const part = `idb://${dbName}/${tableName}/${indexName}`; + return (subscr[part] || + (subscr[part] = new RangeSet())); + }; + const pkRangeSet = getRangeSet(""); + const delsRangeSet = getRangeSet(":dels"); + const [queriedIndex, queriedRanges] = readSubscribers[method](req); + getRangeSet(queriedIndex.name || "").add(queriedRanges); + if (!queriedIndex.isPrimaryKey) { + if (method === "count") { + delsRangeSet.add(FULL_RANGE); + } + else { + const keysPromise = method === "query" && + outbound && + req.values && + table.query({ + ...req, + values: false, + }); + return table[method].apply(this, arguments).then((res) => { + if (method === "query") { + if (outbound && req.values) { + return keysPromise.then(({ result: resultingKeys }) => { + pkRangeSet.addKeys(resultingKeys); + return res; + }); + } + const pKeys = req.values + ? res.result.map(extractKey) + : res.result; + if (req.values) { + pkRangeSet.addKeys(pKeys); + } + else { + delsRangeSet.addKeys(pKeys); + } + } + else if (method === "openCursor") { + const cursor = res; + const wantValues = req.values; + return (cursor && + Object.create(cursor, { + key: { + get() { + delsRangeSet.addKey(cursor.primaryKey); + return cursor.key; + }, + }, + primaryKey: { + get() { + const pkey = cursor.primaryKey; + delsRangeSet.addKey(pkey); + return pkey; + }, + }, + value: { + get() { + wantValues && pkRangeSet.addKey(cursor.primaryKey); + return cursor.value; + }, + }, + })); + } + return res; + }); + } + } + } + return table[method].apply(this, arguments); + }; + }); + return tableClone; + }, + }; + }, +}; +function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { + function addAffectedIndex(ix) { + const rangeSet = getRangeSet(ix.name || ""); + function extractKey(obj) { + return obj != null ? ix.extractKey(obj) : null; + } + const addKeyOrKeys = (key) => ix.multiEntry && isArray(key) + ? key.forEach(key => rangeSet.addKey(key)) + : rangeSet.addKey(key); + (oldObjs || newObjs).forEach((_, i) => { + const oldKey = oldObjs && extractKey(oldObjs[i]); + const newKey = newObjs && extractKey(newObjs[i]); + if (cmp(oldKey, newKey) !== 0) { + if (oldKey != null) + addKeyOrKeys(oldKey); + if (newKey != null) + addKeyOrKeys(newKey); + } + }); + } + schema.indexes.forEach(addAffectedIndex); +} + +class Dexie$1 { + constructor(name, options) { + this._middlewares = {}; + this.verno = 0; + const deps = Dexie$1.dependencies; + this._options = options = { + addons: Dexie$1.addons, + autoOpen: true, + indexedDB: deps.indexedDB, + IDBKeyRange: deps.IDBKeyRange, + ...options + }; + this._deps = { + indexedDB: options.indexedDB, + IDBKeyRange: options.IDBKeyRange + }; + const { addons, } = options; + this._dbSchema = {}; + this._versions = []; + this._storeNames = []; + this._allTables = {}; + this.idbdb = null; + this._novip = this; + const state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true, + PR1398_maxLoop: 3 + }; + state.dbReadyPromise = new DexiePromise(resolve => { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise((_, reject) => { + state.cancelOpen = reject; + }); + this._state = state; + this.name = name; + this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => { + return (subscriber, bSticky) => { + Dexie$1.vip(() => { + const 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); + const db = this; + if (!bSticky) + subscribe(function unsubscribe() { + db.on.ready.unsubscribe(subscriber); + db.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", 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", 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 = (mode, storeNames, dbschema, parentTransaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction); + this._fireOnBlocked = ev => { + this.on("blocked").fire(ev); + connections + .filter(c => c.name === this.name && c !== this && !c._state.vcFired) + .map(c => c.on("versionchange").fire(ev)); + }; + this.use(virtualIndexMiddleware); + this.use(hooksMiddleware); + this.use(observabilityMiddleware); + this.use(cacheExistingValuesMiddleware); + this.vip = Object.create(this, { _vip: { value: true } }); + addons.forEach(addon => addon(this)); + } + version(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); + const versions = this._versions; + var versionInstance = versions.filter(v => 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; + } + _whenReady(fn) { + return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise((resolve, reject) => { + if (this._state.openComplete) { + return reject(new exceptions.DatabaseClosed(this._state.dbOpenError)); + } + 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); + } + use({ stack, create, level, name }) { + if (name) + this.unuse({ stack, name }); + const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); + middlewares.push({ stack, create, level: level == null ? 10 : level, name }); + middlewares.sort((a, b) => a.level - b.level); + return this; + } + unuse({ stack, name, create }) { + if (stack && this._middlewares[stack]) { + this._middlewares[stack] = this._middlewares[stack].filter(mw => create ? mw.create !== create : + name ? mw.name !== name : + false); + } + return this; + } + open() { + return dexieOpen(this); + } + _close() { + const state = this._state; + const idx = connections.indexOf(this); + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this._novip.idbdb = null; + } + state.dbReadyPromise = new DexiePromise(resolve => { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise((_, reject) => { + state.cancelOpen = reject; + }); + } + close() { + this._close(); + const state = this._state; + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + } + delete() { + const hasArguments = arguments.length > 0; + const state = this._state; + return new DexiePromise((resolve, reject) => { + const doDelete = () => { + this.close(); + var req = this._deps.indexedDB.deleteDatabase(this.name); + req.onsuccess = wrap(() => { + _onDatabaseDeleted(this._deps, 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(); + } + }); + } + backendDB() { + return this.idbdb; + } + isOpen() { + return this.idbdb !== null; + } + hasBeenClosed() { + const dbOpenError = this._state.dbOpenError; + return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); + } + hasFailed() { + return this._state.dbOpenError !== null; + } + dynamicallyOpened() { + return this._state.autoSchema; + } + get tables() { + return keys(this._allTables).map(name => this._allTables[name]); + } + transaction() { + const args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + } + _transaction(mode, tables, scopeFunc) { + let parentTransaction = PSD.trans; + if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) + parentTransaction = null; + const onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); + let idbMode, storeNames; + try { + storeNames = tables.map(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(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, (_, reject) => { reject(e); }) : + rejection(e); + } + const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); + return (parentTransaction ? + parentTransaction._promise(idbMode, enterTransaction, "lock") : + PSD.trans ? + usePSD(PSD.transless, () => this._whenReady(enterTransaction)) : + this._whenReady(enterTransaction)); + } + table(tableName) { + if (!hasOwn(this._allTables, tableName)) { + throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); + } + return this._allTables[tableName]; + } +} + +const symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol + ? Symbol.observable + : "@@observable"; +class Observable { + constructor(subscribe) { + this._subscribe = subscribe; + } + subscribe(x, error, complete) { + return this._subscribe(!x || typeof x === "function" ? { next: x, error, complete } : x); + } + [symbolObservable]() { + return this; + } +} + +function extendObservabilitySet(target, newSet) { + keys(newSet).forEach(part => { + const rangeSet = target[part] || (target[part] = new RangeSet()); + mergeRanges(rangeSet, newSet[part]); + }); + return target; +} + +function liveQuery(querier) { + let hasValue = false; + let currentValue = undefined; + const observable = new Observable((observer) => { + const scopeFuncIsAsync = isAsyncFunction(querier); + function execute(subscr) { + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + const exec = () => newScope(querier, { subscr, trans: null }); + const rv = PSD.trans + ? + usePSD(PSD.transless, exec) + : exec(); + if (scopeFuncIsAsync) { + rv.then(decrementExpectedAwaits, decrementExpectedAwaits); + } + return rv; + } + let closed = false; + let accumMuts = {}; + let currentObs = {}; + const subscription = { + get closed() { + return closed; + }, + unsubscribe: () => { + closed = true; + globalEvents.storagemutated.unsubscribe(mutationListener); + }, + }; + observer.start && observer.start(subscription); + let querying = false, startedListening = false; + function shouldNotify() { + return keys(currentObs).some((key) => accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key])); + } + const mutationListener = (parts) => { + extendObservabilitySet(accumMuts, parts); + if (shouldNotify()) { + doQuery(); + } + }; + const doQuery = () => { + if (querying || closed) + return; + accumMuts = {}; + const subscr = {}; + const ret = execute(subscr); + if (!startedListening) { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); + startedListening = true; + } + querying = true; + Promise.resolve(ret).then((result) => { + hasValue = true; + currentValue = result; + querying = false; + if (closed) + return; + if (shouldNotify()) { + doQuery(); + } + else { + accumMuts = {}; + currentObs = subscr; + observer.next && observer.next(result); + } + }, (err) => { + querying = false; + hasValue = false; + observer.error && observer.error(err); + subscription.unsubscribe(); + }); + }; + doQuery(); + return subscription; + }); + observable.hasValue = () => hasValue; + observable.getValue = () => currentValue; + return observable; +} + +let domDeps; +try { + domDeps = { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; +} +catch (e) { + domDeps = { indexedDB: null, IDBKeyRange: null }; +} + +const Dexie = Dexie$1; +props(Dexie, { + ...fullNameExceptions, + delete(databaseName) { + const db = new Dexie(databaseName, { addons: [] }); + return db.delete(); + }, + exists(name) { + return new Dexie(name, { addons: [] }).open().then(db => { + db.close(); + return true; + }).catch('NoSuchDatabaseError', () => false); + }, + getDatabaseNames(cb) { + try { + return getDatabaseNames(Dexie.dependencies).then(cb); + } + catch (_a) { + return rejection(new exceptions.MissingAPI()); + } + }, + defineClass() { + function Class(content) { + extend(this, content); + } + return Class; + }, + ignoreTransaction(scopeFunc) { + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : + scopeFunc(); + }, + 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: () => PSD.trans || null + }, + waitFor: function (promiseOrFunction, optionalTimeout) { + const promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? + Dexie.ignoreTransaction(promiseOrFunction) : + promiseOrFunction) + .timeout(optionalTimeout || 60000); + return PSD.trans ? + PSD.trans.waitFor(promise) : + promise; + }, + Promise: DexiePromise, + debug: { + get: () => debug, + set: value => { + setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter); + } + }, + derive: derive, + extend: extend, + props: props, + override: override, + Events: Events, + on: globalEvents, + liveQuery, + extendObservabilitySet, + getByKeyPath: getByKeyPath, + setByKeyPath: setByKeyPath, + delByKeyPath: delByKeyPath, + shallowClone: shallowClone, + deepClone: deepClone, + getObjectDiff: getObjectDiff, + cmp, + asap: asap$1, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: domDeps, + semVer: DEXIE_VERSION, + version: DEXIE_VERSION.split('.') + .map(n => parseInt(n)) + .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))), +}); +Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); + +if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => { + if (!propagatingLocally) { + let event; + if (isIEOrEdge) { + event = document.createEvent('CustomEvent'); + event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts); + } + else { + event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { + detail: updatedParts + }); + } + propagatingLocally = true; + dispatchEvent(event); + propagatingLocally = false; + } + }); + addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({ detail }) => { + if (!propagatingLocally) { + propagateLocally(detail); + } + }); +} +function propagateLocally(updateParts) { + let wasMe = propagatingLocally; + try { + propagatingLocally = true; + globalEvents.storagemutated.fire(updateParts); + } + finally { + propagatingLocally = wasMe; + } +} +let propagatingLocally = false; + +if (typeof BroadcastChannel !== 'undefined') { + const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); + if (typeof bc.unref === 'function') { + bc.unref(); + } + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => { + if (!propagatingLocally) { + bc.postMessage(changedParts); + } + }); + bc.onmessage = (ev) => { + if (ev.data) + propagateLocally(ev.data); + }; +} +else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => { + try { + if (!propagatingLocally) { + if (typeof localStorage !== 'undefined') { + localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({ + trig: Math.random(), + changedParts, + })); + } + if (typeof self['clients'] === 'object') { + [...self['clients'].matchAll({ includeUncontrolled: true })].forEach((client) => client.postMessage({ + type: STORAGE_MUTATED_DOM_EVENT_NAME, + changedParts, + })); + } + } + } + catch (_a) { } + }); + if (typeof addEventListener !== 'undefined') { + addEventListener('storage', (ev) => { + if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) { + const data = JSON.parse(ev.newValue); + if (data) + propagateLocally(data.changedParts); + } + }); + } + const swContainer = self.document && navigator.serviceWorker; + if (swContainer) { + swContainer.addEventListener('message', propagateMessageLocally); + } +} +function propagateMessageLocally({ data }) { + if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) { + propagateLocally(data.changedParts); + } +} + +DexiePromise.rejectionMapper = mapError; +setDebug(debug, dexieStackFrameFilter); + +export { Dexie$1 as Dexie, RangeSet, Dexie$1 as default, liveQuery, mergeRanges, rangesOverlap }; +//# sourceMappingURL=dexie.mjs.map diff --git a/dist/modern/dexie.mjs.map b/dist/modern/dexie.mjs.map new file mode 100644 index 000000000..a9acd4619 --- /dev/null +++ b/dist/modern/dexie.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.mjs","sources":["../../src/globals/global.ts","../../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/functions/workaround-undefined-primkey.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/functions/cmp.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/event-wrappers.ts","../../src/globals/global-events.ts","../../src/classes/transaction/transaction.ts","../../src/classes/transaction/transaction-constructor.ts","../../src/helpers/index-spec.ts","../../src/helpers/table-schema.ts","../../src/functions/quirks.ts","../../src/dbcore/get-key-extractor.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","../../node_modules/safari-14-idb-fix/dist/index.js","../../src/classes/dexie/dexie-open.ts","../../src/helpers/yield-support.ts","../../src/classes/dexie/transaction-helpers.ts","../../src/dbcore/virtual-index-middleware.ts","../../src/functions/get-object-diff.ts","../../src/dbcore/get-effective-keys.ts","../../src/hooks/hooks-middleware.ts","../../src/dbcore/cache-existing-values-middleware.ts","../../src/helpers/rangeset.ts","../../src/live-query/observability-middleware.ts","../../src/classes/dexie/dexie.ts","../../src/classes/observable/observable.ts","../../src/live-query/extend-observability-set.ts","../../src/live-query/live-query.ts","../../src/classes/dexie/dexie-dom-dependencies.ts","../../src/classes/dexie/dexie-static-props.ts","../../src/live-query/propagate-locally.ts","../../src/live-query/enable-broadcast.ts","../../src/index.ts"],"sourcesContent":["declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n","import { _global } from \"../globals/global\";\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\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: T, extension: X): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\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 (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(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: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} {\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 (typeof keyPath === 'string' && 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 == null ? 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 || !hasOwn(obj, currentKeyPath)) 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 \"BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\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]);\nexport const intrinsicTypeNameSet = arrayToObject(intrinsicTypeNames, x=>[x,true]);\n\nlet circularRefs: null | WeakMap = null;\nexport function deepClone(any: T): T {\n circularRefs = typeof WeakMap !== 'undefined' && new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone(any: T): T {\n if (!any || typeof any !== 'object') return any;\n let rv = circularRefs && circularRefs.get(any); // Resolve circular references\n if (rv) return rv;\n if (isArray(any)) {\n rv = [];\n circularRefs && circularRefs.set(any, rv);\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(innerDeepClone(any[i]));\n }\n } else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n } else {\n const proto = getProto(any);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs && circularRefs.set(any, rv);\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = innerDeepClone(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\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nexport const getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nexport const asyncIteratorSymbol = typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\")\n : '@asyncIterator';\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 https://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 MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\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 = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = 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 { _global } from '../globals/global';\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend, getProto} 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, getProto(globalP), 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 getProto(nativeP),\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 const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\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() {\n if (!task.awaits) return false;\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 return true;\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, cleanup) {\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 if (cleanup) enqueueNativeMicroTask(decrementExpectedAwaits);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone),\n nativeAwaitCompatibleWrap(onRejected, zone));\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 { errnames, 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.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\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 {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(()=>tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\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: [[]],\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 { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(keyPath: string | ArrayLike) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === \"string\" && !/\\./.test(keyPath) \n ? (obj: object) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\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';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\n\n/** class Table\n * \n * https://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 * https://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 * https://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 if (\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {\n for (let i=0; i a.keyPath.length - b.keyPath.length)[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 const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));\n }\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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * https://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 * https://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * https://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\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 // object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly.\n try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }\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 * https://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * https://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 * https://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 * https://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 * https://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 {auto, keyPath} = this.schema.primKey;\n if (keyPath && 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 let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, 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`, failures);\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * https://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 {auto, keyPath} = this.schema.primKey;\n if (keyPath && 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 let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, 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`, failures);\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * https://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","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(\n a: Uint8Array,\n b: Uint8Array\n) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\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';\nimport { cmp } from \"../../functions/cmp\";\n\n/** class Collection\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * https://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 * https://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 = this.db._options.modifyChunkSize || 200;\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({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\" // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n }).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(()=>(putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>(deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\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 * https://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(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => ctx.value = null;\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 * https://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 * https://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 * https://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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 * https://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();\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 { 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 Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME) as GlobalDexieEvents;\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';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n * \n * https://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: ChromeTransactionDurability;\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 ||\n (this.db.core \n ? this.db.core.transaction(this.storeNames, this.mode as 'readwrite' | 'readonly', { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n ) as IDBTransaction;\n\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 if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\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(): https://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 * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n * \n * https://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 chromeTransactionDurability: ChromeTransactionDurability,\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 chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\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 { 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 let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\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 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';\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 IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\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}) {\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 let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n \n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\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 reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()\n else\n reqs.push(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 reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\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 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, 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({_novip: 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 { _global } from \"../../globals/global\";\nimport { setProp, keys, slice, isArray, shallowClone, isAsyncFunction, defineProperty, getPropertyDescriptor } 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({_novip: db}: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\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({_novip: 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 {_novip: 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 trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\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 (\n (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n ''+(oldDef.primKey.keyPath||'')\n ) !== (\n ''+(newDef.primKey.keyPath||'')\n ) ||\n // Compare the autoIncrement flag also\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) // IE has bug reading autoIncrement prop.\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 [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\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({_novip: 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 verifyInstalledSchema(db: Dexie, tmpTrans: IDBTransaction): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\n\nexport function adjustToExistingIndexNames({_novip: 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';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\n\n/** class Version\n *\n * https://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 | null; }): 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 = promisableChain(this._cfg.contentUpgrade || nop, 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 { Dexie } from \"../classes/dexie/dexie\";\nimport { Table } from \"../public/types/table\";\nimport { DBNAMES_DB } from \"../globals/constants\";\nimport { DexieDOMDependencies } from \"../public/types/dexie-dom-dependencies\";\nimport { nop } from \"../functions/chaining-functions\";\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\") as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n 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 : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({name}).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\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","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\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, verifyInstalledSchema } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } 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';\nimport safari14Workaround from 'safari-14-idb-fix';\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 const openCanceller = state.openCanceller;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller) throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\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 wasCreated = false;\n\n const tryOpenDB = () => 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 throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\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(); // 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 wasCreated = oldVer < 1;\n db._novip.idbdb = req.result;// db._novip is because db can be an Object.create(origDb).\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._novip.idbdb = req.result; // db._novip is because db can be an Object.create(origDb).\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 {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\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 idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n\n }, reject);\n }).catch(err => {\n if (err && err.name === 'UnknownError' && state.PR1398_maxLoop > 0) {\n // Bug in Chrome after clearing site data\n // https://github.com/dexie/Dexie.js/issues/543#issuecomment-1795736695\n state.PR1398_maxLoop--;\n console.warn('Dexie: Workaround for Chrome UnknownError on open()');\n return tryOpenDB();\n } else {\n return Promise.reject(err);\n }\n });\n \n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([\n openCanceller,\n (typeof navigator === 'undefined' ? Promise.resolve() : safari14Workaround()).then(tryOpenDB)\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 throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>db.on.ready.fire(db.vip))).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(db.vip))).then(fireRemainders)\n }\n });\n }).finally(()=>{\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n return db;\n }).catch(err => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\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 { }\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection (err);\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 { errnames, 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 try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(\n db,\n mode,\n storeNames,\n null,\n scopeFunc\n ));\n }\n return rejection(ex);\n }\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 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(\n cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)\n ) :\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 primaryKey: {\n get() {\n return cursor.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 { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\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 // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) 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","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","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 { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from \"../functions/get-object-diff\";\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } 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} :\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 if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] = additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\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\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n","import { deepClone } from \"../functions/utils\";\nimport { DBCore } from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport Promise from \"../helpers/promise\";\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans[\"_cache\"],\n req.cache === \"clone\"\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== \"add\") req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { cmp } from \"../functions/cmp\";\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from \"../public/types/rangeset\";\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n * \n */\n\nfunction isEmptyRange(node: IntervalTree | {from: IndexableType, to: IndexableType}): node is EmptyRange {\n return !(\"from\" in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function(fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(this, arguments.length ? {d:1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree} : {d:0});\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n\n [iteratorSymbol](): Iterator {\n return getRangeSetIterator(this);\n }\n});\n\nfunction addRange(target: IntervalTree, from: IndexableType, to: IndexableType) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n \n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(target: IntervalTree, newSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n function _addRangeSet(\n target: IntervalTree,\n { from, to, l, r }: IntervalTreeNode | {from: IndexableType, to: IndexableType, l?: undefined, r?: undefined}\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if(!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator {\n let state: RangeSetIteratorState = isEmptyRange(node) ? null : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n // \n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n // \n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L] \n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === \"r\" ? \"l\" : \"r\"; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r]; \n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import { getFromTransactionCache } from \"../dbcore/cache-existing-values-middleware\";\nimport { cmp } from \"../functions/cmp\";\nimport { isArray, keys } from \"../functions/utils\";\nimport { PSD } from \"../helpers/promise\";\nimport { RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\n\nexport const observabilityMiddleware: Middleware = {\n stack: \"dbcore\",\n level: 0,\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts =\n trans.mutatedParts || (trans.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === \"deleteRange\"\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === \"delete\"\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [[], req.values] // keys = empty array - will be resolved in mutate().then(...).\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n const oldCache = req.trans[\"_cache\"];\n return table.mutate(req).then((res) => {\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n if (type !== \"delete\") keys = res.results;\n // individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs = getFromTransactionCache(keys, oldCache);\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs && type !== \"add\") {\n // delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(range.lower ?? core.MIN_KEY, range.upper ?? core.MAX_KEY),\n ];\n\n const readSubscribers: {[method in\n Exclude]: \n (req: any) => [DBCoreIndex, RangeSet]\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n }\n\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD;\n if (subscr) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (subscr[part] ||\n (subscr[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === \"count\") {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === \"query\" &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({ result: resultingKeys }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === \"openCursor\") {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest).values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: any[] | undefined,\n newObjs: any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) => ix.multiEntry && isArray(key)\n // multiEntry and the old property was an array - add each array entry to the rangeSet:\n ? key.forEach(key => rangeSet.addKey(key))\n // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n : rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\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 { _onDatabaseDeleted } 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';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\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 PR1398_maxLoop?: number;\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 _vip?: boolean;\n _novip?: Dexie;// db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\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 this._novip = this;\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 PR1398_maxLoop: 3\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\", \"close\", { 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, this._options.chromeTransactionDurability, 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 this.use(observabilityMiddleware);\n this.use(cacheExistingValuesMiddleware);\n\n this.vip = Object.create(this, {_vip: {value: true}}) as Dexie;\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.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\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 state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this._novip.idbdb = null; // db._novip is because db can be an Object.create(origDb).\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 close(): void {\n this._close();\n const state = this._state;\n this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\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 _onDatabaseDeleted(this._deps, 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 {\n Observable as IObservable,\n Observer,\n Subscription,\n} from \"../../public/types/observable\";\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\" as any;\n\nexport class Observable implements IObservable {\n private _subscribe: (observer: Observer) => Subscription;\n hasValue?: ()=>boolean;\n getValue?: ()=>T;\n\n constructor(subscribe: (observer: Observer) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === \"function\" ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { deepClone, keys } from \"../functions/utils\";\nimport { mergeRanges, RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach(part => {\n const rangeSet = target[part] || (target[part] = new RangeSet());\n mergeRanges(rangeSet, newSet[part]);\n });\n return target;\n}\n","import { isAsyncFunction, keys } from \"../functions/utils\";\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME } from \"../globals/global-events\";\nimport {\n decrementExpectedAwaits,\n incrementExpectedAwaits,\n newScope,\n PSD,\n usePSD,\n} from \"../helpers/promise\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n Observable as IObservable,\n Subscription,\n} from \"../public/types/observable\";\nimport { Observable } from \"../classes/observable/observable\";\nimport { extendObservabilitySet } from \"./extend-observability-set\";\nimport { rangesOverlap } from \"../helpers/rangeset\";\n\nexport function liveQuery(querier: () => T | Promise): IObservable {\n let hasValue = false;\n let currentValue: T = undefined as any;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(subscr: ObservabilitySet) {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const exec = () => newScope(querier, { subscr, trans: null });\n const rv = PSD.trans\n ? // Ignore current transaction if active when calling subscribe().\n usePSD(PSD.transless, exec)\n : exec();\n if (scopeFuncIsAsync) {\n (rv as Promise).then(\n decrementExpectedAwaits,\n decrementExpectedAwaits\n );\n }\n return rv;\n }\n\n let closed = false;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n closed = true;\n globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let querying = false,\n startedListening = false;\n\n function shouldNotify() {\n return keys(currentObs).some(\n (key) =>\n accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key])\n );\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const doQuery = () => {\n if (querying || closed) return;\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n const ret = execute(subscr);\n if (!startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n }\n querying = true;\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n querying = false;\n if (closed) return;\n if (shouldNotify()) {\n // Mutations has happened while we were querying. Redo query.\n doQuery();\n } else {\n accumMuts = {};\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n observer.next && observer.next(result);\n }\n },\n (err) => {\n querying = false;\n hasValue = false;\n observer.error && observer.error(err);\n subscription.unsubscribe();\n }\n );\n };\n\n doQuery();\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies\n\ntry {\n domDeps = {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, asap } from '../../functions/utils';\nimport { getObjectDiff } from \"../../functions/get-object-diff\";\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } 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';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\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, {addons: []});\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 try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\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 on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\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: domDeps,\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, // Commented because solved in index-umd.ts instead.\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 // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { isIEOrEdge } from '../globals/constants';\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME, STORAGE_MUTATED_DOM_EVENT_NAME } from '../globals/global-events';\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event: CustomEvent;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n } else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({detail}: CustomEvent) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\n\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n globalEvents.storagemutated.fire(updateParts);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n } \n \n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n bc.onmessage = (ev) => {\n if (ev.data) propagateLocally(ev.data);\n };\n} else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n // DOM verified - when typeof self !== \"undefined\", we are a window or worker. Not a Node process.\n\n //\n // Propagate local changes to remote tabs/windows via storage event and service worker\n // via messages. We have this code here because of https://bugs.webkit.org/show_bug.cgi?id=161472.\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n // We're a browsing window or tab. Propagate to other windows/tabs via storage event:\n localStorage.setItem(\n STORAGE_MUTATED_DOM_EVENT_NAME,\n JSON.stringify({\n trig: Math.random(),\n changedParts,\n })\n );\n }\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n })\n );\n }\n }\n } catch {}\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev: StorageEvent) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data) propagateLocally(data.changedParts);\n }\n });\n }\n\n //\n // Propagate messages from service worker\n //\n const swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\n if (swContainer) {\n // We're a browser window and want to propagate message from the SW:\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\n\nfunction propagateMessageLocally({ data }: MessageEvent) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\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';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport { liveQuery } from './live-query/live-query';\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 { RangeSet, mergeRanges, rangesOverlap } from \"./helpers/rangeset\";\nexport { Dexie, liveQuery }; // Comply with public/index.d.ts.\nexport default Dexie;\n"],"names":["asap","Promise","Dexie","Debug.debug","Debug.getErrorWithStack","safari14Workaround","_Dexie","Debug.setDebug"],"mappings":";;;;;;;;;;;;;AACO,MAAM,OAAO,GAChB,OAAO,UAAU,KAAK,WAAW,GAAG,UAAU;IAC9C,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI;QAClC,OAAO,MAAM,KAAK,WAAW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AAC,EAAE,mBAAmB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,OAAO,CAClE,CAAC,MAAM,KACL,MAAM,CAAC,WAAW,CAAC;wBACjB,IAAI,EAAE,8BAA8B;wBACpC,YAAY;qBACb,CAAC,CACL,CAAC;iBACH;aACF;SACF;QAAC,WAAM,GAAE;KACX,CAAC,CAAC;IAKH,IAAI,OAAO,gBAAgB,KAAK,WAAW,EAAE;QACzC,gBAAgB,CAAC,SAAS,EAAE,CAAC,EAAgB;YAC7C,IAAI,EAAE,CAAC,GAAG,KAAK,8BAA8B,EAAE;gBAC7C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;gBACrC,IAAI,IAAI;oBAAE,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;aAC/C;SACF,CAAC,CAAC;KACJ;IAKD,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,IAAI,SAAS,CAAC,aAAa,CAAC;IAC7D,IAAI,WAAW,EAAE;QAEf,WAAW,CAAC,gBAAgB,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;KAClE;CACF;AAED,SAAS,uBAAuB,CAAC,EAAE,IAAI,EAAgB;IACrD,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,8BAA8B,EAAE;QACxD,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;KACrC;AACH;;AChFA,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCO,QAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC;;;;"} \ No newline at end of file diff --git a/test/bundle.js b/test/bundle.js new file mode 100644 index 000000000..9d372c792 --- /dev/null +++ b/test/bundle.js @@ -0,0 +1,13346 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('dexie'), require('QUnit')) : + typeof define === 'function' && define.amd ? define(['dexie', 'QUnit'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Dexie, global.QUnit)); +})(this, (function (Dexie, QUnit) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var Dexie__default = /*#__PURE__*/_interopDefaultLegacy(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$1 = function(d, b) { + extendStatics$1 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics$1(d, b); + }; + + function __extends$1(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics$1(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 }; + } + } + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + } + + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + + function fillArrayBuffer(ab, val) { + var view = new Uint8Array(ab); + for (var i = 0; i < view.byteLength; ++i) { + view[i] = val; + } + } + QUnit.module('cmp'); + var cmp$1 = Dexie__default["default"].cmp; + QUnit.test('it should support indexable types', function () { + var e_1, _a; + // numbers + QUnit.ok(cmp$1(1, 1) === 0, 'Equal numbers should return 0'); + QUnit.ok(cmp$1(1, 2) === -1, 'Less than numbers should return -1'); + QUnit.ok(cmp$1(-1, -2000) === 1, 'Greater than numbers should return 1'); + // strings + QUnit.ok(cmp$1('A', 'A') === 0, 'Equal strings should return 0'); + QUnit.ok(cmp$1('A', 'B') === -1, 'Less than strings should return -1'); + QUnit.ok(cmp$1('C', 'A') === 1, 'Greater than strings should return 1'); + // Dates + QUnit.ok(cmp$1(new Date(1), new Date(1)) === 0, 'Equal dates should return 0'); + QUnit.ok(cmp$1(new Date(1), new Date(2)) === -1, 'Less than dates should return -1'); + QUnit.ok(cmp$1(new Date(1000), new Date(500)) === 1, 'Greater than dates should return 1'); + // Arrays + QUnit.ok(cmp$1([1, 2, '3'], [1, 2, '3']) === 0, 'Equal arrays should return 0'); + QUnit.ok(cmp$1([-1], [1]) === -1, 'Less than arrays should return -1'); + QUnit.ok(cmp$1([1], [-1]) === 1, 'Greater than arrays should return 1'); + QUnit.ok(cmp$1([1], [1, 0]) === -1, 'If second array is longer with same leading entries, return -1'); + QUnit.ok(cmp$1([1, 0], [1]) === 1, 'If first array is longer with same leading entries, return 1'); + QUnit.ok(cmp$1([1], [0, 0]) === 1, 'If first array is shorter but has greater leading entries, return 1'); + QUnit.ok(cmp$1([0, 0], [1]) === -1, 'If second array is shorter but has greater leading entries, return -1'); + /* Binary types + | DataView + | Uint8ClampedArray + | Uint8Array + | Int8Array + | Uint16Array + | Int16Array + | Uint32Array + | Int32Array + | Float32Array + | Float64Array; + */ + var viewTypes = [ + 'DataView', + 'Uint8ClampedArray', + 'Uint8Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Int32Array', + 'Float32Array', + 'Float64Array', + ] + .map(function (typeName) { return [typeName, self[typeName]]; }) + .filter(function (_a) { + var _b = __read(_a, 2); _b[0]; var ctor = _b[1]; + return !!ctor; + }); // Don't try to test types not supported by the browser + var zeroes1 = new ArrayBuffer(16); + var zeroes2 = new ArrayBuffer(16); + var ones = new ArrayBuffer(16); + fillArrayBuffer(zeroes1, 0); + fillArrayBuffer(zeroes2, 0); + fillArrayBuffer(ones, 1); + try { + for (var viewTypes_1 = __values(viewTypes), viewTypes_1_1 = viewTypes_1.next(); !viewTypes_1_1.done; viewTypes_1_1 = viewTypes_1.next()) { + var _b = __read(viewTypes_1_1.value, 2), typeName = _b[0], ArrayBufferView = _b[1]; + // Equals + var v1 = new ArrayBufferView(zeroes1); + var v2 = new ArrayBufferView(zeroes2); + QUnit.ok(cmp$1(v1, v2) === 0, "Equal " + typeName + "s should return 0"); + // Less than + v1 = new ArrayBufferView(zeroes1); + v2 = new ArrayBufferView(ones); + QUnit.ok(cmp$1(v1, v2) === -1, "Less than " + typeName + "s should return -1"); + // Less than + v1 = new ArrayBufferView(ones); + v2 = new ArrayBufferView(zeroes1); + QUnit.ok(cmp$1(v1, v2) === 1, "Greater than " + typeName + "s should return 1"); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (viewTypes_1_1 && !viewTypes_1_1.done && (_a = viewTypes_1.return)) _a.call(viewTypes_1); + } + finally { if (e_1) throw e_1.error; } + } + }); + QUnit.test("it should respect IndexedDB's type order", function () { + var zoo = [ + 'meow', + 1, + new Date(), + Infinity, + -Infinity, + new ArrayBuffer(1), + [[]], + ]; + var _a = __read(zoo.sort(cmp$1), 7), minusInfinity = _a[0], num = _a[1], infinity = _a[2], date = _a[3], string = _a[4], binary = _a[5], array = _a[6]; + QUnit.equal(minusInfinity, -Infinity, 'Minus infinity is sorted first'); + QUnit.equal(num, 1, 'Numbers are sorted second'); + QUnit.equal(infinity, Infinity, 'Infinity is sorted third'); + QUnit.ok(date instanceof Date, 'Date is sorted fourth'); + QUnit.ok(typeof string === 'string', 'strings are sorted fifth'); + QUnit.ok(binary instanceof ArrayBuffer, 'binaries are sorted sixth'); + QUnit.ok(Array.isArray(array), 'Arrays are sorted seventh'); + }); + QUnit.test('it should return NaN on invalid types', function () { + QUnit.ok(isNaN(cmp$1(1, { foo: 'bar' })), 'Comparing a number against an object returns NaN (would throw in indexedDB)'); + QUnit.ok(isNaN(cmp$1({ foo: 'bar' }, 1)), 'Comparing an object against a number returns NaN also'); + }); + QUnit.test('it should treat different binary types as if they were equal', function () { + var e_2, _a; + var viewTypes = [ + 'DataView', + 'Uint8ClampedArray', + 'Uint8Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Int32Array', + 'Float32Array', + 'Float64Array', + ] + .map(function (typeName) { return [typeName, self[typeName]]; }) + .filter(function (_a) { + var _b = __read(_a, 2); _b[0]; var ctor = _b[1]; + return !!ctor; + }); // Don't try to test types not supported by the browser + var zeroes1 = new ArrayBuffer(16); + var zeroes2 = new ArrayBuffer(16); + fillArrayBuffer(zeroes1, 0); + fillArrayBuffer(zeroes2, 0); + try { + for (var viewTypes_2 = __values(viewTypes), viewTypes_2_1 = viewTypes_2.next(); !viewTypes_2_1.done; viewTypes_2_1 = viewTypes_2.next()) { + var _b = __read(viewTypes_2_1.value, 2), typeName = _b[0], ArrayBufferView = _b[1]; + var v1 = new ArrayBufferView(zeroes1); + QUnit.ok(cmp$1(v1, zeroes1) === 0, "Comparing " + typeName + " with ArrayBuffer should return 0 if they have identical data"); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (viewTypes_2_1 && !viewTypes_2_1.done && (_a = viewTypes_2.return)) _a.call(viewTypes_2); + } + finally { if (e_2) throw e_2.error; } + } + }); + QUnit.test('it should return NaN if comparing arrays where any item or sub array item includes an invalid key', function () { + QUnit.ok(cmp$1([1, [[2, "3"]]], [1, [[2, "3"]]]) === 0, "It can deep compare arrays with valid keys (equals)"); + QUnit.ok(cmp$1([1, [[2, "3"]]], [1, [[2, 3]]]) === 1, "It can deep compare arrays with valid keys (greater than)"); + QUnit.ok(isNaN(cmp$1([1, [[2, 3]]], [1, [[{ foo: "bar" }, 3]]])), "It returns NaN when any item in the any of the arrays are invalid keys"); + }); + + // 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__default["default"].debug = window.location.search.indexOf('longstacks') !== -1 ? 'dexie' : false; + if (window.location.search.indexOf('longstacks=tests') !== -1) + Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].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 isChrome = !!window.chrome; + 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__default["default"].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__default["default"].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__default["default"].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__default["default"].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$b = new Dexie__default["default"]("TestDBTable"); + db$b.version(1).stores({ + users: "++id,first,last,&username,*&email,*pets", + folks: "++,first,last", + items: "id", + schema: "" // Test issue #1039 + }); + db$b.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String], + }); + var idOfFirstUser = 0, idOfLastUser = 0; + db$b.on("populate", function (trans) { + db$b.users.add({ first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }).then(function (id) { + idOfFirstUser = id; + }); + db$b.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$b).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 updateAssertions, date1, date2, first1, first2, id, obj; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + updateAssertions = 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); + } + }; + db$b.folks.hook("updating", updateAssertions); + 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$b.folks.add({ first: first1, last: "Bar", date: date1 })]; + case 1: + id = _a.sent(); + return [4 /*yield*/, db$b.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$b.folks.put(obj, id)]; + case 3: + _a.sent(); + return [4 /*yield*/, db$b.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"); + db$b.folks.hook("updating").unsubscribe(updateAssertions); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue #966 - put() with dotted field in update hook", function () { return __awaiter(void 0, void 0, void 0, function () { + var updateAssertions, id, obj; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + updateAssertions = function (mods) { + QUnit.equal(mods["nested.field"], "value", "mods.nested.field should contain 'value'"); + QUnit.equal(mods.nested, undefined, "mods.nested field should be empty"); + return __assign({}, mods); + }; + db$b.folks.hook("updating", updateAssertions); + return [4 /*yield*/, db$b.folks.add({ first: "first", last: "last" })]; + case 1: + id = _a.sent(); + return [4 /*yield*/, db$b.folks.put({ first: "first", last: "last", "nested.field": "value" }, id)]; + case 2: + _a.sent(); + return [4 /*yield*/, db$b.folks.get(id)]; + case 3: + obj = _a.sent(); + QUnit.equal(obj["nested.field"], "value", "obj.nested.field should have been successfully updated to 'value'"); + QUnit.equal(obj.nested, undefined, "obj.nested field should have remained undefined"); + db$b.folks.hook("updating").unsubscribe(updateAssertions); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("update array property", function () { return __awaiter(void 0, void 0, void 0, function () { + var obj; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.items.put({ id: 1, foo: [{ bar: 123 }] })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$b.items.update(1, { foo: [{ bar: 222 }] })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$b.items.get(1)]; + case 3: + obj = _a.sent(); + QUnit.equal(JSON.stringify(obj.foo), JSON.stringify([{ bar: 222 }]), "foo har been updated to the new array"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Verify #1130 doesn't break contract of hook('updating')", function () { return __awaiter(void 0, void 0, void 0, function () { + var updateHook, id, foo; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + updateHook = function (mods) { + return { "address.postalCode": 111 }; + }; + _a.label = 1; + case 1: + _a.trys.push([1, , 5, 6]); + return [4 /*yield*/, db$b.folks.add({ + first: "Foo", + last: "Bar", + address: { + city: "Stockholm", + street: "Folkungagatan" + } + })]; + case 2: + id = _a.sent(); + db$b.folks.hook("updating", updateHook); + return [4 /*yield*/, db$b.folks.update(id, { + "address.streetNo": 23 + })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$b.folks.get(id)]; + case 4: + foo = _a.sent(); + QUnit.equal(foo.address.city, "Stockholm", "Correct city Stockholm"); + QUnit.equal(foo.address.street, "Folkungagatan", "Correct street Folkungagatan"); + QUnit.equal(foo.address.streetNo, 23, "Correct streetNo: 23"); + QUnit.equal(foo.address.postalCode, 111, "Hooks should have added postal code"); + return [3 /*break*/, 6]; + case 5: + db$b.folks.hook("updating").unsubscribe(updateHook); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("get", 4, function () { + db$b.table("users").get(idOfFirstUser).then(function (obj) { + QUnit.equal(obj.first, "David", "Got the first object"); + return db$b.users.get(idOfLastUser); + }).then(function (obj) { + QUnit.equal(obj.first, "Karl", "Got the second object"); + return db$b.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$b.transaction("r", db$b.users, function () { + db$b.users.where("username").equals("kceder").first(function (user) { + QUnit.equal(user.first, "Karl", "where().equals()"); + }), + db$b.users.where("id").above(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 1, "where().above()"); + }), + db$b.users.where("id").aboveOrEqual(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 2, "where().aboveOrEqual()"); + }), + db$b.users.where("id").below(idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().below().count()"); + }), + db$b.users.where("id").below(idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().below().count() should be zero"); + }), + db$b.users.where("id").belowOrEqual(idOfFirstUser).count(function (count) { + QUnit.ok(count == 1, "where().belowOrEqual()"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 1)"); + }), + db$b.users.where("id").between(0, Infinity).count(function (count) { + QUnit.ok(count == 2, "where().between(0, Infinity)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfFirstUser, true, true).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 1, true, true)"); + }), + db$b.users.where("id").between(1, -1, true, true).count(function (count) { + QUnit.ok(count == 0, "where().between(1, -1, true, true)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 2)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfLastUser, true, true).count(function (count) { + QUnit.ok(count == 2, "where().between(1, 2, true, true)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfLastUser, false, false).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 2, false, false)"); + }); + db$b.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$b.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$b.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$b.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$b.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$b.users.where("last").anyOf("Faadersköld").toArray(function (a) { + QUnit.equal(a.length, 1, "in() returned expected number of items"); + }); + if (supports("multiEntry")) { + db$b.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$b.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$b.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$b.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$b.transaction("rw", db$b.users, function () { + // Modify first found user with a helloMessage + db$b.users.orderBy("first").reverse().limit(1).modify(function (user) { + user.helloMessage = "Hello " + user.first; + }); + // Check that the modification went fine: + db$b.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$b.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$b.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$b.transaction("rw", db$b.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db$b.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$b.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$b.users.put(user).then(function (id) { + QUnit.equal(id, currentId, "Still got same id because we update same object"); + }); + db$b.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$b.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$b.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$b.users.put(user).then(function (id) { + QUnit.equal(id, userId, "Still got same id because we update same object"); + return db$b.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$b.transaction("rw", db$b.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db$b.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$b.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$b.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$b.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db$b.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__default["default"]("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$1(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$1(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$1(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$b.transaction("rw", db$b.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$b.users.bulkAdd(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie__default["default"].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$b.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$b.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$b.transaction("rw", db$b.users, function () { + db$b.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$b.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$b.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$b.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$b.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$b.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$b.transaction('rw', db$b.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$b.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__default["default"].BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db$b.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$b.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$b.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$b.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$b.transaction('rw', db$b.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$b.transaction('rw', db$b.users, function () { + db$b.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$b.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("Issue #1280 - add() with auto-incrementing ID and CryptoKey", function () { + var generatedKey, db, objToAdd, id, storedObj; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!((_a = self === null || self === void 0 ? void 0 : self.crypto) === null || _a === void 0 ? void 0 : _a.subtle)) { + QUnit.ok(true, "This browser doesnt have WebCrypto"); + return [2 /*return*/]; + } + return [4 /*yield*/, self.crypto.subtle.generateKey({ + name: "RSA-OAEP", + modulusLength: 1024, + publicExponent: new Uint8Array([1, 0, 1]), + hash: "SHA-256", + }, true, ["encrypt", "decrypt"])]; + case 1: + generatedKey = _b.sent(); + return [4 /*yield*/, Dexie__default["default"].delete("MyDatabaseToStoreCryptoKeys")]; + case 2: + _b.sent(); + db = new Dexie__default["default"]("MyDatabaseToStoreCryptoKeys"); + db.version(1).stores({ + keys: "++id", + }); + objToAdd = { key: generatedKey.privateKey }; + QUnit.ok(generatedKey.privateKey instanceof CryptoKey, "The CryptoKey object was generated correctly"); + return [4 /*yield*/, db.keys.add(objToAdd)]; + case 3: + id = _b.sent(); + QUnit.ok(id != null, "The id we got was not nullish"); + return [4 /*yield*/, db.keys.get(id)]; + case 4: + storedObj = _b.sent(); + QUnit.ok(storedObj.key instanceof CryptoKey, "The CryptoKey object exists in storage"); + // Verify that update works + return [4 /*yield*/, db.keys.update(id, { someOtherProp: 'x' })]; + case 5: + // Verify that update works + _b.sent(); + return [4 /*yield*/, db.keys.get(id)]; + case 6: + storedObj = _b.sent(); + QUnit.ok(storedObj.key instanceof CryptoKey, "The CryptoKey object is still a CryptoKey"); + 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$b.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$b.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db$b.users.get(idOfFirstUser)]; + case 3: + existingFirstUserToReplace = _a.sent(); + QUnit.equal(existingFirstUserToReplace.username, "dfahlander", "Existing user should be dfahlander"); + return [4 /*yield*/, db$b.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$b.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$b.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__default["default"]("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$1(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$1(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$1(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$b.users.bulkPut([{ + id: "sdjls83", + first: "Daveious" + }, { + id: "sdjls83", + last: "Olvono" + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$b.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$b.transaction("rw", db$b.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$b.users.bulkPut(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie__default["default"].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$b.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$b.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$b.transaction("rw", db$b.users, function () { + db$b.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$b.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$b.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$b.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$b.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$b.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$b.transaction('rw', db$b.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$b.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__default["default"].BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db$b.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$b.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$b.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$b.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$b.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$b.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$b.users.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_e.sent(), 1, "Should be 1 Bar"]); + return [4 /*yield*/, db$b.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$b.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$b.users.where('first').equals('Foo2').count()]; + case 6: + _d.apply(void 0, [_e.sent(), 4, "Should be 4 Foo2s now"]); + return [4 /*yield*/, db$b.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$b.transaction('rw', db$b.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$b.transaction('rw', db$b.users, function () { + db$b.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$b.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$b.users.orderBy('id').keys()]; + case 1: + userKeys = _a.sent(); + QUnit.ok(userKeys.length > 0, "User keys found: " + userKeys.join(',')); + return [4 /*yield*/, db$b.users.bulkDelete(userKeys)]; + case 2: + _a.sent(); + return [4 /*yield*/, db$b.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$b.users.orderBy(':id').lastKey()]; + case 1: + userKeys = _a.concat([_b.sent()]); + return [4 /*yield*/, db$b.users.bulkDelete(userKeys)]; + case 2: + _b.sent(); + return [4 /*yield*/, db$b.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$b.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$b.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }).then(function () { + db$b.users.delete(1).then(function () { + db$b.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$b.transaction("rw", db$b.users, function () { + db$b.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }); + db$b.users.delete(idOfFirstUser); + db$b.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$b.users.count().then(function (count) { + numUsers = count; + QUnit.ok(true, "Number of users before delete: " + count); + }).then(function () { + return db$b.users.delete("nonexisting key"); + }).then(function () { + QUnit.ok(true, "Success even though nothing was deleted"); + }).then(function () { + return db$b.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$b.transaction("rw", "users", function () { + db$b.users.count(function (count) { + QUnit.equal(count, 2, "There are 2 items in database before clearing it"); + }); + db$b.users.clear(); + db$b.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$b.transaction('r', 'users', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.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$b.transaction('rw', 'folks', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.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$b.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$1(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$b.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$b.users.bulkGet(keys)]; + case 2: + retrieved = _b.sent(); + deepEqual$1(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$b.users.bulkGet(["x", "y", 100, "z"])]; + case 3: + _a = __read.apply(void 0, [_b.sent(), 4]), 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*/]; + } + }); + }); }); + promisedTest("bulkError by pos", function () { return __awaiter(void 0, void 0, void 0, function () { + var bulkError_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, db$b.users.bulkAdd([ + { first: "foo1", last: "bar1", username: "foobar" }, + { first: "foo2", last: "bar2", username: "foobar" }, + { first: "foo3", last: "bar3", username: "foobar3" }, + ])]; + case 1: + _a.sent(); + QUnit.ok(false, "Should not succeed"); + return [3 /*break*/, 3]; + case 2: + bulkError_1 = _a.sent(); + QUnit.ok(bulkError_1 instanceof Dexie__default["default"].BulkError, "Got BulkError"); + QUnit.equal(bulkError_1.failures.length, 1, "Got one failure"); + QUnit.ok(!!bulkError_1.failures[0], "failures[0] is one Error"); + QUnit.ok(bulkError_1.failures[1] === undefined, "failures[1] is undefined"); + QUnit.equal(Object.keys(bulkError_1.failuresByPos).length, 1, "Got one key in failuresByPos"); + QUnit.equal(Object.keys(bulkError_1.failuresByPos)[0], 1, "Failure in position 1"); + QUnit.ok(bulkError_1.failuresByPos[0] === undefined, "failuresByPos[0] is undefined"); + QUnit.ok(!!bulkError_1.failuresByPos[1], "failuresByPos[1] is one Error"); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); }); + + module("chrome-transaction-durability", { + setup: function () { + }, + teardown: function () { + } + }); + QUnit.asyncTest("Transaction should use relaxed durability if specified", function () { + if (!isChrome) { + QUnit.ok(true, "This browser does not support Chrome transaction durability"); + QUnit.start(); + return; + } + var db = setupDb('relaxed'); + db.transaction('rw', db.users, function (trans) { + if (trans.idbtrans.durability === void 0) { + QUnit.ok(true, "This version of Chromium does not support transaction durability"); + } + else { + QUnit.ok(trans.idbtrans.durability === 'relaxed', "Transaction has relaxed durability"); + } + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }); + }); + QUnit.asyncTest("Transaction should use strict durability if specified", function () { + if (!isChrome) { + QUnit.ok(true, "This browser does not support Chrome transaction durability"); + QUnit.start(); + return; + } + var db = setupDb('strict'); + db.transaction('rw', db.users, function (trans) { + if (trans.idbtrans.durability === void 0) { + QUnit.ok(true, "This version of Chromium does not support transaction durability"); + } + else { + QUnit.ok(trans.idbtrans.durability === 'strict', "Transaction has strict durability"); + } + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }); + }); + QUnit.asyncTest("Transaction should use default durability if not specified", function () { + if (!isChrome) { + QUnit.ok(true, "This browser does not support Chrome transaction durability"); + QUnit.start(); + return; + } + var db = setupDb(); + db.transaction('rw', db.users, function (trans) { + if (trans.idbtrans.durability === void 0) { + QUnit.ok(true, "This version of Chromium does not support transaction durability"); + } + else { + QUnit.ok(trans.idbtrans.durability === 'default', "Transaction has default durability"); + } + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }); + }); + var setupDb = function (chromeTransactionDurability) { + var db = new Dexie__default["default"]("TestDBTrans", { chromeTransactionDurability: chromeTransactionDurability }); + db.version(1).stores({ + users: "username", + }); + return db; + }; + + var db$a = new Dexie__default["default"]("TestDBCollection"); + db$a.version(1).stores({ users: "id,first,last,[foo+bar],&username,*&email,*pets" }); + db$a.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String], + }); + db$a.on("populate", function () { + db$a.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$a.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$a).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$a.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$a.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$a.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$a.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$a.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$a.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$a.transaction("r", db$a.users, function () { + db$a.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$a.users.orderBy("last").limit(10).toArray(function (a) { + QUnit.equal(a.length, 2, "Array length is 2"); + }); + db$a.users.orderBy("last").limit(0).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$a.users.orderBy("last").limit(-1).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$a.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$a.transaction("rw", db$a.users, function () { + for (var i = 0; i < 10; ++i) { + db$a.users.add({ id: 3 + i, first: "First" + i, last: "Last" + i, username: "user" + i, email: ["user" + i + "@abc.se"] }); + } + // Using algorithm + count() + db$a.users.where("first").startsWithIgnoreCase("first").count(function (count) { + QUnit.equal(count, 10, "Counting all 10"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").limit(5).count(function (count) { + QUnit.equal(count, 5, "algorithm + count(): limit(5).count()"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).count()"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "algorithm + count(): offset(6).limit(4)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).limit(4)"); + }); + db$a.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$a.users.where("first").startsWithIgnoreCase("first").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "algorithm + toArray(): limit(5)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "algorithm + toArray(): offset(6).limit(4)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7).limit(4)"); + }); + db$a.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$a.users.where("first").startsWith("First").count(function (count) { + QUnit.equal(count, 10, "IDBKeyRange + count() - count all 10"); + }); + db$a.users.where("first").startsWith("First").limit(5).count(function (count) { + QUnit.equal(count, 5, "IDBKeyRange + count(): limit(5)"); + }); + db$a.users.where("first").startsWith("First").offset(7).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7)"); + }); + db$a.users.where("first").startsWith("First").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "IDBKeyRange + count(): offset(6)"); + }); + db$a.users.where("first").startsWith("First").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7).limit(4)"); + }); + db$a.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$a.users.where("first").startsWith("First").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "IDBKeyRange + toArray(): limit(5)"); + }); + db$a.users.where("first").startsWith("First").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7)"); + }); + db$a.users.where("first").startsWith("First").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "IDBKeyRange + toArray(): offset(6).limit(4)"); + }); + db$a.users.where("first").startsWith("First").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7).limit(4)"); + }); + db$a.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$a.users.orderBy("last").first(function (karlCeder) { + QUnit.equal(karlCeder.first, "Karl", "Got Karl"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("last", function () { + db$a.users.orderBy("last").last(function (david) { + QUnit.equal(david.first, "David", "Got David"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("and", 2, function () { + db$a.transaction("r", db$a.users, function () { + db$a.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$a.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$a.transaction("r", db$a.users, function () { + db$a.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$a.transaction("r", db$a.users, function () { + db$a.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$a.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$a.transaction("rw", db$a.users, function () { + var currentTime = new Date(); + db$a.users.toCollection().modify({ + lastUpdated: currentTime + }).then(function (count) { + QUnit.equal(count, 2, "Promise supplied the number of modifications made"); + }); + db$a.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$a.transaction("rw", db$a.users, function () { + var currentTime = new Date(); + db$a.users.toCollection().modify(function (user) { + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$a.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$a.transaction("rw", db$a.users, function () { + var currentTime = new Date(); + db$a.users.toCollection().modify(function (user) { + user.id = 1; + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$a.users.toArray(function (a) { + QUnit.ok(false, "Should not come here, beacuse we should get error when setting all primkey to 1"); + }); + }).catch(Dexie__default["default"].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$a.users.add({ id: 87, first: "Olle" })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$a.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$a.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$a.users.add({ id: 3, first: "David", last: "Fahlander2", username: "dfahlander2", email: ["david2@awarica.com"], pets: [] }); + db$a.users.add({ id: 4, first: "David", last: "Fahlander3", username: "dfahlander3", email: ["david3@awarica.com"], pets: [] }); + return [4 /*yield*/, db$a.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$a.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$a.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$a.users.orderBy("id").delete().then(function (count) { + QUnit.equal(count, 2, "All two records deleted"); + return db$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$a.users.where("first").equalsIgnoreCase("david").delete().then(function (deleteCount) { + QUnit.equal(deleteCount, 2, "Two items deleted (Both davids)"); + }); + db$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$a.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$a.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$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "David", last: "Helenius", username: "dahel" }); + db$a.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$a.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$a.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$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "Ylva", last: "Fahlander", username: "yfahlander" }); + var a = []; + db$a.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$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "Apan", last: "Japan", username: "apanjapan" }); + db$a.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$a.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$a.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__default["default"]("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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "Apa1", username: "apa1" }); + db$a.users.add({ id: 4, first: "Apa2", username: "apa2" }); + db$a.users.add({ id: 5, first: "Apa3", username: "apa3" }); + // Checking that it stops immediately when first item is the stop item: + db$a.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$a.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$a.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$a.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$a.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$a.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$a.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$a.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$a.transaction('r', db$a.users, function () { + db$a.users.each(function (user) { + db$a.users.where('id').equals(user.id).first(function (usr) { + return db$a.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); + }); + promisedTest("Issue 1381: Collection.filter().primaryKeys() on virtual index", function () { return __awaiter(void 0, void 0, void 0, function () { + var ids; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("compound")) { + QUnit.ok(true, "Skipping this test as the browser does not support compound indexes"); + return [2 /*return*/]; + } + // The original repro: https://jsitor.com/qPJXVESEcb failed when using Collection.delete(). + // Debugging it led me to that there is a general problem with virtual cursor's primaryKey property. + // So that's what we're testing here: + return [4 /*yield*/, db$a.users.add({ id: 1000, foo: "A", bar: "B" })]; + case 1: + // The original repro: https://jsitor.com/qPJXVESEcb failed when using Collection.delete(). + // Debugging it led me to that there is a general problem with virtual cursor's primaryKey property. + // So that's what we're testing here: + _a.sent(); + return [4 /*yield*/, db$a.users.where({ foo: "A" }).filter(function (x) { return true; }).primaryKeys()]; + case 2: + ids = _a.sent(); + QUnit.ok(ids.length === 1, "Theres one id there"); + QUnit.equal(ids[0], 1000, "The ID is 1000"); + return [2 /*return*/]; + } + }); + }); }); + + Dexie__default["default"].async; + var db$9 = new Dexie__default["default"]("TestDBWhereClause"); + db$9.version(2).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+age]", + multiMulti: "id,*tags,*categories" + }); + var Folder = db$9.folders.defineClass({ + id: Number, + path: String, + description: String + }); + var File = db$9.files.defineClass({ + id: Number, + filename: String, + extension: String, + folderId: Number + }); + File.prototype.getFullPath = function () { + var file = this; + return db$9.folders.get(this.folderId, function (folder) { + return folder.path + "/" + file.filename + (file.extension || ""); + }); + }; + Folder.prototype.getFiles = function () { + return db$9.files.where('folderId').equals(this.id).toArray(); + }; + var Chart = db$9.chart.defineClass({ + patno: Number, + row: Number, + col: Number, + sym: Number + }); + Chart.prototype.save = function () { + return db$9.chart.put(this); + }; + var firstFolderId = 0; + db$9.on("populate", function () { + var folders = db$9.table("folders"); + var files = db$9.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$9).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$9.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$9.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$9.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$9.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__default["default"].Promise.all(mippler(db$9.folders.where('path').startsWithAnyOf([])).count(), // Empty + mippler(db$9.folders.where('path').startsWithAnyOf('/var', '/var', '/var')).count(), // Duplicates + mippler(db$9.folders.where('path').startsWithAnyOf('')).count(), // Empty string should match all + mippler(db$9.folders).count(), mippler(db$9.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$9.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$9.transaction('r', db$9.folders, db$9.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$9.transaction("r", db$9.files, db$9.folders, function () { + db$9.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$9.files.put({ id: 9000, filename: "new file 1", folderId: firstFolderId }); + db$9.files.put({ id: 10000, filename: "new file 2", folderId: firstFolderId }); + db$9.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$9.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$9.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$9.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$9.transaction("rw", db$9.files, function () { + fileArray.forEach(function (file) { + db$9.files.add(file); + }); + db$9.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$9.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$9.transaction("rw", db$9.files, function () { + fileArray.forEach(function (file) { + db$9.files.add(file); + }); + db$9.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__default["default"].dependencies.indexedDB === idbModules.shimIndexedDB) { + // Using indexedDBShim. + QUnit.ok(false, "This test would hang with IndexedDBShim as of 2015-05-07"); + QUnit.start(); + return; + } + db$9.transaction("rw", db$9.files, function () { + db$9.files.clear(); + db$9.files.add({ filename: "Hello-there-", folderId: 1 }); + db$9.files.add({ filename: "hello-there-", folderId: 1 }); + db$9.files.add({ filename: "hello-there-everyone", folderId: 1 }); + db$9.files.add({ filename: "hello-there-everyone-of-you!", folderId: 1 }); + // Ascending + db$9.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$9.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$9.transaction("r", db$9.folders, function () { + db$9.folders.count(function (count) { + QUnit.ok(true, "Number of folders in database: " + count); + db$9.folders.where("path").startsWithIgnoreCase("/").toArray(function (a) { + QUnit.equal(a.length, count, "Got all folder objects because all of them starts with '/'"); + }); + }); + db$9.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$9.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$9.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$9.transaction("r", db$9.files, function () { + db$9.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$9.transaction('rw', db$9.people, function () { + db$9.people.add({ name: "Santaclaus", number: 123 }); + db$9.people.add({ name: "Santaclaus", number: 124 }); + db$9.people.add({ name: "Santaclaus2", number: 1 }); + return db$9.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$9.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$9.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$9.transaction("rw", db$9.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$9.chart.bulkAdd(chart); + }).then(function () { + var grid = [], x1 = 91, x2 = 130; + return db$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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", + //"/var/bin" + ], 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$9.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", + //"/var/bin" + ], 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$9.transaction('rw', db$9.friends, function () { + db$9.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$9.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$9.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$9.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$9.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$9.transaction('r', db$9.folders, db$9.files, function () { + db$9.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$9.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$9.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$9.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$9.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$9.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__default["default"].Promise.all(mippler(db$9.folders.where('path').startsWithAnyOfIgnoreCase([])).count(), // Empty + mippler(db$9.folders.where('path').startsWithAnyOfIgnoreCase('/var', '/var', '/var')).count(), // Duplicates + mippler(db$9.folders.where('path').startsWithAnyOfIgnoreCase('')).count(), // Empty string should match all + mippler(db$9.folders).count(), mippler(db$9.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$9.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$9.transaction('r', db$9.folders, db$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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("where({notIndexed: value}) should not return emtpy result", function () { return __awaiter(void 0, void 0, void 0, function () { + var chaplin, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$9.chaps.add({ name: "Chaplin", number: 1, age: 134, notIndexed: 'foo' })]; + case 1: + _a.sent(); + _a.label = 2; + case 2: + _a.trys.push([2, 4, , 5]); + return [4 /*yield*/, db$9.chaps.where({ name: "Chaplin", notIndexed: "foo" }).first()]; + case 3: + chaplin = _a.sent(); + if (!chaplin) { + QUnit.ok(false, "Got empty result when data exists matching the query. If we're not using an index we should not get an empty result but an error."); + } + else { + QUnit.ok(chaplin, "Ok, so we got a result even though 'notIndexed' is not indexed at all. " + + "This is not expected but ok if the result would be valid"); + QUnit.equal(chaplin.name, "Chaplin", "Got the correct data Chaplin!"); + } + return [3 /*break*/, 5]; + case 4: + e_1 = _a.sent(); + QUnit.ok(true, "Got error: \"" + e_1 + "\" because 'notIndexed' is not indexed at all. This is also ok."); + return [3 /*break*/, 5]; + case 5: 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$9.files.add({ filename: "hello", extension: ".bat" }); + return [4 /*yield*/, db$9.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$9.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$9.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$9.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, mambosNumber5, 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$9.chaps.bulkAdd([{ + name: "David", + number: 2, + age: 29 + }, { + name: "David", + number: 3, + age: 39 + }, { + name: "David", + number: 1, + age: 49 + }, { + name: "Mambo", + number: 5, + age: 55 + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.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$9.chaps.where({ name: "Mambo", number: 5 }).toArray()]; + case 3: + mambosNumber5 = _a.sent(); + QUnit.equal(mambosNumber5.length, 1, "There should be 1 Mambo no 5 in the result"); + return [4 /*yield*/, db$9.chaps.where('name').equalsIgnoreCase('david').toArray()]; + case 4: + 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*/]; + } + }); + }); }); + promisedTest("WhereClause.equals(invalid key)", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$9.files.where("filename").equals(null).first().then(function () { + QUnit.ok(false, "db.files.where('filename').equals(null) must fail but it didnt!"); + }).catch(function (error) { + QUnit.ok(true, "db.files.where('filename').equals(null) failed as expected (with " + error + ")"); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.files.where("filename").equals(undefined).first().then(function () { + QUnit.ok(false, "db.files.where('filename').equals(undefined) must fail but it didnt!"); + }).catch(function (error) { + QUnit.ok(true, "db.files.where('filename').equals(undefined) failed as expected (with " + error + ")"); + })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$9.files.where("filename").equals(function () { }).first().then(function () { + QUnit.ok(false, "db.files.where('filename').equals(function(){}) must fail but it didnt!"); + }).catch(function (error) { + QUnit.ok(true, "db.files.where('filename').equals(function(){}) failed as expected (with " + error + ")"); + })]; + case 3: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var db$8 = new Dexie__default["default"]("TestDBTrans"); + db$8.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + QUnit.module("transaction", { + setup: function () { + QUnit.stop(); + resetDatabase(db$8).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + var NativePromise$2 = window.Promise; + QUnit.asyncTest("Transaction should work when returning native Promise in transaction scope", function () { + if (!NativePromise$2) { + QUnit.ok(true, "Current Browser doesn't have a native Promise"); + return QUnit.start(); + } + db$8.transaction('rw', db$8.users, function (trans) { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "First argument to transaction callback should be the transaction instance itself"); + return NativePromise$2.resolve().then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + }).then(function () { + return db$8.users.add({ username: "barfoo" }); // Will only work on Chrome, Opera and Edge as of Oktober 6, 2016. + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + return db$8.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$8.transaction('rw', db$8.users, db$8.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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "arne" }); + return db$8.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__default["default"].currentTransaction != null, "Current Transaction must be set"); + }); + }).then(function () { + QUnit.ok(Dexie__default["default"].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$8.pets.add({ kind: "dog" }).then(function () { + return db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "arne" }); + return db$8.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$8.transaction('rw', db$8.users, function () { + db$8.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$8.transaction('r', db$8.users, function () { + db$8.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$8.transaction('rw', db$8.users, function () { + return new Dexie__default["default"].Promise(function (resolve, reject) { + // Notify log when transaction completes too early + Dexie__default["default"].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$8.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$8.transaction('rw', db$8.users, function () { + // First make an operation so that transaction is internally created (this is the thing differing from the previous test case + return db$8.users.add({ username: "arne" }).then(function () { + // Create a custom promise that will use setTimeout() so that IDB transaction will commit + return new Dexie__default["default"].Promise(function (resolve, reject) { + // Notify log when transaction completes too early + Dexie__default["default"].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$8.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$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + QUnit.ok(parentTrans._reculock > 0, "Parent transaction is locked"); + db$8.users.add(user); + pets.forEach(function (pet) { + db$8.pets.add(pet).then(function (petId) { + return db$8.petsPerUser.add({ user: user.username, pet: petId }); + }); + }); + }).then(function () { + return db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: user.username + "2" }); + return "hello..."; + }); + }); + } + db$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + var trans = Dexie__default["default"].currentTransaction; + parentTrans = Dexie__default["default"].currentTransaction; + QUnit.ok(trans._reculock === 0, "Main transaction not locked yet"); + addUser({ username: "user1" }, [{ kind: "dog" }, { kind: "cat" }]).then(function () { + db$8.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$8.users.get("someoneelse", function (someone) { + QUnit.ok(!someone, "Someoneelse not yet added"); + }); + db$8.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__default["default"].currentTransaction == null, "Dexie.currentTransaction is null"); + db$8.users.count(function (count) { + QUnit.equal(count, 5, "There are five users in db"); + }); + db$8.pets.count(function (count) { + QUnit.equal(count, 3, "There are three pets in db"); + }); + db$8.petsPerUser.count(function (count) { + QUnit.equal(count, 3, "There are three pets-to-user relations"); + }); + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == null, "Dexie.currentTransaction is null"); + // Start an outer transaction + return db$8.transaction('rw', db$8.users, function () { + // Do an add operation + db$8.users.add({ username: "sune" }); //.then(function () { + // Start an inner transaction + db$8.transaction('rw', db$8.users, function () { + // Do an add-operation that will result in ConstraintError: + db$8.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$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + db$8.users.add({ username: "ojsan" }); + db$8.transaction('rw', db$8.users, db$8.pets, function () { + db$8.users.add({ username: "ojsan2" }); + db$8.users.toCollection().delete(); + db$8.transaction('r', db$8.users, function () { + db$8.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie__default["default"].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__default["default"].Promise.resolve().then(function () { + return db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "bertil" }); + db$8.transaction('rw', db$8.users, db$8.pets, function () { + db$8.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$8.transaction('r', db$8.users, db$8.pets, function () { + db$8.users.toArray(); + db$8.transaction('rw', db$8.users, db$8.pets, function () { + db$8.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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "bertil" }); + db$8.transaction('rw!', db$8.users, db$8.pets, function () { + db$8.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__default["default"].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$8.transaction('r', db$8.users, db$8.pets, function () { + db$8.users.toArray(); + db$8.transaction('rw!', db$8.users, db$8.pets, function () { + db$8.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__default["default"]("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + db2.delete() + .then(function () { return db2.open(); }) + .then(function () { return db$8.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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "bertil" }); + db$8.transaction('rw?', db$8.users, db$8.pets, function () { + db$8.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__default["default"].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$8.transaction('r', db$8.users, db$8.pets, function () { + db$8.users.toArray(); + db$8.transaction('rw?', db$8.users, db$8.pets, function () { + db$8.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__default["default"]("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + db2.open(); + db$8.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$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + db$8.users.add({ username: "ojsan" }); + db$8.transaction('rw?', db$8.users, db$8.pets, function () { + db$8.users.add({ username: "ojsan2" }); + db$8.users.toCollection().delete(); + db$8.transaction('r?', db$8.users, function () { + db$8.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie__default["default"].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__default["default"]("logger"); + logDb.version(1).stores({ + log: "++,time,type,message" + }); + var lastLogAddPromise; + logDb.open().then(function () { + return db$8.transaction('rw', db$8.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$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + QUnit.ok(true, "Now adding Gunnar in parent transaction"); + db$8.users.add({ username: "Gunnar" }).then(function () { + QUnit.ok(true, "First add on parent transaction finished. Now adding another object in parent transaction."); + db$8.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$8.transaction('rw', db$8.users, function () { + QUnit.ok(true, "Entered sub transaction"); + return db$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + var trans = Dexie__default["default"].currentTransaction; + return db$8.transaction('rw', db$8.users, function () { + QUnit.ok(true, "Entered sub transaction"); + QUnit.ok(Dexie__default["default"].currentTransaction !== trans, "We are not in parent transaction"); + QUnit.ok(Dexie__default["default"].currentTransaction.parent === trans, "...but in a sub transaction"); + return Dexie__default["default"].Promise.resolve(3); + }).then(function (result) { + QUnit.equal(result, 3, "Got 3"); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Now we are in parent transaction"); + db$8.users.add({ username: "Gunnar" }); + return db$8.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__default["default"].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$8.transaction('rw', db$8.users, db$8.pets, function () { + console.log("Entering small child"); + return db$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + console.log("Entering middle child"); + return db$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + console.log("Entering root transaction"); + return db$8.transaction('rw', db$8.users, db$8.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__default["default"].currentTransaction, "There is no ongoing transaction"); + db$8.transaction('rw', db$8.pets, function () { + var rootLevelTransaction = Dexie__default["default"].currentTransaction; + QUnit.ok(true, "Entered root transaction scope"); + return db$8.transaction('rw', db$8.pets, function () { + QUnit.ok(true, "Entered sub scope"); + var level2Transaction = Dexie__default["default"].currentTransaction; + QUnit.ok(level2Transaction.parent === rootLevelTransaction, "Level2 transaction's parent is the root level transaction"); + return db$8.transaction('rw', db$8.pets, function () { + QUnit.ok(true, "Entered sub of sub scope"); + var innermostTransaction = Dexie__default["default"].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__default["default"].Promise.resolve().then(function () { + QUnit.ok(true, "Sub of sub scope: Promise.resolve().then() called"); + QUnit.ok(!!Dexie__default["default"].currentTransaction, "There is an ongoing transaction"); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return db$8.pets.add({ + id: 123, + value: 'val' + }).then(function (resultId) { + QUnit.ok(true, "Sub of sub scope: add() resolved"); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(resultId).then(function (res) { + return Dexie__default["default"].Promise.resolve(res); + }); + }).then(function (resultId) { + QUnit.ok(true, "Sub if sub scope: Promise.resolve() after add() resolve"); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(resultId); + }); + }).then(function () { + QUnit.ok(true, "sub of sub scope chaining further in promise chains..."); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(db$8.pets.get(123)); + }).then(function (pet) { + QUnit.ok(true, "sub of sub scope chaining further in promise chains 2..."); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(pet.id); + }); + }).then(function (resultId) { + QUnit.ok(true, "Innermost transaction completed"); + QUnit.ok(Dexie__default["default"].currentTransaction == level2Transaction, "We should now be executing within level 2 sub transaction"); + return Dexie__default["default"].Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.ok(Dexie__default["default"].currentTransaction == level2Transaction, "We should still be executing within level 2 sub transaction"); + return Dexie__default["default"].Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.equal(resultId, 123, "Result was 123 as expected"); + }).then(function () { + return db$8.transaction('rw', db$8.pets, function () { + var innermostTransaction2 = Dexie__default["default"].currentTransaction; + QUnit.ok(innermostTransaction2.parent == level2Transaction, "Another 3rd level transaction has parent set to our level2 transaction"); + return db$8.pets.add({ + id: 321, + value: 'val' + }).then(function (resultId2) { + return Dexie__default["default"].Promise.resolve(resultId2); + }).then(function (resultId2) { + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction2, "We're still in the innermostTransaction (second one)"); + return Dexie__default["default"].Promise.resolve(resultId2).then(function (x) { + QUnit.ok(Dexie__default["default"].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__default["default"].currentTransaction === level2Transaction, "We should still be executing within level 2 sub transaction"); + return "finalResult"; + }); + }); + }).then(function (x) { + QUnit.ok(Dexie__default["default"].currentTransaction === rootLevelTransaction, "Now we're at the root level transaction and can do some more stuff here"); + return db$8.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__default["default"].currentTransaction, "No ongoing transaction now"); + QUnit.ok(true, "done"); + }).catch(function (error) { + QUnit.ok(false, error.stack); + }).finally(QUnit.start); + QUnit.ok(!Dexie__default["default"].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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "erictheviking", color: "blue" }).then(function () { + db$8.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$8.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__default["default"].currentTransaction === trans, "Dexie.currentTransaction correct in " + scope); + }; + } + function onCreating(primKey, obj, transaction) { + QUnit.ok(!!Dexie__default["default"].currentTransaction, "Dexie.currentTransaction should exist in creating"); + QUnit.ok(Dexie__default["default"].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__default["default"].currentTransaction, "Dexie.currentTransaction should exist in reading"); + return obj; + } + function onUpdating(modifications, primKey, obj, transaction) { + QUnit.ok(Dexie__default["default"].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__default["default"].currentTransaction === transaction, "Dexie.currentTransaction correct in deleting"); + this.onsuccess = CurrentTransChecker("deleting.onsuccess", transaction); + } + db$8.users.hook.creating.subscribe(onCreating); + db$8.users.hook.reading.subscribe(onReading); + db$8.users.hook.updating.subscribe(onUpdating); + db$8.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$8.users.add({ username: "monkey1" })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.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$8.users.bulkAdd([{ username: "monkey1" }, { username: "monkey2" }]) + .then(function () { return QUnit.ok(false, "Should get error on one of the adds"); }) + .catch(Dexie__default["default"].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$8.users.where("username").equals("monkey1").modify({ + name: "Monkey 1" + })]; + case 4: + _a.sent(); + return [4 /*yield*/, db$8.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$8.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$8.users.where({ username: "monkey88" }).modify({ username: "monkey1" })]; + case 7: + _a.sent(); + return [4 /*yield*/, db$8.users.toArray()]; + case 8: + _a.sent(); + return [4 /*yield*/, db$8.users.delete("monkey2")]; + case 9: + _a.sent(); + return [4 /*yield*/, db$8.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$8.transaction('rw', db$8.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$8.users.hook.creating.unsubscribe(onCreating); + db$8.users.hook.reading.unsubscribe(onReading); + db$8.users.hook.updating.unsubscribe(onUpdating); + db$8.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$8.transaction('rw', db$8.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__default["default"].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__default["default"].waitFor(function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(Dexie__default["default"].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__default["default"].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__default["default"].currentTransaction === trans, "Zone info should still be correct"); + // Subtransaction + return [4 /*yield*/, db$8.transaction('r', db$8.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__default["default"].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__default["default"].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__default["default"].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$8.transaction('r', db$8.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__default["default"].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$8.transaction('r', db$8.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__default["default"].ignoreTransaction(function () { + return new Dexie__default["default"].Promise(function (resolve) { return setTimeout(resolve, 50); }).then(function () { + return db$8.pets.put({ kind: "dog" }); + }).then(function () { + return db$8.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__default["default"].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$8.transaction('r', db$8.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$8.transaction('rw!', db$8.pets, function () { + return db$8.pets.put({ kind: "dog" }).then(function () { + return db$8.pets.count(); + }).then(function (numPets) { + QUnit.ok(true, "num pets: " + numPets); + }).then(function () { + return Dexie__default["default"].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*/]; + } + }); + }); }); + QUnit.asyncTest("abort will rollback previous writes", function () { + db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "james", color: "red" }); + Dexie__default["default"].currentTransaction.abort(); + }).catch(function () { + QUnit.ok(true, "transaction done"); + }).then(function () { + return db$8.users.get('james'); + }).then(function (user) { + QUnit.ok(user == null, "should not written if transaction aborted"); + }) + .finally(QUnit.start); + }); + + var async$3 = Dexie__default["default"].async; + QUnit.module("open", { + setup: function () { + QUnit.stop(); + Dexie__default["default"].delete("TestDB").then(function () { + QUnit.start(); + }).catch(function (e) { + QUnit.ok(false, "Could not delete database"); + }); + }, + teardown: function () { + QUnit.stop(); + Dexie__default["default"].delete("TestDB").then(QUnit.start); + } + }); + var timeout = async$3(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__default["default"]("TestDB"), db2 = new Dexie__default["default"]("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__default["default"]('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__default["default"].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__default["default"].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__default["default"]("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__default["default"]("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__default["default"]("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__default["default"].NoSuchDatabaseError, function (err) { + // An error happened. Database did not exist. + QUnit.ok(true, "Database did not exist"); + db = new Dexie__default["default"]("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__default["default"]("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__default["default"].Observable ? 1 : 10, function () { + if (Dexie__default["default"].Observable) { + QUnit.ok(true, "Dexie.Observable currently not compatible with this mode"); + return QUnit.start(); + } + var db = new Dexie__default["default"]("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__default["default"]("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__default["default"]("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__default["default"].getDatabaseNames(function (names) { + defaultDatabases = [].slice.call(names, 0); + QUnit.ok(true, "Current databases: " + (defaultDatabases.length ? defaultDatabases.join(',') : "(none)")); + db1 = new Dexie__default["default"]("TestDB1"); + db1.version(1).stores({}); + return db1.open(); + }).then(function () { + // One DB created + QUnit.ok(true, "TestDB1 successfully created"); + return Dexie__default["default"].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__default["default"]("TestDB2"); + db2.version(1).stores({}); + return db2.open(); + }).then(function () { + QUnit.ok(true, "TestDB2 successfully created"); + return Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].exists("nonexistingDB"); + }).then(function (exists) { + QUnit.ok(!exists, "'nonexistingDB' should not exist indeed"); + return Dexie__default["default"].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__default["default"].Promise.resolve()).finally(function () { + (db2 ? db2.delete() : Dexie__default["default"].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__default["default"]("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__default["default"].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__default["default"]("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__default["default"].exists("TestDB").then(function (result) { + QUnit.equal(result, false, "Should not exist yet"); + db = new Dexie__default["default"]("TestDB"); + db.version(1).stores({ + some: "schema" + }); + return db.open(); + }).then(function () { + return Dexie__default["default"].exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should exist now and has another open connection."); + db.close(); + return Dexie__default["default"].exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should still exist"); + return Dexie__default["default"].delete("TestDB"); + }).then(function () { + return Dexie__default["default"].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__default["default"]("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__default["default"].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__default["default"].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__default["default"].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__default["default"]("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__default["default"].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__default["default"]("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__default["default"]("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__default["default"]('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__default["default"].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*/]; + } + }); + }); }); + promisedTest("Should be possible to open a vip DB", function () { return __awaiter(void 0, void 0, void 0, function () { + var db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie__default["default"].delete('TestDB')]; + case 1: + _a.sent(); + db = new Dexie__default["default"]('TestDB'); + db.version(1).stores({ foobar: 'id' }); + return [4 /*yield*/, db.vip.open()]; + case 2: + _a.sent(); + QUnit.ok(true, "Could open viped db"); + return [4 /*yield*/, db.vip.foobar.toArray()]; + case 3: + _a.sent(); + QUnit.ok(true, "Could query viped db"); + return [4 /*yield*/, db.foobar.toArray()]; + case 4: + _a.sent(); + QUnit.ok(true, "Could query non-viped db after opening it through vip mode"); + db.vip.close(); + // Try testing it dynamically + db = new Dexie__default["default"]('TestDB'); + return [4 /*yield*/, db.vip.open()]; + case 5: + _a.sent(); + QUnit.ok(true, "Could open viped db dynamically"); + return [4 /*yield*/, db.vip.table('foobar').toArray()]; + case 6: + _a.sent(); + QUnit.ok(true, "Could query dynamically opened viped db"); + return [2 /*return*/]; + } + }); + }); }); + + var db$7 = new Dexie__default["default"]("TestYieldDb"); + var async$2 = Dexie__default["default"].async; + var spawn = Dexie__default["default"].spawn; + db$7.version(1).stores({ + friends: '++id,name,*groups', + pets: '++id,name' + }); + QUnit.module("yield", { + setup: function () { + QUnit.stop(); + resetDatabase(db$7).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + QUnit.asyncTest("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$7.transaction('rw', 'friends', 'pets', function () { + var catId, dogId, gurra, gurrasPets; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$7.pets.add({ name: "Tito", kind: "cat" })]; + case 1: + catId = _a.sent(); + return [4 /*yield*/, db$7.pets.add({ name: "Josephina", kind: "dog" })]; + case 2: + dogId = _a.sent(); + // Add a friend who owns the pets + db$7.friends.add({ name: "Gurra G", pets: [catId, dogId] }); + return [4 /*yield*/, db$7.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$7.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$7.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$7.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$7.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$7.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$7.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$7.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$7.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$7.transaction('rw', 'pets', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$7.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$7.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$7.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; + 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: + _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; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, [1, 2, Dexie__default["default"].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: + _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__default["default"].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$7.friends.add(friend)]; + case 1: + friendId = _a.sent(); + return [4 /*yield*/, db$7.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$7.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 _global = typeof globalThis !== 'undefined' ? globalThis : + typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; + + var keys = Object.keys; + var isArray$1 = Array.isArray; + 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)); + (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(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 = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" + .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]; }); + intrinsicTypeNames.map(function (t) { return _global[t]; }); + arrayToObject(intrinsicTypeNames, function (x) { return [x, true]; }); + var toString = {}.toString; + function toStringTag(o) { + return toString.call(o).slice(8, -1); + } + // If first argument is iterable or array-like, return it as an array + var iteratorSymbol = typeof Symbol !== 'undefined' ? + Symbol.iterator : + '@@iterator'; + var getIteratorOf = typeof iteratorSymbol === "symbol" ? 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$1(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$1() { } + 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. + getErrorWithStack.arguments; + throw new Error(); // Fallback if above line don't throw. + } + catch (e) { + return e; + } + return new Error(); + } + function prettyStack(exception, numIgnoredFrames) { + var stack = exception.stack; + if (!stack) + return ""; + numIgnoredFrames = (numIgnoredFrames || 0); + if (stack.indexOf(exception.name) === 0) + numIgnoredFrames += (exception.name + exception.message).split('\n').length; + return stack.split('\n') + .slice(numIgnoredFrames) + .filter(libraryFilter) + .map(function (frame) { return "\n" + frame; }) + .join(''); + } + + 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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" + }; + // + // 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 = Object.keys(failures).map(function (pos) { return failures[pos]; }); + this.failuresByPos = 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"} + 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; + 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, + // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. + MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + // Generate a native promise (as window.Promise may have been patched) + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], 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 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } + }; + var isOutsideMicroTick = true, // True when NOT in a virtual microTick. + needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick() + unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'. + rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback. + currentFulfiller = null, 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$1; // 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); + var cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), 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: function () { return totalEchoes; } }, + //task: {get: ()=>task}, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap; }, + set: function (value) { asap = 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(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(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(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, 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) + extend(psd, props); + // 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() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0. + return true; + } + 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$1; + } + // 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, cleanup) { + 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); + if (cleanup) + enqueueNativeMicroTask(decrementExpectedAwaits); + } + }; + } + function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; + } + 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$1(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__default["default"]("idbPromiseCompatTest"); + db.version(1).stores({ foo: 'bar' }); + return [4 /*yield*/, db.delete()]; + case 1: + _a.sent(); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + return [4 /*yield*/, db.transaction('r', db.foo, function () { return __awaiter(_this, void 0, void 0, function () { + var p, i, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.foo.count()]; + case 1: + _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: + _a.sent(); + db.close(); + throw new IdbPromiseIncompatibleError(); + case 6: return [2 /*return*/]; + } + }); + }); })]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + } + + var idbAndPromiseCompatible; + var hasNativeAsyncFunctions = false; + try { + hasNativeAsyncFunctions = !!new Function("return (async ()=>{})();")().then; + } + catch (e) { } + var db$6 = new Dexie__default["default"]("TestDBTranx"); + db$6.version(1).stores({ + items: "id" + }); + QUnit.module("asyncawait", { + setup: function (assert) { + // Execute this promise when needed: + if (idbAndPromiseCompatible === undefined) { + // Initialize this promise. + idbAndPromiseCompatible = isIdbAndPromiseCompatible(); + } + var done = assert.async(); + resetDatabase(db$6).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$6.transaction('rw', db$6.items, function (trans) { + return window.Promise.resolve().then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$6.items.add({ id: "foobar" }); + }).then(function () { + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$6.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__default["default"].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__default["default"], db$6); + }).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__default["default"].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__default["default"]); + }).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__default["default"].delete("issue612"); + }).then(done); + }); + var NativePromise = (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__default["default"], db$6).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__default["default"].currentTransaction === null, "Should not have an ongoing transaction to start with"); + db$6.transaction('rw', db$6.items, function () { + var trans = Dexie__default["default"].currentTransaction; + QUnit.ok(trans !== null, "Should have a current transaction"); + var otherZonePromise; + Dexie__default["default"].ignoreTransaction(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == null, "No Transaction in this zone"); + function promiseFlow() { + return NativePromise.resolve().then(function () { + if (Dexie__default["default"].currentTransaction !== null) + QUnit.ok(false, "PSD zone leaked"); + return new NativePromise(function (resolve) { return NativePromise.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$6.items.get(1).then(function () { + return idbAndPromiseCompatible; + }).then(function () { + QUnit.ok(Dexie__default["default"].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__default["default"], trans, NativePromise, db$6); + }).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__default["default"].currentTransaction === trans, "Still same transaction 2"); + return Promise.resolve(); + }).then(function () { + // window.Promise + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still same transaction 3"); + return Dexie__default["default"].Promise.resolve(); + }).then(function () { + // Dexie.Promise + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still same transaction 4"); + return otherZonePromise; // wait for the foreign zone promise to complete. + }).then(function () { + QUnit.ok(Dexie__default["default"].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__default["default"], db$6) + .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$6.transaction('rw', db$6.items, function () { + var all; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve(3)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$6.items.bulkAdd([{ id: 'a' }, { id: 'b' }])]; + case 2: + _a.sent(); + return [4 /*yield*/, Promise.all([db$6.items.get('a'), db$6.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$6.items.get('a'), db$6.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$6.transaction('rw', db$6.items, function () { + var trans = Dexie__default["default"].currentTransaction; + QUnit.ok(trans !== null, "Have a transaction"); + return Promise.resolve().then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still have the same current transaction."); + return Promise.resolve().then(function () { return Promise.resolve(); }); + }).then(function () { + QUnit.ok(Dexie__default["default"].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__default["default"], db$6)]; + 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__default["default"].Promise, "At global scope. Promise should not be Dexie.Promise"); + QUnit.ok(window.Promise !== Dexie__default["default"].Promise, "At global scope. Promise should not be Dexie.Promise"); + GlobalPromise = window.Promise; + return [4 /*yield*/, db$6.transaction('rw', db$6.items, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + QUnit.ok(Promise === Dexie__default["default"].Promise, "Within transaction scope, Promise should be Dexie.Promise."); + QUnit.ok(window.Promise === Dexie__default["default"].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$6.transaction('rw', db$6.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__default["default"].currentTransaction; + QUnit.ok(!!trans, "Should have a current transaction"); + return [4 /*yield*/, db$6.items.add({ id: 'foo' })]; + case 1: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of Dexie.Promise"); + return [4 /*yield*/, Promise.resolve()]; + case 2: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of Promise.resolve()"); + return [4 /*yield*/, 3]; + case 3: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted after await 3"); + return [4 /*yield*/, db$6.transaction('r', db$6.items, function (innerTrans) { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(!!innerTrans, "Should have inner transaction"); + QUnit.equal(Dexie__default["default"].currentTransaction, innerTrans, "Inner transaction should be there"); + QUnit.equal(innerTrans.parent, trans, "Parent transaction should be correct"); + return [4 /*yield*/, db$6.items.get(1)]; + case 1: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === innerTrans, "Transaction persisted in inner transaction"); + return [2 /*return*/]; + } + }); + }); })]; + case 4: + _a.sent(); + QUnit.ok(Dexie__default["default"].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$6.items.get(1)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); })()]; + case 5: + _a.sent(); + QUnit.ok(Dexie__default["default"].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$6.transaction('r', db$6.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$6.items.get(1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$6.items.get(2)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }), db$6.transaction('r', db$6.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$6.items.get(1)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); })])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })()]; + case 6: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of async function 2"); + return [4 /*yield*/, Promise.resolve().then(function () { + QUnit.ok(Dexie__default["default"].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__default["default"].currentTransaction === trans, "Transaction persisted after native promise completion"); + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie__default["default"].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__default["default"].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__default["default"], db$6)]; + 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__default["default"], db$6, GlobalPromise)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var db$5 = new Dexie__default["default"]("TestDBException"); + db$5.version(1).stores({ users: "id,first,last,&username,&*email,*pets" }); + db$5.on("populate", function (trans) { + db$5.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$5.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$5).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$5.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$5.transaction("rw", db$5.users, function () { + var id; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$5.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" })]; + case 1: + id = _a.sent(); + QUnit.equal(id, 3); + return [4 /*yield*/, db$5.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$5.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$5.transaction("rw", db$5.users, function () { + db$5.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" }); + db$5.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$5.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$5.transaction("rw", db$5.users, function () { + db$5.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$5.transaction("rw", db$5.users, function () { + db$5.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$5.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$5.transaction("r", db$5.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$5.transaction("r", db$5.users, function () { + db$5.users.where("username").equals("apa").toArray(function () { + db$5.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$5.users.hook('deleting', deletingHook); + db$5.transaction('rw', db$5.users, function () { + function deleteKarls() { + db$5.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }); + } + db$5.users.delete(1); + deleteKarls(); + }).then(function () { + QUnit.ok(false, "Transaction should not complete!"); + }).catch(function (err) { + QUnit.ok(true, "Transaction aborted"); + }).finally(function () { + db$5.users.hook('deleting').unsubscribe(deletingHook); + QUnit.start(); + }); + }); + QUnit.asyncTest("exceptionThrown-iteration-should-not-abort-when-using-hook", function () { + db$5.users.hook('deleting', function () { + // Testing with + }); + db$5.transaction('rw', db$5.users, function () { + function deleteKarls() { + db$5.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }).catch(function (err) { + // Catching error should prevent transaction from aborting. + }); + } + db$5.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__default["default"]("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__default["default"]("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__default["default"]("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__default["default"]("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__default["default"]("TestUpgrader"); + return db.open(); + }).then(function () { + QUnit.ok(false, "The database should not have been created"); + }).catch(function (err) { + QUnit.ok(err instanceof Dexie__default["default"].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__default["default"]("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__default["default"].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__default["default"].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__default["default"].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__default["default"].Promise.all([ + // WhereClause.equals() + db$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.transaction('rw', db$5.users, function () { + db$5.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$5.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$5.transaction('rw', db$5.users, function () { + db$5.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$5.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__default["default"].Promise(function (resolve, reject) { + reject("first error (by reject)"); + }); + // Also if the rejection was caused by a throw... + new Dexie__default["default"].Promise(function () { + throw "second error (throw)"; + }); + // But when catched it should not trigger the global event: + new Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].delete("testdb").then(function () { + // Now just do some Dexie stuff... + var db = new Dexie__default["default"]("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$2 = Dexie__default["default"].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; + 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$2.resolve(function () { + return Dexie__default["default"].delete(DBNAME); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Empty schema + db = new Dexie__default["default"](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. + db.tables.length; + baseTables = db.tables.map(function (t) { return t.name; }); + }); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Adding version. + db = new Dexie__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"].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__default["default"].delete("raw-db").then(function () { + // Create a bare-bone indexedDB database with custom indexes of various kinds. + return new Dexie__default["default"].Promise(function (resolve, reject) { + var indexedDB = Dexie__default["default"].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__default["default"]("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", + 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__default["default"]("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__default["default"].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__default["default"].delete("issue713")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]('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__default["default"]('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__default["default"].delete("issue713Short")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]('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__default["default"]('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__default["default"].delete("changePrimKey")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]("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__default["default"]("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__default["default"].delete("changePrimKeyShort")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]("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__default["default"]("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__default["default"].delete("issue919")]; + case 1: + _g.sent(); + db = new Dexie__default["default"]("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__default["default"]("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__default["default"].delete(DBNAME)]; + case 1: + _a.sent(); + db = new Dexie__default["default"](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__default["default"](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__default["default"].delete("issue959")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]("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__default["default"]("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*/]; + } + }); + }); }); + promisedTest("Issue 1145 - Regression: SchemaError during version upgrade", function () { return __awaiter(void 0, void 0, void 0, function () { + var DBNAME, db, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + DBNAME = "issue1145"; + return [4 /*yield*/, Dexie__default["default"].delete(DBNAME)]; + case 1: + _a.sent(); + db = new Dexie__default["default"](DBNAME); + db.version(1).stores({ Y: "id" }); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + return [4 /*yield*/, db.close()]; + case 3: + _a.sent(); + db.version(2).upgrade(function (trans) { + QUnit.ok(true, "Starting version 2 upgrade."); + return trans.Y.count(); + }); + db.version(3).stores({ + Y: "id,X", + }); + db.version(4).upgrade(function (trans) { + QUnit.ok(true, "Starting version 4 upgrade."); + return trans.Y.where("X").equals("value").toArray(); + }); + _a.label = 4; + case 4: + _a.trys.push([4, 6, 7, 9]); + return [4 /*yield*/, db.open()]; + case 5: + _a.sent(); + QUnit.ok(true, "Open successful"); + return [3 /*break*/, 9]; + case 6: + e_1 = _a.sent(); + QUnit.ok(false, "Open Failed:: " + e_1); + return [3 /*break*/, 9]; + case 7: return [4 /*yield*/, db.delete()]; + case 8: + _a.sent(); + return [7 /*endfinally*/]; + case 9: return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue 1418 - Not deleting all object stores", function () { return __awaiter(void 0, void 0, void 0, function () { + var DBNAME, db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("deleteObjectStoreAfterRead")) { + QUnit.ok(true, "Skipping this test - buggy browser."); + return [2 /*return*/]; + } + if (Dexie__default["default"].addons.length > 0) { + QUnit.ok(true, "Skipping this test - default addons are acitve and can add more object stores"); + return [2 /*return*/]; + } + DBNAME = "issue1418"; + return [4 /*yield*/, Dexie__default["default"].delete(DBNAME)]; + case 1: + _a.sent(); + db = new Dexie__default["default"](DBNAME); + db.version(1).stores({ + a: '++', + b: '++', + c: '++', + d: '++', + e: '++' + }); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + QUnit.equal(db.idbdb.objectStoreNames.length, 5, "There are 5 object stores"); + db.close(); + db = new Dexie__default["default"](DBNAME); + db.version(2).stores({ + a: null, + b: null, + c: null, + d: null, + e: '++' + }); + return [4 /*yield*/, db.open()]; + case 3: + _a.sent(); + QUnit.equal(db.idbdb.objectStoreNames.length, 1, "There is only one object store now"); + db.close(); + return [4 /*yield*/, Dexie__default["default"].delete(DBNAME)]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var async$1 = Dexie__default["default"].async; + var db$4 = new Dexie__default["default"]("TestIssuesDB"); + db$4.version(1).stores({ + users: "id,first,last,&username,*&email,*pets", + keyless: ",name", + foo: "id", + bars: "++id,text", + metrics: "id,[name+time]", + // If required for your test, add more tables here + }); + QUnit.module("misc", { + setup: function () { + QUnit.stop(); + resetDatabase(db$4).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, err_2, err_3, 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$4.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$4.foo.add({ id: 1, foo: "bar" })]; + case 5: + _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$4.foo.get(false)]; + case 8: + _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$4.foo.where({ id: 1 }) + .modify({ id: 2, foo: "bar" })]; + case 11: + _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$4.keyless.add({ name: "foo" }, 1).then(function (id) { + QUnit.equal(id, 1, "Normal case ok - Object with key 1 was successfully added."); + return db$4.keyless.add({ name: "bar" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could add a numeric falsy value (0)"); + return db$4.keyless.add({ name: "foobar" }, ""); + }).then(function (id) { + QUnit.equal(id, "", "Could add a string falsy value ('')"); + return db$4.keyless.put({ name: "bar2" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could put a numeric falsy value (0)"); + return db$4.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__default["default"](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__default["default"](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__default["default"].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__default["default"](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__default["default"](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__default["default"](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$1(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$4.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$4.foo.hook('creating', creatingHook); + db$4.foo.hook('reading', readingHook); + db$4.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$4.foo.add({ id: 1, date: testDate }); + return [4 /*yield*/, db$4.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$4.foo.put({ id: 1, date: testDate2 }); + return [4 /*yield*/, db$4.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$4.foo.hook('creating').unsubscribe(creatingHook); + db$4.foo.hook('reading').unsubscribe(readingHook); + db$4.foo.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("Issue: Broken Promise rejection #264", 1, function () { + db$4.open().then(function () { + return db$4.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: false, + configurable: true + }); + return Foo; + }()); + db$4.foo.mapToClass(Foo); + db$4.transaction('rw', db$4.foo, function () { + db$4.foo.put({ id: 1 }); + db$4.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$4.foo.get(1); + }).then(function (foo) { + return db$4.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$4.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$4.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$4.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$4.transaction('rw', db$4.foo, function () { + var i; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$4.foo.put({ id: 1, value: 0 })]; + case 1: + _a.sent(); + for (i = 0; i < NUM_UPDATES; ++i) { + db$4.foo.where('id').equals(1).modify(function (item) { return ++item.value; }); + } + return [4 /*yield*/, db$4.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__default["default"].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$4.foo.mapToClass(Foo); + db$4.transaction('rw', db$4.foo, function () { + db$4.foo.put({ id: 1 }); + }).catch(function (e) { + QUnit.ok(true, "Unexpected error from put: " + (e.stack || e)); + }).then(function () { + return db$4.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$4.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.asyncTest("PR #1108", function () { return __awaiter(void 0, void 0, void 0, function () { + var origConsoleWarn, warnings, DBNAME, db_1, error_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE || isEdge) { + QUnit.ok(true, "Disabling this test for IE and legacy Edge"); + QUnit.start(); + return [2 /*return*/]; + } + origConsoleWarn = console.warn; + warnings = []; + console.warn = function (msg) { warnings.push(msg); return origConsoleWarn.apply(this, arguments); }; + _a.label = 1; + case 1: + _a.trys.push([1, 5, 6, 7]); + DBNAME = "PR1108"; + db_1 = new Dexie__default["default"](DBNAME); + db_1.version(1).stores({ + foo: "id" + }); + return [4 /*yield*/, db_1.open()]; + case 2: + _a.sent(); + QUnit.ok(!warnings.some(function (x) { return /SchemaDiff/.test(x); }), DBNAME + " could be opened without SchemaDiff warnings"); + db_1.close(); + // Adding an index without updating version number: + db_1 = new Dexie__default["default"](DBNAME); + db_1.version(1).stores({ + foo: "id,name" + }); + warnings = []; + return [4 /*yield*/, db_1.open()]; + case 3: + _a.sent(); + QUnit.ok(warnings.some(function (x) { return /SchemaDiff/.test(x); }), "Should warn when a new index was declared without incrementing version number"); + db_1.close(); + warnings = []; + // Adding a table without updating version number: + db_1 = new Dexie__default["default"](DBNAME); + db_1.version(1).stores({ + foo: "id", + bar: "" + }); + return [4 /*yield*/, db_1.open()]; + case 4: + _a.sent(); + QUnit.ok(warnings.some(function (x) { return /SchemaDiff/.test(x); }), "Should warn when a new table was declared without incrementing version number"); + db_1.close(); + warnings = []; + return [3 /*break*/, 7]; + case 5: + error_1 = _a.sent(); + QUnit.ok(false, error_1); + return [3 /*break*/, 7]; + case 6: + console.warn = origConsoleWarn; + QUnit.start(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("Issue #1112", function () { return __awaiter(void 0, void 0, void 0, function () { + function Bar(text) { + this.id = undefined; + this.text = text; + } + var id1, id2, id3, id4, bar3, bar3_2, error_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 8, 9, 10]); + return [4 /*yield*/, db$4.bars.add(new Bar("hello1"))]; + case 1: + id1 = _a.sent(); + QUnit.ok(!isNaN(id1), "got a real autoincremented id for my bar using add()"); + return [4 /*yield*/, db$4.bars.put(new Bar("hello2"))]; + case 2: + id2 = _a.sent(); + QUnit.ok(!isNaN(id2), "got a real autoincremented id for my bar using put()"); + return [4 /*yield*/, db$4.bars.bulkAdd([new Bar("hello3")])]; + case 3: + id3 = _a.sent(); + QUnit.ok(!isNaN(id3), "got a real autoincremented id for my bar using bulkAdd()"); + return [4 /*yield*/, db$4.bars.bulkPut([new Bar("hello4")])]; + case 4: + id4 = _a.sent(); + QUnit.ok(!isNaN(id4), "got a real autoincremented id for my bar using bulkPut()"); + return [4 /*yield*/, db$4.bars.get(id3)]; + case 5: + bar3 = _a.sent(); + QUnit.equal(bar3.text, "hello3", "Should get the object with text hello3"); + bar3.text = "hello3 modified"; + return [4 /*yield*/, db$4.bars.put(bar3)]; + case 6: + _a.sent(); + return [4 /*yield*/, db$4.bars.get(id3)]; + case 7: + bar3_2 = _a.sent(); + QUnit.equal(bar3_2.text, "hello3 modified", "Could successfully change a prop and put back."); + return [3 /*break*/, 10]; + case 8: + error_2 = _a.sent(); + QUnit.ok(false, error_2); + return [3 /*break*/, 10]; + case 9: + QUnit.start(); + return [7 /*endfinally*/]; + case 10: return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("Issue #1280 - Don't perform deep-clone workaround when adding non-POJO to auto-incrementing table", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, db$4.bars.add({ text: "hello1", fooProp: function () { } })]; + case 1: + _a.sent(); + QUnit.ok(false, "Expected add() to fail since IDB would fail with DOMError if trying to store a function."); + return [3 /*break*/, 4]; + case 2: + _a.sent(); + QUnit.ok(true); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue #1333 - uniqueKeys on virtual index should produce unique results", function () { return __awaiter(void 0, void 0, void 0, function () { + var result; + 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$4.metrics.add({ id: "id1", name: "a", time: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$4.metrics.add({ id: "id2", name: "b", time: 2 })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$4.metrics.add({ id: "id3", name: "a", time: 3 })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$4.metrics.orderBy("name").uniqueKeys()]; + case 4: + result = _a.sent(); + QUnit.ok(result.length === 2, "Unexpected array length " + result.length + " from uniqueKeys on virtual index, expected 2. Got " + result.join(',')); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue #1890 - BigInt64Array getting corrupted after an update", function () { return __awaiter(void 0, void 0, void 0, function () { + var val; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (typeof BigInt64Array === 'undefined') { + QUnit.ok(true, "BigInt64Array not supported in browser"); + return [2 /*return*/]; + } + if (typeof ((_a = Dexie__default["default"].Observable) === null || _a === void 0 ? void 0 : _a.version) === 'string') { + QUnit.ok(true, "Skipping this test - Dexie.Observable bails out from BigInts"); + return [2 /*return*/]; + } + return [4 /*yield*/, db$4.foo.put({ + id: 1, + updated: Date.now(), + cols: [{ + values: new BigInt64Array([BigInt(1), BigInt(2)]) + }] + })]; + case 1: + _b.sent(); + return [4 /*yield*/, db$4.foo.get(1)]; + case 2: + val = _b.sent(); + QUnit.ok(val.cols[0].values instanceof BigInt64Array, "cols[0].values is a BigInt64Array"); + return [4 /*yield*/, db$4.foo.update(1, { + updated: Date.now() + })]; + case 3: + _b.sent(); + return [4 /*yield*/, db$4.foo.get(1)]; + case 4: + val = _b.sent(); + QUnit.ok(val.cols[0].values instanceof BigInt64Array, "cols[0].values is still a BigInt64Array after update"); + return [2 /*return*/]; + } + }); + }); }); + + QUnit.module("promise"); + //Dexie.debug = "dexie"; + function createDirectlyResolvedPromise() { + return new Dexie__default["default"].Promise(function (resolve) { + resolve(); + }); + } + QUnit.asyncTest("Promise basics", function () { + new Dexie__default["default"].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__default["default"].Promise(function (resolve) { return resolve("value"); }) + .then(function (value) { + return Dexie__default["default"].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__default["default"].Promise(function (resolve) { return resolve("value"); }) + .then(function (value) { + return new Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"]("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__default["default"].Promise.newPSD(function () { + Dexie__default["default"].Promise.PSD.hello = "promise land"; + Dexie__default["default"].Promise.resolve().then(function () { + QUnit.ok(!!Dexie__default["default"].Promise.PSD, "We should have a Dexie.Promise.PSD"); + QUnit.equal(Dexie__default["default"].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__default["default"].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__default["default"].Promise(function (resolve, reject) { + new Dexie__default["default"].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__default["default"].Promise(function (resolve, reject) { + new Dexie__default["default"].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__default["default"]("TestDB"); + db.version(1).stores({ + activities: "Oid,Task,Tick,Tock,Type,Flags", + tasks: "Oid,Name,Parent" + }); + 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__default["default"].Promise.newPSD(function () { + Dexie__default["default"].currentTransaction._lock(); + db.activities.where("Type").equals(2).modify({ Flags: 2 }).finally(function () { + Dexie__default["default"].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__default["default"].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__default["default"].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)"); + }); + + var Promise$1 = Dexie__default["default"].Promise, all = Promise$1.all, async = Dexie__default["default"].async; Dexie__default["default"].spawn; + var db$3 = new Dexie__default["default"]("TestDBCrudHooks"); + db$3.version(1).stores({ + table1: "id,idx", + table2: ",&idx", + table3: "++id,&idx", + table4: "++,&idx", + table5: "" + }); + var ourTables = [db$3.table1, db$3.table2, db$3.table3, db$3.table4, db$3.table5]; + var opLog = [], successLog = [], errorLog = [], watchSuccess = false, watchError = false, deliverKeys = [], deliverModifications = null, deliverKeys2 = [], deliverModifications2 = null, opLog2 = [], successLog2 = [], errorLog2 = [], 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(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() { } + 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__default["default"].currentTransaction }); + var op = { + op: "create", + key: primKey, + value: Dexie__default["default"].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__default["default"].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__default["default"].deepClone(obj) + }); + return { theObject: obj }; + } + function reading2(obj) { + opLog2.push({ + op: "read", + obj: Dexie__default["default"].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__default["default"].currentTransaction }); + var op = { + op: "update", + key: primKey, + obj: Dexie__default["default"].deepClone(obj), + mods: Dexie__default["default"].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__default["default"].deepClone(obj), + mods: Dexie__default["default"].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__default["default"].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$3).then(function () { return reset(); }).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + unsubscribeHooks(); + } + }); + var expect = async(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(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$3.transaction('rw', db$3.tables, function () { + db$3.table1.add({ id: 1, idx: 11 }); + db$3.table2.add({ idx: 12 }, 2); + db$3.table3.add({ idx: 13 }); + db$3.table4.add({ idx: 14 }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$3.table1.add({ id: 1 }).catch(nop)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table2.add({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$3.table2.add({}, 1).catch(nop)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table1.add({ id: {} }).catch(nop)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', db$3.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$3.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$3.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$3.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$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.put({ idx: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$3.table3.put({ idx: 1 }).catch(nop)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table2.put({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$3.table2.put({}, 1).catch(nop)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table3.put({ id: {} }).catch(nop)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + db$3.table1.bulkAdd([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }]); + db$3.table2.bulkAdd([{ idx: 12 }, { idx: 12.2 }], [2, 2.2]); + db$3.table3.bulkAdd([{ idx: 13 }, { idx: 13.2 }]); + db$3.table4.bulkAdd([{ idx: 14 }, { idx: 14.2 }]); + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.bulkAdd([{ id: 1 }, { id: 1 }]).catch(nop)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$3.table1.bulkAdd([{ id: 2 }, { id: 2 }, { id: 3 }]).catch(nop)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$3.table2.bulkAdd([{}, {}], [1, 1]).catch(nop)]; + case 3: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$3.table2.bulkAdd([{}, {}, {}], [2, 2, 3]).catch(nop)]; + case 4: + _a.sent(); // 1. success, 2. error event. 3. success. + return [4 /*yield*/, db$3.table1.bulkAdd([{ id: {} }]).catch(nop)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.bulkPut([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table2.bulkPut([{ idx: 12 }, { idx: 12.2 }], [2, 2.2])]; + case 2: + _a.sent(); + return [4 /*yield*/, db$3.table3.bulkPut([{ idx: 13 }, { idx: 13.2 }])]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.bulkPut([{ idx: 1 }, { idx: 1 }]).catch(nop)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$3.table3.bulkPut([{ idx: 2 }, { idx: 2 }, { idx: 3 }]).catch(nop)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$3.table1.bulkPut([{ id: {} }]).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', 'table5', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table5.bulkAdd([{ foo: "bar" }, { fee: "bore" }], [1, 2])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table5.toArray()]; + case 2: + _a.sent(); + return [4 /*yield*/, db$3.table5.reverse().each(function (x) { })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.table5.orderBy(':id').first()]; + case 4: + _a.sent(); + return [4 /*yield*/, db$3.table5.orderBy(':id').last()]; + case 5: + _a.sent(); + return [4 /*yield*/, db$3.table5.bulkGet([1, 2])]; + case 6: + _a.sent(); + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + db$3.table1.put({ id: 1, address: { city: 'A' } }); // create + db$3.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.add({ id: 1, idx: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table3.put({ id: 2, idx: 1 }).catch(nop)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$3.table3.put({ id: {} }).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + db$3.table1.put({ id: 1, address: { city: 'A' } }); // create + db$3.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table4.add({ idx: 1 }, 1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table4.bulkPut([{ idx: 1 }], [2]).catch(nop)]; + case 2: + _a.sent(); // error event (DataError) + return [4 /*yield*/, db$3.table3.bulkPut([{}], [{}]).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table3.update(1, { idx: 2 }).catch(nop)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$3.table3.update(1, 3).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception? + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table3.where('id').equals(1).modify({ idx: 2 }).catch(nop)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$3.table3.where('id').equals(1).modify(function () { throw "apa"; }).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + 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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.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$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.where('id').between(0, 2).delete()]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + promisedTest("issue #1195 Update with array as value adds number objects", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "update", + key: 1, + obj: { id: 1 }, + mods: { authors: [{ foo: "bar" }] }, + updatedObj: { id: 1, authors: [{ foo: "bar" }] }, + }, { + op: "update", + key: 1, + obj: { id: 1, authors: [{ foo: "bar" }] }, + mods: { authors: [] }, + updatedObj: { id: 1, authors: [] }, + }, { + op: "update", + key: 1, + obj: { id: 1, authors: [] }, + mods: { authors: [{ name: "foo" }, { name: "bar" }] }, + updatedObj: { id: 1, authors: [{ name: "foo" }, { name: "bar" }] }, + }], function () { return db$3.transaction('rw', db$3.table1, 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.table1.add({ id: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [{ foo: "bar" }] })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [] })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [{ name: "foo" }, { name: "bar" }] })]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("issue #1270 Modification object in updating hook not correct when changing array", function () { return __awaiter(void 0, void 0, void 0, function () { + var buffer1, buffer2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + // Test sub-array + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, authors: [{ name: "foo" }] } + }, { + op: "update", + key: 1, + obj: { id: 1, authors: [{ name: "foo" }] }, + mods: { authors: [{ name: "bar" }] }, + updatedObj: { id: 1, authors: [{ name: "bar" }] }, + }], function () { return db$3.transaction('rw', db$3.table1, 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.table1.add({ id: 1, authors: [{ name: "foo" }] })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [{ name: "bar" }] })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 1: + // Test sub-array + _a.sent(); + // Test sub-object + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, author: { name: "foo" } } + }, { + op: "update", + key: 1, + obj: { id: 1, author: { name: "foo" } }, + mods: { "author.name": "bar" }, + updatedObj: { id: 1, author: { name: "bar" } }, + }], function () { return db$3.transaction('rw', db$3.table1, 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.table1.add({ id: 1, author: { name: "foo" } })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, author: { name: "bar" } })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 2: + // Test sub-object + _a.sent(); + buffer1 = new Uint8Array(8).fill(1); + buffer2 = new Uint8Array(8).fill(2); + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, author: { buf: buffer1 } } + }, { + op: "update", + key: 1, + obj: { id: 1, author: { buf: buffer1 } }, + mods: { "author.buf": buffer2 }, + updatedObj: { id: 1, author: { buf: buffer2 } }, + }], function () { return db$3.transaction('rw', db$3.table1, 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.table1.add({ id: 1, author: { buf: buffer1 } })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, author: { buf: buffer2 } })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 3: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var db$2 = new Dexie__default["default"]("TestDBBinary"); + db$2.version(1).stores({ + items: "id" + }); + QUnit.module("blobs", { + setup: function () { + QUnit.stop(); + resetDatabase(db$2).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$2.items.add({ id: 1, blob: blob })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$2.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$2.items.hook('updating', updatingHook); + binaryData = new Uint8Array([1, 2, 3, 4]); + blob = new Blob([binaryData], { type: 'application/octet-binary' }); + return [4 /*yield*/, db$2.items.add({ id: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$2.items.put({ id: 1, blob: blob })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$2.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$2.items.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); }); + + var db$1 = new Dexie__default["default"]("TestDBBinaryKeys"); + db$1.version(1).stores({ + items: "id,data" + }); + db$1.on('populate', function () { + db$1.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$1).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$1.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$1.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$1.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$1.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$1.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$1.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$1.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$1.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$1.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$1.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$1.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*/]; + } + }); + }); }); + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var sortedJson = createCommonjsModule(function (module, exports) { + var NON_SORTABLE_TYPES = ['undefined', 'string', 'number', 'boolean', 'function']; + var DEFAULT_SORT_OPTIONS = { + sortBy : undefined, + sortKey : true, + sortArray: false, + + stringify: false, + replacer : null, + space : null, + }; + + var _sortify = function(obj, options) { + for (var i = 0; i < NON_SORTABLE_TYPES.length; i++) { + if (NON_SORTABLE_TYPES[i] === typeof obj || obj === null) { + return obj; + } + } + + if (Array.isArray(obj)) { + if (options.sortArray === true) { + obj.sort(options.sortBy); + } + + for (var i = 0; i < obj.length; i++) { + obj[i] = _sortify(obj[i], options); + } + + return obj; + + } else { + if (options.sortKey === true) { + var sortedObj = {}; + var keyList = []; + + for (var k in obj) { + keyList.push(k); + } + keyList.sort(options.sortBy); + + for (var i = 0; i < keyList.length; i++) { + var k = keyList[i]; + var v = obj[k]; + + sortedObj[k] = _sortify(v, options); + } + + return sortedObj; + + } else { + for (var k in obj) { + obj[k] = _sortify(obj[k], options); + } + + return obj; + } + } + }; + + exports.sortify = function(obj, options) { + if (!options) { + options = {}; + } + + for (var k in DEFAULT_SORT_OPTIONS) if (DEFAULT_SORT_OPTIONS.hasOwnProperty(k)) { + var v = DEFAULT_SORT_OPTIONS[k]; + + if (!(k in options)) { + options[k] = v; + } + } + + var result = _sortify(obj, options); + if (options.stringify === true) { + result = JSON.stringify(result, options.replacer, options.space); + } + + return result; + }; + + /* Deprecated Code below */ + var _stringify = function(obj, compareFunction) { + if (typeof obj == 'string') { + return '"' + obj + '"'; + } + else if (typeof obj == 'number') { + return obj; + } + else if (typeof obj == 'boolean') { + return obj; + } + else if (typeof obj == 'function') { + return '""'; + } + else if (typeof obj == 'object') { + if (Array.isArray(obj)) { + var parts = []; + for (var i = 0; i < obj.length; i++) { + var v = exports.stringify(obj[i], compareFunction); + parts.push(v); + } + + return '[' + parts.join(',') + ']'; + } + else { + var keyList = []; + for (var k in obj) { + keyList.push(k); + } + keyList.sort(compareFunction); + + var parts = []; + for (var i = 0; i < keyList.length; i++) { + var k = keyList[i]; + var v = exports.stringify(obj[k], compareFunction); + + parts.push('"' + k + '":' + v); + } + return '{' + parts.join(',') + '}'; + } + } + else { + return '""'; + } + }; + + exports.stringify = function(obj, compareFunction) { + console.log("The stringify() function is DEPRECATED. Please use sortify() instead."); + + return _stringify(obj, compareFunction); + }; + }); + sortedJson.sortify; + sortedJson.stringify; + + /*! ***************************************************************************** + 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 __()); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isFunction(x) { + return typeof x === 'function'; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var _enable_super_gross_mode_that_will_cause_bad_things = false; + var config = { + Promise: undefined, + set useDeprecatedSynchronousErrorHandling(value) { + if (value) { + var error = /*@__PURE__*/ new Error(); + /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); + } + _enable_super_gross_mode_that_will_cause_bad_things = value; + }, + get useDeprecatedSynchronousErrorHandling() { + return _enable_super_gross_mode_that_will_cause_bad_things; + }, + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function hostReportError(err) { + setTimeout(function () { throw err; }, 0); + } + + /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ + var empty = { + closed: true, + next: function (value) { }, + error: function (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + }, + complete: function () { } + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isObject(x) { + return x !== null && typeof x === 'object'; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { + function UnsubscriptionErrorImpl(errors) { + Error.call(this); + this.message = errors ? + errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; + this.name = 'UnsubscriptionError'; + this.errors = errors; + return this; + } + UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return UnsubscriptionErrorImpl; + })(); + var UnsubscriptionError = UnsubscriptionErrorImpl; + + /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ + var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parentOrParents = null; + this._subscriptions = null; + if (unsubscribe) { + this._ctorUnsubscribe = true; + this._unsubscribe = unsubscribe; + } + } + Subscription.prototype.unsubscribe = function () { + var errors; + if (this.closed) { + return; + } + var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parentOrParents = null; + this._subscriptions = null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } + } + if (isFunction(_unsubscribe)) { + if (_ctorUnsubscribe) { + this._unsubscribe = undefined; + } + try { + _unsubscribe.call(this); + } + catch (e) { + errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; + } + } + if (isArray(_subscriptions)) { + var index = -1; + var len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (isObject(sub)) { + try { + sub.unsubscribe(); + } + catch (e) { + errors = errors || []; + if (e instanceof UnsubscriptionError) { + errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); + } + else { + errors.push(e); + } + } + } + } + } + if (errors) { + throw new UnsubscriptionError(errors); + } + }; + Subscription.prototype.add = function (teardown) { + var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; + } + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (!(subscription instanceof Subscription)) { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: { + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } + } + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; + } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); + } + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; + }()); + function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var rxSubscriber = /*@__PURE__*/ (function () { + return typeof Symbol === 'function' + ? /*@__PURE__*/ Symbol('rxSubscriber') + : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); + })(); + + /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ + var Subscriber = /*@__PURE__*/ (function (_super) { + __extends(Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + switch (arguments.length) { + case 0: + _this.destination = empty; + break; + case 1: + if (!destinationOrNext) { + _this.destination = empty; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; + } + return _this; + } + Subscriber.prototype[rxSubscriber] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parentOrParents = _parentOrParents; + return this; + }; + return Subscriber; + }(Subscription)); + var SafeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (isFunction(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== empty) { + context = Object.create(observerOrNext); + if (isFunction(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + hostReportError(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + hostReportError(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!config.useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + hostReportError(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; + }(Subscriber)); + + /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ + function canReportError(observer) { + while (observer) { + var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; + if (closed_1 || isStopped) { + return false; + } + else if (destination && destination instanceof Subscriber) { + observer = destination; + } + else { + observer = null; + } + } + return true; + } + + /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ + function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver) { + if (nextOrObserver instanceof Subscriber) { + return nextOrObserver; + } + if (nextOrObserver[rxSubscriber]) { + return nextOrObserver[rxSubscriber](); + } + } + if (!nextOrObserver && !error && !complete) { + return new Subscriber(empty); + } + return new Subscriber(nextOrObserver, error, complete); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function identity(x) { + return x; + } + + /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ + function pipeFromArray(fns) { + if (fns.length === 0) { + return identity; + } + if (fns.length === 1) { + return fns[0]; + } + return function piped(input) { + return fns.reduce(function (prev, fn) { return fn(prev); }, input); + }; + } + + /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ + var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = toSubscriber(observerOrNext, error, complete); + if (operator) { + sink.add(operator.call(sink, this.source)); + } + else { + sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (config.useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (canReportError(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[observable] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return pipeFromArray(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; + }()); + function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = config.Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var subscribeToArray = function (array) { + return function (subscriber) { + for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { + subscriber.next(array[i]); + } + subscriber.complete(); + }; + }; + + /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ + function scheduleArray(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + var i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); + } + + /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + function map(project, thisArg) { + return function mapOperation(source) { + if (typeof project !== 'function') { + throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); + } + return source.lift(new MapOperator(project, thisArg)); + }; + } + var MapOperator = /*@__PURE__*/ (function () { + function MapOperator(project, thisArg) { + this.project = project; + this.thisArg = thisArg; + } + MapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); + }; + return MapOperator; + }()); + var MapSubscriber = /*@__PURE__*/ (function (_super) { + __extends(MapSubscriber, _super); + function MapSubscriber(destination, project, thisArg) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.count = 0; + _this.thisArg = thisArg || _this; + return _this; + } + MapSubscriber.prototype._next = function (value) { + var result; + try { + result = this.project.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return MapSubscriber; + }(Subscriber)); + + /** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ + var subscribeToPromise = function (promise) { + return function (subscriber) { + promise.then(function (value) { + if (!subscriber.closed) { + subscriber.next(value); + subscriber.complete(); + } + }, function (err) { return subscriber.error(err); }) + .then(null, hostReportError); + return subscriber; + }; + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function getSymbolIterator() { + if (typeof Symbol !== 'function' || !Symbol.iterator) { + return '@@iterator'; + } + return Symbol.iterator; + } + var iterator = /*@__PURE__*/ getSymbolIterator(); + + /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ + var subscribeToIterable = function (iterable) { + return function (subscriber) { + var iterator$1 = iterable[iterator](); + do { + var item = void 0; + try { + item = iterator$1.next(); + } + catch (err) { + subscriber.error(err); + return subscriber; + } + if (item.done) { + subscriber.complete(); + break; + } + subscriber.next(item.value); + if (subscriber.closed) { + break; + } + } while (true); + if (typeof iterator$1.return === 'function') { + subscriber.add(function () { + if (iterator$1.return) { + iterator$1.return(); + } + }); + } + return subscriber; + }; + }; + + /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ + var subscribeToObservable = function (obj) { + return function (subscriber) { + var obs = obj[observable](); + if (typeof obs.subscribe !== 'function') { + throw new TypeError('Provided object does not correctly implement Symbol.observable'); + } + else { + return obs.subscribe(subscriber); + } + }; + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isPromise(value) { + return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; + } + + /** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ + var subscribeTo = function (result) { + if (!!result && typeof result[observable] === 'function') { + return subscribeToObservable(result); + } + else if (isArrayLike(result)) { + return subscribeToArray(result); + } + else if (isPromise(result)) { + return subscribeToPromise(result); + } + else if (!!result && typeof result[iterator] === 'function') { + return subscribeToIterable(result); + } + else { + var value = isObject(result) ? 'an invalid object' : "'" + result + "'"; + var msg = "You provided " + value + " where a stream was expected." + + ' You can provide an Observable, Promise, Array, or Iterable.'; + throw new TypeError(msg); + } + }; + + /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ + function scheduleObservable(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + var observable$1 = input[observable](); + sub.add(observable$1.subscribe({ + next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, + error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, + complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, + })); + })); + return sub; + }); + } + + /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ + function schedulePromise(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + return input.then(function (value) { + sub.add(scheduler.schedule(function () { + subscriber.next(value); + sub.add(scheduler.schedule(function () { return subscriber.complete(); })); + })); + }, function (err) { + sub.add(scheduler.schedule(function () { return subscriber.error(err); })); + }); + })); + return sub; + }); + } + + /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ + function scheduleIterable(input, scheduler) { + if (!input) { + throw new Error('Iterable cannot be null'); + } + return new Observable(function (subscriber) { + var sub = new Subscription(); + var iterator$1; + sub.add(function () { + if (iterator$1 && typeof iterator$1.return === 'function') { + iterator$1.return(); + } + }); + sub.add(scheduler.schedule(function () { + iterator$1 = input[iterator](); + sub.add(scheduler.schedule(function () { + if (subscriber.closed) { + return; + } + var value; + var done; + try { + var result = iterator$1.next(); + value = result.value; + done = result.done; + } + catch (err) { + subscriber.error(err); + return; + } + if (done) { + subscriber.complete(); + } + else { + subscriber.next(value); + this.schedule(); + } + })); + })); + return sub; + }); + } + + /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ + function isInteropObservable(input) { + return input && typeof input[observable] === 'function'; + } + + /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ + function isIterable(input) { + return input && typeof input[iterator] === 'function'; + } + + /** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ + function scheduled(input, scheduler) { + if (input != null) { + if (isInteropObservable(input)) { + return scheduleObservable(input, scheduler); + } + else if (isPromise(input)) { + return schedulePromise(input, scheduler); + } + else if (isArrayLike(input)) { + return scheduleArray(input, scheduler); + } + else if (isIterable(input) || typeof input === 'string') { + return scheduleIterable(input, scheduler); + } + } + throw new TypeError((input !== null && typeof input || input) + ' is not observable'); + } + + /** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ + function from(input, scheduler) { + if (!scheduler) { + if (input instanceof Observable) { + return input; + } + return new Observable(subscribeTo(input)); + } + else { + return scheduled(input, scheduler); + } + } + + var db = new Dexie__default["default"]("TestLiveQuery"); + db.version(2).stores({ + items: "id, name", + foo: "++id", + outbound: "++,name", + friends: "++id, name, age", + multiEntry: "id, *tags" + }); + db.on('populate', function () { + db.items.bulkAdd([ + { id: 1 }, + { id: 2 }, + { id: 3 } + ]); + db.outbound.bulkAdd([ + { num: 1, name: "A" }, + { num: 2, name: "B" }, + { num: 3, name: "C" } + ], [1, 2, 3]); + }); + function objectify(map) { + var rv = {}; + map.forEach(function (value, name) { + rv[name] = value; + }); + return rv; + } + function deepEqual(actual, expected, description) { + actual = sortedJson.sortify(actual, { sortArray: false }); + expected = sortedJson.sortify(expected, { sortArray: false }); + QUnit.equal(JSON.stringify(actual, null, 2), JSON.stringify(expected, null, 2), description); + } + var Signal = /** @class */ (function () { + function Signal() { + var _this = this; + this.promise = new Promise(function (resolve) { return _this.resolve = resolve; }); + } + return Signal; + }()); + QUnit.module("live-query", { + setup: function () { + QUnit.stop(); + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + /*promisedTest("txcommitted event", async ()=>{ + let signal = new Signal(); + let os = {}; + function txCommitted(observabilitySet) { + Dexie.extendObservabilitySet(os, observabilitySet); + signal.resolve(observabilitySet); + } + await db.open(); + Dexie.on('txcommitted', txCommitted); + await db.transaction('rw', db.items, db.foo, async ()=>{ + await db.items.add({id: 4, name: "aiwo1"}); + await db.items.add({id: 7, name: "kjlj"}); + await db.foo.add({name: "jkll"}); + await db.items.update(1, {name: "A"}); + }); + while (!os.TestLiveQuery || !os.TestLiveQuery.items || !hasKey(os.TestLiveQuery.items.keys, 4)) { + // When Dexie.Observable is active, we might see intermediate transactions taking place + // before our transaction. + signal = new Signal(); + await signal.promise; + console.log("got new os:", os); + } + ok(!!os.TestLiveQuery, "Got changes in our table name TestLiveQuery"); + let itemsChanges = os.TestLiveQuery.items; + ok(itemsChanges, "Got changes for items table"); + deepEqual(itemsChanges.keys, rangeSet([[4], [7], [1]]), "Item changes on concattenated keys"); + deepEqual(itemsChanges.indexes, {"": rangeSet([[4],[7]]),name: rangeSet([["aiwo1"],["kjlj"],["A"]])}, "Index changes present"); + + // Foo changes (auto-incremented id) + let fooChanges = os.TestLiveQuery.foo; + ok(fooChanges, "Got changes for foo table"); + + os = {}; + let fooIds = await db.foo.toCollection().primaryKeys(); + await db.transaction('rw', db.items, db.foo, async ()=>{ + await db.items.update(4, {name: "aiwo2"}); + await db.foo.where('id').between(0, 1000).delete(); + }); + while (!os.TestLiveQuery || !os.TestLiveQuery.items || !hasKey(os.TestLiveQuery.items.keys, 4)) { + // When Dexie.Observable is active, we might see intermediate transactions taking place + // before our transaction. + signal = new Signal(); + await signal.promise; + } + itemsChanges = os.TestLiveQuery.items; + ok(hasKey(itemsChanges.keys, 4), "Item 4 was updated"); + ok(hasKey(itemsChanges.indexes.name, "aiwo1"), "Old value of name index were triggered"); + ok(hasKey(itemsChanges.indexes.name, "aiwo2"), "New value of name index were triggered"); + + fooChanges = os.TestLiveQuery.foo; + ok(!!fooChanges, "Foo table changed"); + if (hasKey(fooChanges.keys, 0) && hasKey(fooChanges.keys, 1000)) { + // Without addons: + deepEqual(fooChanges.keys, rangeSet([[0, 1000]]), "Got a range update of foo keys 0..1000"); + } else { + // With hooks / addons or browser workarounds: + deepEqual(fooChanges.keys, rangeSet(fooIds.map(id => [id])), "Got individual delete updates of foo keys ", fooIds.join(',')); + } + + Dexie.on('txcommitted').unsubscribe(txCommitted); + });*/ + promisedTest("subscribe to range", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal, subscription, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + signal = new Signal(); + subscription = Dexie.liveQuery(function () { return db.items.toArray(); }).subscribe(function (result) { + signal.resolve(result); + }); + return [4 /*yield*/, signal.promise]; + case 1: + result = _a.sent(); + deepEqual(result, [{ id: 1 }, { id: 2 }, { id: 3 }], "First callback should give initally populated content"); + signal = new Signal(); + db.items.add({ id: -1 }); + return [4 /*yield*/, signal.promise]; + case 2: + result = _a.sent(); + deepEqual(result, [{ id: -1 }, { id: 1 }, { id: 2 }, { id: 3 }], "2nd callback should give updated content"); + signal = new Signal(); + db.items.delete(2); + return [4 /*yield*/, signal.promise]; + case 3: + result = _a.sent(); + deepEqual(result, [{ id: -1 }, { id: 1 }, { id: 3 }], "3rd callback should wake up when deletion was made"); + subscription.unsubscribe(); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("subscribe to keys", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal1, signal2, count1, count2, sub1, res1, sub2, res2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE) { + // The IE implementation becomes shaky here. + // Maybe becuase we launch several parallel queries to IDB. + QUnit.ok(true, "Skipping this test for IE - too shaky for the CI"); + return [2 /*return*/]; + } + signal1 = new Signal(), signal2 = new Signal(); + count1 = 0, count2 = 0; + sub1 = Dexie.liveQuery(function () { return db.items.get(1); }).subscribe(function (result) { + ++count1; + signal1.resolve(result); + }); + return [4 /*yield*/, signal1.promise]; + case 1: + res1 = _a.sent(); + QUnit.equal(res1.id, 1, "First result for ID 1 ok"); + QUnit.equal(count1, 1, "Callback called once"); + sub2 = Dexie.liveQuery(function () { return db.items.get(2); }).subscribe(function (result) { + ++count2; + signal2.resolve(result); + }); + return [4 /*yield*/, signal2.promise]; + case 2: + res2 = _a.sent(); + QUnit.equal(res2.id, 2, "2nd result for ID 2 ok"); + QUnit.equal(count2, 1, "2nd callback called once"); + QUnit.equal(count1, 1, "First callback wasn't called again"); + // Now mutate using update - verify listeners don't wake up on other than the keys the subscribe + signal1 = new Signal(); + signal2 = new Signal(); + return [4 /*yield*/, db.items.update(1, { name: "one" })]; + case 3: + _a.sent(); + QUnit.ok(true, "Could update item 1"); + return [4 /*yield*/, signal1.promise]; + case 4: + res1 = _a.sent(); + QUnit.equal(count1, 2, "First should have been called 2 times now"); + QUnit.equal(count2, 1, "2nd callback should still only have been called once"); + QUnit.equal(res1.name, "one", "We got the updated value from the expression"); + return [4 /*yield*/, db.items.update(2, { name: "two" })]; + case 5: + _a.sent(); + return [4 /*yield*/, signal2.promise]; + case 6: + res2 = _a.sent(); + QUnit.equal(count1, 2, "First should have been called 2 times now"); + QUnit.equal(count2, 2, "2nd callback should have been called twice also"); + QUnit.equal(res2.name, "two", "We got the updated value from the 2nd expression"); + // Now mutate using delete + signal1 = new Signal(); + signal2 = new Signal(); + return [4 /*yield*/, db.items.delete(1)]; + case 7: + _a.sent(); + return [4 /*yield*/, signal1.promise]; + case 8: + res1 = _a.sent(); + QUnit.equal(count1, 3, "First should have been called 3 times now"); + QUnit.equal(count2, 2, "2nd callback should still only have been called twice"); + QUnit.ok(res1 === undefined, "The updated result of db.items.get(1) should return undefined after the deletion"); + return [4 /*yield*/, db.items.delete(2)]; + case 9: + _a.sent(); + return [4 /*yield*/, signal2.promise]; + case 10: + res2 = _a.sent(); + QUnit.equal(count1, 3, "First should still have been called 3 times"); + QUnit.equal(count2, 3, "2nd callback should have been called 3 times also now"); + QUnit.ok(res2 === undefined, "The updated result of db.items.get(2) should return undefined after the deletion"); + // Verify that no more callbacks are called after unsubscribing + sub1.unsubscribe(); + sub2.unsubscribe(); + return [4 /*yield*/, db.items.update(1, { name: "fljkds" })]; + case 11: + _a.sent(); + QUnit.equal(count1, 3, "No more calls after having unsubscribed"); + return [4 /*yield*/, db.items.update(1, { name: "sfdfs" })]; + case 12: + _a.sent(); + QUnit.equal(count1, 3, "Just double-checking - no more calls after having unsubscribed"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("subscribe and error occur", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal, subscription, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + signal = new Signal(); + subscription = Dexie.liveQuery(function () { return db.items.get(NaN); } // NaN is not a valid key + ).subscribe({ + next: function (result) { return signal.resolve("success"); }, + error: function (result) { return signal.resolve("error"); }, + complete: function () { return signal.resolve("complete"); } + }); + QUnit.ok(!subscription.closed, "Subscription should not yet be closed"); + return [4 /*yield*/, signal.promise]; + case 1: + result = _a.sent(); + QUnit.equal(result, "error", "The observable's error callback should have been called"); + QUnit.ok(subscription.closed, "Subscription should have been closed after error has occurred"); + subscription.unsubscribe(); + return [2 /*return*/]; + } + }); + }); }); + /* Use cases to cover: + + Queries + get + getMany + query + queryKeys + itemsStartsWithAOffset3 + openKeyCursor + count + queryOutbound + queryOutboundByPKey + openCursorOutbound + + Mutations + add + addAuto + update + delete + deleteRange + */ + var abbaKey = 0; + var lastFriendId = 0; + var barbarFriendId = 0; + var fruitCount = 0; // A bug in Safari <= 13.1 makes it unable to count on the name index (adds 1 extra) + var bulkFriends = []; + for (var i = 0; i < 51; ++i) { + bulkFriends.push({ name: "name" + i, age: i }); + } + var bulkOutbounds = []; + for (var i = 0; i < 51; ++i) { + bulkOutbounds.push({ name: "z" + i.toLocaleString('en-US', { + minimumIntegerDigits: 2, + useGrouping: false + }) }); + } + var mutsAndExpects = function () { return [ + // add + [ + function () { return db.items.add({ id: -1, name: "A" }); }, + { + itemsToArray: [{ id: -1, name: "A" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "A" }], + itemsStartsWithA: [{ id: -1, name: "A" }], + itemsStartsWithAPrimKeys: [-1], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: ["A"], + itemsStartsWithACount: fruitCount + 1 + } + ], + // addAuto + [ + function () { return db.outbound.add({ name: "Abba" }).then(function (id) { return abbaKey = id; }); }, + { + outboundToArray: [{ num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }, { name: "Abba" }], + outboundStartsWithA: [{ name: "A", num: 1 }, { name: "Abba" }] + } + ], [ + function () { return db.outbound.bulkAdd([{ name: "Benny" }, { name: "C" }], [-1, 0]); }, + { + outboundToArray: [{ name: "Benny" }, { name: "C" }, { num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }, { name: "Abba" }], + outboundIdBtwnMinus1And2: [{ name: "Benny" }, { name: "C" }, { name: "A", num: 1 }, { name: "B", num: 2 }], + outboundAnyOf_BCD_keys: ["B", "C", "C"] + } + ], + // update + [ + function () { return db.outbound.update(abbaKey, { name: "Zlatan" }); }, + { + outboundToArray: [{ name: "Benny" }, { name: "C" }, { num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }, { name: "Zlatan" }], + outboundStartsWithA: [{ name: "A", num: 1 }] + } + ], + [ + // Testing that keys-only queries don't get bothered + function () { return db.items.update(-1, { foo: "bar" }); }, + { + itemsToArray: [{ id: -1, name: "A", foo: "bar" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "A", foo: "bar" }], + itemsStartsWithA: [{ id: -1, name: "A", foo: "bar" }], + //itemsStartsWithAPrimKeys: [-1], should not have to be updated! + //itemsStartsWithAKeys: ["A"] should not have to be updated! + } + ], + [ + // Update an index property (name) should trigger + // listeners to that index: + function () { return db.items.update(-1, { foo: undefined, name: "B" }); }, + { + itemsToArray: [{ id: -1, name: "B" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "B" }], + itemsStartsWithA: [], + itemsStartsWithAPrimKeys: [], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: [], + itemsStartsWithACount: fruitCount + } + ], + [ + // Restoring and re-checking. + function () { return db.items.update(-1, { name: "A" }); }, + { + itemsToArray: [{ id: -1, name: "A" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "A" }], + itemsStartsWithA: [{ id: -1, name: "A" }], + itemsStartsWithAPrimKeys: [-1], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: ["A"], + itemsStartsWithACount: fruitCount + 1 + } + ], + // add again + [ + function () { return db.items.bulkAdd([{ id: 4, name: "Abbot" }, { id: 5, name: "Assot" }, { id: 6, name: "Ambros" }]).then(function (lastId) { }); }, + { + itemsToArray: [{ id: -1, name: "A" }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5, name: "Assot" }, { id: 6, name: "Ambros" }], + itemsStartsWithA: [{ id: -1, name: "A" }, { id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }, { id: 5, name: "Assot" }], + itemsStartsWithAPrimKeys: [-1, 4, 6, 5], + itemsStartsWithAOffset3: [{ id: 5, name: "Assot" }], + itemsStartsWithAKeys: ["A", "Abbot", "Ambros", "Assot"], + itemsStartsWithACount: fruitCount + 4 + } + ], + // delete: + [ + function () { return db.transaction('rw', db.items, db.outbound, function () { + db.items.delete(-1); + }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5, name: "Assot" }, { id: 6, name: "Ambros" }], + itemsGet1And2: [{ id: 1 }, null], + itemsStartsWithA: [{ id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }, { id: 5, name: "Assot" }], + itemsStartsWithAPrimKeys: [4, 6, 5], + itemsStartsWithAKeys: ["Abbot", "Ambros", "Assot"], + itemsStartsWithACount: fruitCount + 3 + }, + // Allowed extras: + // If hooks is listened to we'll get an even more correct update of the itemsStartsWithAOffset3 query + // since oldVal will be available and offset-queries will be correcly triggered for deleted index keys before the offset. + { + itemsStartsWithAOffset3: [] + } + ], + // Special case for more fine grained keys observation of put (not knowing oldObjs + [ + function () { return db.items.put({ id: 5, name: "Azlan" }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5, name: "Azlan" }, { id: 6, name: "Ambros" }], + itemsStartsWithA: [{ id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }, { id: 5, name: "Azlan" }], + itemsStartsWithAKeys: ["Abbot", "Ambros", "Azlan"], + }, { + // Things that optionally can be matched in result (if no hooks specified): + itemsStartsWithAPrimKeys: [4, 6, 5], + itemsStartsWithACount: fruitCount + 3, + itemsStartsWithAOffset3: [] + } + ], + [ + function () { return db.transaction('rw', db.items, db.outbound, function () { + db.items.bulkPut([{ id: 5 }]); + }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5 }, { id: 6, name: "Ambros" }], + itemsStartsWithA: [{ id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }], + itemsStartsWithAPrimKeys: [4, 6], + itemsStartsWithAKeys: ["Abbot", "Ambros"], + itemsStartsWithACount: fruitCount + 2 + }, { + itemsStartsWithAOffset3: [] // This is + } + ], + [ + function () { return db.transaction('rw', db.items, db.outbound, function () { + db.items.delete(5); + db.outbound.bulkDelete([abbaKey, -1, 0]); + }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }], + // (allOutbound was: + // [{name:"Benny"},{name: "C"},{num:1,name:"A"},{num:2,name:"B"},{num:3,name:"C"},{name:"Zlatan"}]) + // ) + outboundToArray: [{ num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }], + //outboundStartsWithA: [{num:1,name:"A"}], + outboundIdBtwnMinus1And2: [{ num: 1, name: "A" }, { num: 2, name: "B" }], + outboundAnyOf_BCD_keys: ["B", "C"] + }, [ + "itemsStartsWithACount" + ] + ], + [ + function () { return db.friends.add({ name: "Foo", age: 20 }).then(function (id) { return lastFriendId = id; }); }, + { + friendsOver18: [{ get id() { return lastFriendId; }, name: "Foo", age: 20 }] + } + ], + [ + function () { return db.friends.put({ name: "Barbar", age: 21 }).then(function (id) { return barbarFriendId = id; }); }, + { + friendsOver18: [ + { get id() { return lastFriendId; }, name: "Foo", age: 20 }, + { get id() { return barbarFriendId; }, name: "Barbar", age: 21 } + ] + } + ], + [ + // bulkPut + function () { return db.friends.bulkPut(bulkFriends, { allKeys: true }).then(function (ids) { + // Record the actual ids here + for (var i = 0; i < ids.length; ++i) { + bulkFriends[i].id = ids[i]; + } + }); }, + { + friendsOver18: __spreadArray([ + { get id() { return lastFriendId; }, name: "Foo", age: 20 }, + { get id() { return barbarFriendId; }, name: "Barbar", age: 21 } + ], __read(bulkFriends.map(function (f) { return ({ name: f.name, age: f.age, get id() { return f.id; } }); }).filter(function (f) { return f.age > 18; })), false).sort(function (a, b) { return a.age - b.age; }) + } + ], + // bulkPut over 50 items on an outbound table: + [ + function () { return db.outbound.bulkPut(bulkOutbounds); }, + { + outboundToArray: __spreadArray([{ num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }], __read(bulkOutbounds), false), + outbound_above_z49: __spreadArray([], __read(bulkOutbounds.filter(function (o) { return o.name > "z49"; })), false) + }, ["outboundStartsWithA", "outboundIdBtwnMinus1And2", "outboundAnyOf_BCD_keys"] + ], + // deleteRange + [ + function () { return db.friends.where('id').between(0, barbarFriendId, true, true).delete(); }, + { + friendsOver18: __spreadArray([], __read(bulkFriends.filter(function (f) { return f.age > 18; })), false) + } + ], + // bulkDelete + [ + // Delete all but one: + function () { return db.friends.bulkDelete(bulkFriends.filter(function (f) { return f.age !== 20; }).map(function (f) { return f.id; })); }, + { + friendsOver18: __spreadArray([], __read(bulkFriends.filter(function (f) { return f.age === 20; })), false) + } + ], + // multiEntry + [ + function () { return db.multiEntry.add({ id: 1, tags: ["fooTag", "Apa"] }); }, + { + multiEntry1: [1], + multiEntry2: [1] + } + ], + [ + function () { return db.multiEntry.bulkPut([ + { id: 1, tags: [] }, + { id: 2, tags: ["Apa", "x", "y"] }, + { id: 3, tags: ["barTag", "fooTag"] } + ]); }, + { + multiEntry1: [2], + multiEntry2: [3] + } + ] + ]; }; + promisedTest("Full use case matrix", function () { return __awaiter(void 0, void 0, void 0, function () { + var queries, expectedInitialResults, flyingNow, signal, actualResults, observables, subscriptions, prevActual_1, _loop_1, _a, _b, _c, mut, expects, allowedExtra, e_1_1; + var e_1, _d; + return __generator(this, function (_e) { + switch (_e.label) { + case 0: return [4 /*yield*/, db.items.where('name').startsWith('A').count()]; + case 1: + // A bug in Safari <= 13.1 makes it unable to count on the name index (adds 1 extra) + fruitCount = _e.sent(); + if (fruitCount > 0) + console.log("fruitCount: " + fruitCount); + if (isIE) { + // The IE implementation becomes shaky here. + // Maybe becuase we launch several parallel queries to IDB. + QUnit.ok(true, "Skipping this test for IE - too shaky for the CI"); + return [2 /*return*/]; + } + queries = { + itemsToArray: function () { return db.items.toArray(); }, + itemsGet1And2: function () { return Promise.all(db.items.get(1), db.items.get(-1)); }, + itemsBulkGet123: function () { return db.items.bulkGet([1, 2, 3]); }, + itemsStartsWithA: function () { return db.items.where('name').startsWith("A").toArray(); }, + itemsStartsWithAPrimKeys: function () { return db.items.where('name').startsWith("A").primaryKeys(); }, + itemsStartsWithAOffset3: function () { return db.items.where('name').startsWith("A").offset(3).toArray(); }, + itemsStartsWithAKeys: function () { return db.items.where('name').startsWith("A").keys(); }, + itemsStartsWithACount: function () { return db.items.where('name').startsWith("A").count(); }, + outboundToArray: function () { return db.outbound.toArray(); }, + outboundStartsWithA: function () { return db.outbound.where('name').startsWith("A").toArray(); }, + outboundIdBtwnMinus1And2: function () { return db.outbound.where(':id').between(-1, 2, true, true).toArray(); }, + outboundAnyOf_BCD_keys: function () { return db.outbound.where('name').anyOf("B", "C", "D").keys(); }, + outbound_above_z49: function () { return db.outbound.where('name').above("z49").toArray(); }, + friendsOver18: function () { return db.friends.where('age').above(18).toArray(); }, + multiEntry1: function () { return db.multiEntry.where('tags').startsWith('A').primaryKeys(); }, + multiEntry2: function () { return db.multiEntry.where({ tags: "fooTag" }).primaryKeys(); } + }; + expectedInitialResults = { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, undefined], + itemsBulkGet123: [{ id: 1 }, { id: 2 }, { id: 3 }], + itemsStartsWithA: [], + itemsStartsWithAPrimKeys: [], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: [], + itemsStartsWithACount: fruitCount, + outboundToArray: [ + { num: 1, name: "A" }, + { num: 2, name: "B" }, + { num: 3, name: "C" } + ], + outboundStartsWithA: [{ num: 1, name: "A" }], + outboundIdBtwnMinus1And2: [{ num: 1, name: "A" }, { num: 2, name: "B" }], + outboundAnyOf_BCD_keys: ["B", "C"], + outbound_above_z49: [], + friendsOver18: [], + multiEntry1: [], + multiEntry2: [] + }; + flyingNow = 0; + signal = new Signal(); + actualResults = objectify(new Map(Object.keys(queries).map(function (name) { return [name, undefined]; }))); + observables = new Map(Object.keys(queries).map(function (name) { return [ + name, + Dexie.liveQuery(function () { return __awaiter(void 0, void 0, void 0, function () { + var res; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + ++flyingNow; + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, queries[name]()]; + case 2: + res = _a.sent(); + actualResults[name] = res; + return [2 /*return*/, res]; + case 3: + if (--flyingNow === 0) + signal.resolve(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }) + ]; })); + subscriptions = Object.keys(queries).map(function (name) { return observables.get(name).subscribe({ + next: function (res) { }, + error: function (error) { return QUnit.ok(false, '' + error); } + }); }); + _e.label = 2; + case 2: + _e.trys.push([2, , 12, 13]); + return [4 /*yield*/, signal.promise]; + case 3: + _e.sent(); + deepEqual(actualResults, expectedInitialResults, "Initial results as expected"); + prevActual_1 = Dexie__default["default"].deepClone(actualResults); + _loop_1 = function (mut, expects, allowedExtra) { + var expected; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: + actualResults = {}; + signal = new Signal(); + mut(); + return [4 /*yield*/, signal.promise]; + case 1: + _f.sent(); + expected = Dexie__default["default"].deepClone(expects); + if (allowedExtra) + Array.isArray(allowedExtra) ? allowedExtra.forEach(function (key) { + if (actualResults[key]) + expected[key] = prevActual_1[key]; + }) : Object.keys(allowedExtra).forEach(function (key) { + if (actualResults[key]) + expected[key] = allowedExtra[key]; + }); + deepEqual(actualResults, expected, "" + mut.toString()); + Object.assign(prevActual_1, actualResults); + return [2 /*return*/]; + } + }); + }; + _e.label = 4; + case 4: + _e.trys.push([4, 9, 10, 11]); + _a = __values(mutsAndExpects()), _b = _a.next(); + _e.label = 5; + case 5: + if (!!_b.done) return [3 /*break*/, 8]; + _c = __read(_b.value, 3), mut = _c[0], expects = _c[1], allowedExtra = _c[2]; + return [5 /*yield**/, _loop_1(mut, expects, allowedExtra)]; + case 6: + _e.sent(); + _e.label = 7; + case 7: + _b = _a.next(); + return [3 /*break*/, 5]; + case 8: return [3 /*break*/, 11]; + case 9: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 11]; + case 10: + try { + if (_b && !_b.done && (_d = _a.return)) _d.call(_a); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 11: return [3 /*break*/, 13]; + case 12: + subscriptions.forEach(function (s) { return s.unsubscribe(); }); + return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); }); + promisedTest("RxJS compability", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal, o, s, result, res2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + signal = new Signal(); + o = from(Dexie.liveQuery(function () { return db.items.toArray(); })).pipe(map(function (items) { return items.map(function (item) { return item.id; }); })); + s = o.subscribe(function (results) { return signal.resolve(results); }); + return [4 /*yield*/, signal.promise]; + case 1: + result = _a.sent(); + deepEqual(result, [1, 2, 3], "We should have get a mapped result"); + signal = new Signal(); + db.items.add({ id: 4 }); + return [4 /*yield*/, signal.promise]; + case 2: + res2 = _a.sent(); + deepEqual(res2, [1, 2, 3, 4], "We should have get an updated mapped result"); + s.unsubscribe(); + return [2 /*return*/]; + } + }); + }); }); + + // Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys + // ... with the adjustment to return NaN instead of throwing. + function cmp(a, b) { + try { + var ta = type(a); + var tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; // Return value if any given args are valid keys. + } + function compareArrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + var res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function compareUint8Arrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + // Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type + function type(x) { + var t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + var tsTag = toStringTag(x); // Cannot use instanceof in Safari + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; + } + function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + // TypedArray or DataView + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); // ArrayBuffer + } + + var _a; + /* An interval tree implementation to efficiently detect overlapping ranges of queried indexes. + * + * https://en.wikipedia.org/wiki/Interval_tree + * + */ + function isEmptyRange(node) { + return !("from" in node); + } + var RangeSet = function (fromOrTree, to) { + if (this) { + // Called with new() + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + // Called without new() + var rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } + }; + props(RangeSet.prototype, (_a = { + add: function (rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey: function (key) { + addRange(this, key, key); + return this; + }, + addKeys: function (keys) { + var _this = this; + keys.forEach(function (key) { return addRange(_this, key, key); }); + return this; + } + }, + _a[iteratorSymbol] = function () { + return getRangeSetIterator(this); + }, + _a)); + function addRange(target, from, to) { + var diff = cmp(from, to); + // cmp() returns NaN if one of the args are IDB-invalid keys. + // Avoid storing invalid keys in rangeset: + if (isNaN(diff)) + return; + // Caller is trying to add a range where from is greater than to: + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from: from, to: to, d: 1 }); + var left = target.l; + var right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed. + // Grow left? + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; // Cut off for now. Re-add later. + target.d = right ? right.d + 1 : 1; + } + // Grow right? + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; // Cut off for now. Re-add later. + target.d = target.l ? target.l.d + 1 : 1; + } + var rightWasCutOff = !target.r; + // Re-add left? + if (left && !target.l) { + //Ranges to the left may be swallowed. Cut it of and re-add all. + //Could probably be done more efficiently! + mergeRanges(target, left); + } + // Re-add right? + if (right && rightWasCutOff) { + //Ranges to the right may be swallowed. Cut it of and re-add all. + //Could probably be done more efficiently! + mergeRanges(target, right); + } + } + function mergeRanges(target, newSet) { + function _addRangeSet(target, _a) { + var from = _a.from, to = _a.to, l = _a.l, r = _a.r; + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); + } + function rangesOverlap(rangeSet1, rangeSet2) { + // Start iterating other from scratch. + var i1 = getRangeSetIterator(rangeSet2); + var nextResult1 = i1.next(); + if (nextResult1.done) + return false; + var a = nextResult1.value; + // Start iterating this from start of other + var i2 = getRangeSetIterator(rangeSet1); + var nextResult2 = i2.next(a.from); // Start from beginning of other range + var b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) // a is behind. forward it to beginning of next b-range + : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range + } + return false; + } + function getRangeSetIterator(node) { + var state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next: function (key) { + var keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + // Initial state for node. + // Fast forward to leftmost node. + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + // intentionally fall into case 1: + case 1: + // We're on a node where it's left part is already handled or does not exist. + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + // We've emitted our node and should continue with the right part or let parent take over from it's state 1 + if (state.n.r) { + state.s = 3; // So when child is done, we know we're done. + state = { up: state, n: state.n.r, s: 0 }; + continue; // Will fall in to case 0 with fast forward to left leaf of this subtree. + } + // intentionally fall into case 3: + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; + } + function rebalance(target) { + var _a, _b; + var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + // Rotate (https://en.wikipedia.org/wiki/Tree_rotation) + // + // + // [OLDROOT] + // [OLDROOT.L] [NEWROOT] + // [NEWROOT.L] [NEWROOT.R] + // + // Is going to become: + // + // + // [NEWROOT] + // [OLDROOT] [NEWROOT.R] + // [OLDROOT.L] [NEWROOT.L] + // * clone now has the props of OLDROOT + // Plan: + // * target must be given the props of NEWROOT + // * target[l] must point to a new OLDROOT + // * target[r] must point to NEWROOT.R + // * OLDROOT[r] must point to NEWROOT.L + var l = r === "r" ? "l" : "r"; // Support both left/right rotation + var rootClone = __assign({}, target); + // We're gonna copy props from target's right node into target so that target will + // have same range as old target[r] (instead of changing pointers, we copy values. + // that way we do not need to adjust pointers in parents). + var oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); + } + function computeDepth(_a) { + var r = _a.r, l = _a.l; + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; + } + + QUnit.module("rangeset"); + QUnit.test("it should do match correctly", function () { + var set = new RangeSet() + .add({ from: 1, to: 1 }) + .add({ from: 2, to: 10 }) + .add({ from: 20, to: 30 }) + .add({ from: 40, to: 40 }); + QUnit.ok(!rangesOverlap(set, new RangeSet(1.1, 1.9)), "set does not overlap with 1.1-1.9"); + QUnit.ok(rangesOverlap(set, new RangeSet(1, 1)), "set overlaps with 1-1"); + QUnit.ok(rangesOverlap(set, new RangeSet(0, 1)), "set overlaps with 0-1"); + QUnit.ok(!rangesOverlap(set, new RangeSet(0, 0.9)), "set doesnt overlap with 0-0.9"); + QUnit.ok(rangesOverlap(set, new RangeSet(39, 41)), "set overlaps with 39-40"); + }); + QUnit.test("it should balance itself", function () { + var set = new RangeSet(); + for (var i = 0; i < 10000; ++i) { + set.add({ from: i, to: i + 0.5 }); + } + QUnit.ok(!isNaN(set.d) && set.d <= 14 && set.d >= 1, "Depth should be below or equal to 14"); + set.add({ from: 0, to: 10000 }); + QUnit.equal(set.d, 1, "After adding a super range, the depth should be 1"); + QUnit.equal(__spreadArray([], __read(set), false).length, 1, "After adding the super range, the entire set should just contain the super set"); + }); + QUnit.test("it should be iterable", function () { + var set = new RangeSet(); + for (var i = 0; i < 10; ++i) { + set.addKey(i); + } + QUnit.equal(__spreadArray([], __read(set), false).length, 10, "Should iterate 10 items"); + QUnit.ok(__spreadArray([], __read(set), false).every(function (node, i) { return node.from === i && node.to === i; }), "Each node should have correct ranges"); + }); + QUnit.test("it should be mergable", function () { + var set = RangeSet().addKeys([0, 2, 4, 7, 8]); + var set2 = RangeSet().addKeys([1, 3, 5, 7, 9, 11]); + set.add(set2); + QUnit.equal(__spreadArray([], __read(set), false).map(function (_a) { + var from = _a.from; + return from; + }).join(','), [ + 0, + 1, + 2, + 3, + 4, + 5, + 7, + 8, + 9, + 11, + ].join(','), "successful merge of two sets"); + set.add(new RangeSet(1, 6)); + QUnit.equal(JSON.stringify(__spreadArray([], __read(set), false).map(function (_a) { + var from = _a.from, to = _a.to; + return [from, to]; + })), JSON.stringify([ + [0, 0], + [1, 6], + [7, 7], + [8, 8], + [9, 9], + [11, 11], + ]), "after adding a super range to some of the containing ranges, the rangeset should have replaced the subranges with their subset"); + set.add({ from: 0, to: 20 }); + QUnit.equal(JSON.stringify(__spreadArray([], __read(set), false).map(function (_a) { + var from = _a.from, to = _a.to; + return [from, to]; + })), JSON.stringify([[0, 20]]), "after adding a superset, the entire set should just equal the super set"); + }); + function isSequencial(set) { + var e_1, _a; + var lastFrom = -Infinity; + try { + for (var _b = __values(__spreadArray([], __read(set), false)), _c = _b.next(); !_c.done; _c = _b.next()) { + var node = _c.value; + if (node.from <= lastFrom) { + return false; + } + lastFrom = node.from; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + return true; + } + QUnit.test("stress", function () { + var set = new RangeSet(); + //console.log("depth", set.d); + for (var i = 1; i <= 600; ++i) { + set.addKey(i); + } + QUnit.ok(isSequencial(set), "set is sequencial"); + //console.log("the set 1", [...set]); + //console.log("depth", set.d); + QUnit.equal(__spreadArray([], __read(set), false).length, 600, "Set should contain individual ranges"); + QUnit.ok(isSequencial(set), "set is sequencial"); + //debugger; + set.add({ from: 280, to: 321 }); + //console.log("the set 2", JSON.parse(JSON.stringify([...set]))); + QUnit.ok(isSequencial(set), "set is sequencial"); + //console.log("depth", set.d); + QUnit.equal(__spreadArray([], __read(set), false).length, 559, "Set should have less ranges"); + //console.log("depth", set.d); + }); + var issue1268_triggering_input = [ + { from: 63, to: 71 }, + { from: 99, to: 102 }, + // (null) [99-102] + { from: 90, to: 92 }, + // [63-71] (null) + // [90-92] [90-92] + // WOW: Here both left and right leafs are the same node! + { from: 92, to: 95 }, + { from: 4, to: 10 }, + { from: 51, to: 51 }, + { from: 45, to: 46 }, + { from: 14, to: 20 }, + { from: 13, to: 20 }, + { from: 9, to: 12 }, + { from: 23, to: 25 }, + { from: 31, to: 35 }, + { from: 80, to: 88 }, + { from: 87, to: 91 }, + { from: 36, to: 37 }, + { from: 77, to: 79 } + ]; + QUnit.test("issue1268", function () { + var set = new RangeSet(); + issue1268_triggering_input.forEach(function (range, idx) { + try { + //if (idx === 11) debugger; + //console.log(`Adding [${range.from}-${range.to}]`); + set.add(range); + if (!verifySet(set)) { + QUnit.ok(false, "set not ok at idx " + idx + " depth: " + set.d); + } + else { + //console.log("Printing tree on idx " + idx); + //if (idx === 2) debugger; + //printTree([set]); + } + } + catch (e) { + console.log("crashed on idx", idx); + QUnit.ok(false, "died on idx " + idx + " with " + e); + } + }); + QUnit.ok(true, "Done"); + }); + function verifySet(set) { + var e_2, _a; + var i = issue1268_triggering_input.length + 2; + try { + for (var set_1 = __values(set), set_1_1 = set_1.next(); !set_1_1.done; set_1_1 = set_1.next()) { + var node = set_1_1.value; + if (--i === 0) + return false; + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (set_1_1 && !set_1_1.done && (_a = set_1.return)) _a.call(set_1); + } + finally { if (e_2) throw e_2.error; } + } + return true; + } + + Dexie__default["default"].test = true; // Improve code coverage + //import "./tests-performance.js"; Not required. Should make other performance tests separately instead. + +})); +//# sourceMappingURL=bundle.js.map