From 843b47bd6607b415143b940d28409dbbda33db85 Mon Sep 17 00:00:00 2001 From: pubkey <8926560+pubkey@users.noreply.github.com> Date: Wed, 23 Jun 2021 01:21:43 +0200 Subject: [PATCH] BUILD --- dist/es/browserify.index.js | 5 +- dist/es/change-event-buffer.js | 12 +- dist/es/core.js | 13 +- dist/es/crypter.js | 35 +- dist/es/event-reduce.js | 47 +- dist/es/hooks.js | 41 +- dist/es/index.js | 9 +- dist/es/overwritable.js | 24 +- dist/es/plugin.js | 29 +- dist/es/plugins/attachments.js | 342 +- dist/es/plugins/backup/index.js | 39 +- dist/es/plugins/dev-mode/check-names.js | 35 + dist/es/plugins/dev-mode/check-schema.js | 28 +- dist/es/plugins/dev-mode/error-messages.js | 45 +- dist/es/plugins/dev-mode/index.js | 20 + .../plugins/dev-mode/unallowed-properties.js | 9 +- dist/es/plugins/encryption.js | 120 +- dist/es/plugins/in-memory.js | 215 +- dist/es/plugins/json-dump.js | 32 +- dist/es/plugins/key-compression.js | 162 +- dist/es/plugins/local-documents.js | 229 +- dist/es/plugins/migration/data-migrator.js | 178 +- .../es/plugins/{ => pouchdb}/adapter-check.js | 17 +- .../plugins/pouchdb/custom-events-plugin.js | 238 + dist/es/plugins/pouchdb/index.js | 5 + dist/es/plugins/pouchdb/pouch-db.js | 81 + dist/es/plugins/pouchdb/rx-storage-pouchdb.js | 1797 +++ ...{replication.js => replication-couchdb.js} | 110 +- .../crawling-checkpoint.js | 327 +- dist/es/plugins/replication-graphql/helper.js | 110 +- dist/es/plugins/replication-graphql/index.js | 345 +- .../query-builder-from-rx-schema.js | 8 +- dist/es/plugins/server.js | 301 +- dist/es/plugins/update.js | 4 +- dist/es/plugins/watch-for-changes.js | 103 - dist/es/pouch-db.js | 172 - dist/es/rx-change-event.js | 138 +- dist/es/rx-collection-helper.js | 172 +- dist/es/rx-collection.js | 854 +- dist/es/rx-database-internal-store.js | 52 - dist/es/rx-database.js | 772 +- dist/es/rx-document-prototype-merge.js | 12 +- dist/es/rx-document.js | 176 +- dist/es/rx-query.js | 102 +- dist/es/rx-schema-helper.js | 33 + dist/es/rx-schema.js | 95 +- dist/es/rx-storage-helper.js | 365 + dist/es/rx-storage-pouchdb.js | 268 - dist/es/rx-storate.interface.js | 2 - dist/es/types/index.d.js | 6 +- dist/es/types/plugins/backup.d.js | 3 +- dist/es/types/plugins/migration.d.js | 3 +- .../es/types/plugins/replication-graphql.d.js | 3 +- dist/es/types/plugins/replication.d.js | 3 +- dist/es/types/plugins/server.d.js | 3 +- dist/es/types/pouch.d.js | 3 +- dist/es/types/rx-attachment.d.js | 3 +- dist/es/types/rx-change-event.d.js | 3 + dist/es/types/rx-collection.d.js | 3 +- dist/es/types/rx-database.d.js | 3 +- dist/es/types/rx-document.d.js | 3 +- dist/es/types/rx-error.d.js | 3 +- dist/es/types/rx-plugin.d.js | 3 +- dist/es/types/rx-schema.d.js | 3 +- dist/es/types/rx-storage.d.js | 3 + dist/es/types/rx-storage.interface.d.js | 3 + dist/es/types/util.d.js | 3 +- dist/es/util.js | 41 +- dist/lib/browserify.index.js | 6 +- dist/lib/change-event-buffer.js | 13 +- dist/lib/core.js | 147 +- dist/lib/crypter.js | 34 +- dist/lib/event-reduce.js | 49 +- dist/lib/hooks.js | 41 +- dist/lib/index.js | 23 +- dist/lib/overwritable.js | 24 +- dist/lib/plugin.js | 32 +- dist/lib/plugins/attachments.js | 343 +- dist/lib/plugins/backup/index.js | 39 +- dist/lib/plugins/dev-mode/check-names.js | 45 + dist/lib/plugins/dev-mode/check-schema.js | 28 +- dist/lib/plugins/dev-mode/error-messages.js | 45 +- dist/lib/plugins/dev-mode/index.js | 35 + .../plugins/dev-mode/unallowed-properties.js | 11 +- dist/lib/plugins/encryption.js | 121 +- dist/lib/plugins/in-memory.js | 220 +- dist/lib/plugins/json-dump.js | 32 +- dist/lib/plugins/key-compression.js | 168 +- dist/lib/plugins/local-documents.js | 233 +- dist/lib/plugins/migration/data-migrator.js | 186 +- .../plugins/{ => pouchdb}/adapter-check.js | 24 +- .../plugins/pouchdb/custom-events-plugin.js | 260 + dist/lib/plugins/pouchdb/index.js | 59 + dist/lib/plugins/pouchdb/pouch-db.js | 104 + .../lib/plugins/pouchdb/rx-storage-pouchdb.js | 1858 +++ ...{replication.js => replication-couchdb.js} | 124 +- .../crawling-checkpoint.js | 325 +- .../lib/plugins/replication-graphql/helper.js | 121 +- dist/lib/plugins/replication-graphql/index.js | 343 +- .../query-builder-from-rx-schema.js | 8 +- dist/lib/plugins/server.js | 304 +- dist/lib/plugins/update.js | 4 +- dist/lib/plugins/watch-for-changes.js | 119 - dist/lib/pouch-db.js | 204 - dist/lib/rx-change-event.js | 153 +- dist/lib/rx-collection-helper.js | 182 +- dist/lib/rx-collection.js | 859 +- dist/lib/rx-database-internal-store.js | 72 - dist/lib/rx-database.js | 771 +- dist/lib/rx-document-prototype-merge.js | 12 +- dist/lib/rx-document.js | 182 +- dist/lib/rx-query.js | 102 +- dist/lib/rx-schema-helper.js | 48 + dist/lib/rx-schema.js | 103 +- dist/lib/rx-storage-helper.js | 394 + dist/lib/rx-storage-pouchdb.js | 289 - dist/lib/rx-storate.interface.js | 3 - dist/lib/types/index.d.js | 52 + dist/lib/types/rx-change-event.d.js | 3 + dist/lib/types/rx-storage.d.js | 3 + dist/lib/types/rx-storage.interface.d.js | 3 + dist/lib/util.js | 53 +- dist/rxdb.browserify.js | 10259 ++++++++++------ dist/rxdb.browserify.min.js | 8 +- dist/types/change-event-buffer.d.ts | 14 +- dist/types/core.d.ts | 16 +- dist/types/crypter.d.ts | 11 +- dist/types/event-reduce.d.ts | 5 +- dist/types/index.d.ts | 1 + dist/types/overwritable.d.ts | 16 +- dist/types/plugin.d.ts | 6 +- dist/types/plugins/attachments.d.ts | 23 +- .../dev-mode/check-migration-strategies.d.ts | 2 +- dist/types/plugins/dev-mode/check-names.d.ts | 9 + dist/types/plugins/dev-mode/check-schema.d.ts | 2 +- .../plugins/dev-mode/error-messages.d.ts | 130 +- dist/types/plugins/dev-mode/index.d.ts | 9 + .../dev-mode/unallowed-properties.d.ts | 6 +- dist/types/plugins/encryption.d.ts | 11 +- dist/types/plugins/in-memory.d.ts | 17 +- dist/types/plugins/key-compression.d.ts | 39 +- dist/types/plugins/local-documents.d.ts | 15 +- .../plugins/migration/data-migrator.d.ts | 12 +- .../plugins/migration/migration-state.d.ts | 2 +- .../plugins/{ => pouchdb}/adapter-check.d.ts | 7 - .../plugins/pouchdb/custom-events-plugin.d.ts | 25 + dist/types/plugins/pouchdb/index.d.ts | 4 + dist/types/plugins/pouchdb/pouch-db.d.ts | 19 + .../plugins/pouchdb/rx-storage-pouchdb.d.ts | 128 + ...lication.d.ts => replication-couchdb.d.ts} | 12 +- .../crawling-checkpoint.d.ts | 27 +- .../graphql-schema-from-rx-schema.d.ts | 2 +- .../plugins/replication-graphql/helper.d.ts | 24 +- .../plugins/replication-graphql/index.d.ts | 29 +- dist/types/plugins/server.d.ts | 2 +- dist/types/plugins/watch-for-changes.d.ts | 11 - dist/types/pouch-db.d.ts | 35 - dist/types/rx-change-event.d.ts | 65 +- dist/types/rx-collection-helper.d.ts | 23 +- dist/types/rx-collection.d.ts | 81 +- dist/types/rx-database-internal-store.d.ts | 30 - dist/types/rx-database.d.ts | 84 +- dist/types/rx-document.d.ts | 76 +- dist/types/rx-error.d.ts | 14 +- dist/types/rx-query.d.ts | 16 +- dist/types/rx-schema-helper.d.ts | 10 + dist/types/rx-schema.d.ts | 24 +- dist/types/rx-storage-helper.d.ts | 32 + dist/types/rx-storage-pouchdb.d.ts | 33 - dist/types/rx-storate.interface.d.ts | 51 - dist/types/types/index.d.ts | 4 + dist/types/types/plugins/migration.d.ts | 9 +- .../types/plugins/replication-graphql.d.ts | 15 +- dist/types/types/plugins/replication.d.ts | 4 +- dist/types/types/plugins/server.d.ts | 24 +- dist/types/types/pouch.d.ts | 71 +- dist/types/types/rx-attachment.d.ts | 5 +- dist/types/types/rx-change-event.d.ts | 43 + dist/types/types/rx-collection.d.ts | 23 +- dist/types/types/rx-database.d.ts | 44 +- dist/types/types/rx-document.d.ts | 32 +- dist/types/types/rx-error.d.ts | 12 +- dist/types/types/rx-plugin.d.ts | 13 +- dist/types/types/rx-schema.d.ts | 31 +- dist/types/types/rx-storage.d.ts | 313 + dist/types/types/rx-storage.interface.d.ts | 316 + dist/types/types/util.d.ts | 17 + dist/types/util.d.ts | 11 +- 188 files changed, 19465 insertions(+), 10441 deletions(-) create mode 100644 dist/es/plugins/dev-mode/check-names.js rename dist/es/plugins/{ => pouchdb}/adapter-check.js (81%) create mode 100644 dist/es/plugins/pouchdb/custom-events-plugin.js create mode 100644 dist/es/plugins/pouchdb/index.js create mode 100644 dist/es/plugins/pouchdb/pouch-db.js create mode 100644 dist/es/plugins/pouchdb/rx-storage-pouchdb.js rename dist/es/plugins/{replication.js => replication-couchdb.js} (73%) delete mode 100644 dist/es/plugins/watch-for-changes.js delete mode 100644 dist/es/pouch-db.js delete mode 100644 dist/es/rx-database-internal-store.js create mode 100644 dist/es/rx-schema-helper.js create mode 100644 dist/es/rx-storage-helper.js delete mode 100644 dist/es/rx-storage-pouchdb.js delete mode 100644 dist/es/rx-storate.interface.js create mode 100644 dist/es/types/rx-change-event.d.js create mode 100644 dist/es/types/rx-storage.d.js create mode 100644 dist/es/types/rx-storage.interface.d.js create mode 100644 dist/lib/plugins/dev-mode/check-names.js rename dist/lib/plugins/{ => pouchdb}/adapter-check.js (75%) create mode 100644 dist/lib/plugins/pouchdb/custom-events-plugin.js create mode 100644 dist/lib/plugins/pouchdb/index.js create mode 100644 dist/lib/plugins/pouchdb/pouch-db.js create mode 100644 dist/lib/plugins/pouchdb/rx-storage-pouchdb.js rename dist/lib/plugins/{replication.js => replication-couchdb.js} (70%) delete mode 100644 dist/lib/plugins/watch-for-changes.js delete mode 100644 dist/lib/pouch-db.js delete mode 100644 dist/lib/rx-database-internal-store.js create mode 100644 dist/lib/rx-schema-helper.js create mode 100644 dist/lib/rx-storage-helper.js delete mode 100644 dist/lib/rx-storage-pouchdb.js delete mode 100644 dist/lib/rx-storate.interface.js create mode 100644 dist/lib/types/rx-change-event.d.js create mode 100644 dist/lib/types/rx-storage.d.js create mode 100644 dist/lib/types/rx-storage.interface.d.js create mode 100644 dist/types/plugins/dev-mode/check-names.d.ts rename dist/types/plugins/{ => pouchdb}/adapter-check.d.ts (52%) create mode 100644 dist/types/plugins/pouchdb/custom-events-plugin.d.ts create mode 100644 dist/types/plugins/pouchdb/index.d.ts create mode 100644 dist/types/plugins/pouchdb/pouch-db.d.ts create mode 100644 dist/types/plugins/pouchdb/rx-storage-pouchdb.d.ts rename dist/types/plugins/{replication.d.ts => replication-couchdb.d.ts} (70%) delete mode 100644 dist/types/plugins/watch-for-changes.d.ts delete mode 100644 dist/types/pouch-db.d.ts delete mode 100644 dist/types/rx-database-internal-store.d.ts create mode 100644 dist/types/rx-schema-helper.d.ts create mode 100644 dist/types/rx-storage-helper.d.ts delete mode 100644 dist/types/rx-storage-pouchdb.d.ts delete mode 100644 dist/types/rx-storate.interface.d.ts create mode 100644 dist/types/types/rx-change-event.d.ts create mode 100644 dist/types/types/rx-storage.d.ts create mode 100644 dist/types/types/rx-storage.interface.d.ts diff --git a/dist/es/browserify.index.js b/dist/es/browserify.index.js index 668cfc13c85..63c619bd63e 100644 --- a/dist/es/browserify.index.js +++ b/dist/es/browserify.index.js @@ -5,7 +5,8 @@ */ import '@babel/polyfill'; import * as RxDB from './index.js'; -RxDB.addRxPlugin(require('pouchdb-adapter-idb')); -RxDB.addRxPlugin(require('pouchdb-adapter-http')); +import * as RxDbPouchPlugin from './plugins/pouchdb/index.js'; +RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb')); +RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http')); window['RxDB'] = RxDB; //# sourceMappingURL=browserify.index.js.map \ No newline at end of file diff --git a/dist/es/change-event-buffer.js b/dist/es/change-event-buffer.js index f7bde7c35a2..7c01e6636e9 100644 --- a/dist/es/change-event-buffer.js +++ b/dist/es/change-event-buffer.js @@ -1,6 +1,7 @@ /** * a buffer-cache which holds the last X changeEvents of the collection */ +import { filter } from 'rxjs/operators'; export var ChangeEventBuffer = /*#__PURE__*/function () { /** * array with changeEvents @@ -15,7 +16,9 @@ export var ChangeEventBuffer = /*#__PURE__*/function () { this.eventCounterMap = new WeakMap(); this.buffer = []; this.collection = collection; - this.subs.push(this.collection.$.subscribe(function (cE) { + this.subs.push(this.collection.$.pipe(filter(function (cE) { + return !cE.isLocal; + })).subscribe(function (cE) { return _this._handleChangeEvent(cE); })); } @@ -23,7 +26,6 @@ export var ChangeEventBuffer = /*#__PURE__*/function () { var _proto = ChangeEventBuffer.prototype; _proto._handleChangeEvent = function _handleChangeEvent(changeEvent) { - // console.log('changeEventBuffer()._handleChangeEvent()'); this.counter++; this.buffer.push(changeEvent); this.eventCounterMap.set(changeEvent, this.counter); @@ -102,6 +104,7 @@ export var ChangeEventBuffer = /*#__PURE__*/function () { /** * use this to check if a change has already been handled * @returns true if change with revision exists + * TODO only used in the in-memory plugin, we should move it there. * */ ; @@ -113,7 +116,10 @@ export var ChangeEventBuffer = /*#__PURE__*/function () { while (t > 0) { t--; var cE = this.buffer[t]; - if (cE.documentData && cE.documentData._rev === revision) return true; + + if (cE.documentData && cE.documentData._rev === revision) { + return true; + } } return false; diff --git a/dist/es/core.js b/dist/es/core.js index 34f79a2c4c4..59986bd01eb 100644 --- a/dist/es/core.js +++ b/dist/es/core.js @@ -6,20 +6,19 @@ import './types/modules/crypto-js.d'; import './types/modules/graphql-client.d'; import './types/modules/mocha.parallel.d'; import './types/modules/modifiyjs.d'; -import './types/modules/pouchdb-selector-core.d'; import './types/modules/random-token.d'; export { addRxPlugin } from './plugin'; -export { PouchDB, validateCouchDBString, getBatch, countAllUndeleted, getNewestSequence } from './pouch-db'; -export { createRxDatabase, removeRxDatabase, checkAdapter, isInstanceOf as isRxDatabase, dbCount, _collectionNamePrimary // used in tests +export { createRxDatabase, removeRxDatabase, isRxDatabase, dbCount, _collectionNamePrimary // used in tests } from './rx-database'; -export { isInstanceOf as isRxCollection, create as _createRxCollection // used in tests +export { isRxCollection, RxCollectionBase, createRxCollection // used in tests } from './rx-collection'; -export { isInstanceOf as isRxDocument } from './rx-document'; +export { _handleFromStorageInstance, _handleToStorageInstance, fillObjectDataBeforeInsert } from './rx-collection-helper'; +export { isRxDocument } from './rx-document'; export { getDocumentOrmPrototype, getDocumentPrototype } from './rx-document-prototype-merge'; export { isInstanceOf as isRxQuery } from './rx-query'; export { isInstanceOf as isRxSchema, createRxSchema, RxSchema, getIndexes, normalize, getFinalFields, getPreviousVersions } from './rx-schema'; -export { RxChangeEvent } from './rx-change-event'; -export { getRxStoragePouchDb, getPouchLocation } from './rx-storage-pouchdb'; +export { getPseudoSchemaForVersion, getSchemaByObjectPath } from './rx-schema-helper'; +export { findLocalDocument, getSingleDocument, getNewestSequence, getAllDocuments, writeSingleLocal, writeSingle, countAllUndeleted, getBatch } from './rx-storage-helper'; export { _clearHook // used in tests } from './hooks'; export { createCrypter // used in tests diff --git a/dist/es/crypter.js b/dist/es/crypter.js index f96f36927f0..acdf4cc2f54 100644 --- a/dist/es/crypter.js +++ b/dist/es/crypter.js @@ -1,5 +1,8 @@ /** * handle the en/decryption of documents-data + * TODO atm we have the crypter inside of rxdb core. + * Instead all should be moved to the encryption plugin + * and work via plugin hooks. */ import objectPath from 'object-path'; import { clone, pluginMissing } from './util'; @@ -9,36 +12,44 @@ export var Crypter = /*#__PURE__*/function () { this.schema = schema; } /** - * encrypt and stringify data + * encrypt a given string. * @overwritten by plugin (optional) */ var _proto = Crypter.prototype; - _proto._encryptValue = function _encryptValue(_value) { + _proto._encryptString = function _encryptString(_value) { throw pluginMissing('encryption'); } /** - * decrypt and json-parse an encrypted value + * decrypt a given string. * @overwritten by plugin (optional) */ ; - _proto._decryptValue = function _decryptValue(_value) { + _proto._decryptString = function _decryptString(_value) { throw pluginMissing('encryption'); }; _proto.encrypt = function encrypt(obj) { var _this = this; - if (!this.password) return obj; + if (!this.password) { + return obj; + } + obj = clone(obj); this.schema.encryptedPaths.forEach(function (path) { var value = objectPath.get(obj, path); - if (typeof value === 'undefined') return; - var encrypted = _this._encryptValue(value); + if (typeof value === 'undefined') { + return; + } + + var stringValue = JSON.stringify(value); + + var encrypted = _this._encryptString(stringValue); objectPath.set(obj, path, encrypted); }); @@ -52,11 +63,15 @@ export var Crypter = /*#__PURE__*/function () { obj = clone(obj); this.schema.encryptedPaths.forEach(function (path) { var value = objectPath.get(obj, path); - if (typeof value === 'undefined') return; - var decrypted = _this2._decryptValue(value); + if (typeof value === 'undefined') { + return; + } + + var decrypted = _this2._decryptString(value); - objectPath.set(obj, path, decrypted); + var decryptedParsed = JSON.parse(decrypted); + objectPath.set(obj, path, decryptedParsed); }); return obj; }; diff --git a/dist/es/event-reduce.js b/dist/es/event-reduce.js index e6052fbbcb2..92f6a934a9c 100644 --- a/dist/es/event-reduce.js +++ b/dist/es/event-reduce.js @@ -1,4 +1,6 @@ import { calculateActionName, runAction } from 'event-reduce-js'; +import { runPluginHooks } from './hooks'; +import { rxChangeEventToEventReduceChangeEvent } from './rx-change-event'; export function getSortFieldsOfQuery(primaryKey, query) { if (!query.sort || query.sort.length === 0) { return [primaryKey]; @@ -11,16 +13,51 @@ export function getSortFieldsOfQuery(primaryKey, query) { export var RXQUERY_QUERY_PARAMS_CACHE = new WeakMap(); export function getQueryParams(rxQuery) { if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) { - var storage = rxQuery.collection.database.storage; + var collection = rxQuery.collection; var queryJson = rxQuery.toJSON(); - var primaryKey = rxQuery.collection.schema.primaryPath; + var primaryKey = collection.schema.primaryPath; + /** + * Create a custom sort comparator + * that uses the hooks to ensure + * we send for example compressed documents to be sorted by compressed queries. + */ + + var sortComparator = collection.storageInstance.getSortComparator(queryJson); + + var useSortComparator = function useSortComparator(docA, docB) { + var sortComparatorData = { + docA: docA, + docB: docB, + rxQuery: rxQuery + }; + runPluginHooks('preSortComparator', sortComparatorData); + return sortComparator(sortComparatorData.docA, sortComparatorData.docB); + }; + /** + * Create a custom query matcher + * that uses the hooks to ensure + * we send for example compressed documents to match compressed queries. + */ + + + var queryMatcher = collection.storageInstance.getQueryMatcher(queryJson); + + var useQueryMatcher = function useQueryMatcher(doc) { + var queryMatcherData = { + doc: doc, + rxQuery: rxQuery + }; + runPluginHooks('preQueryMatcher', queryMatcherData); + return queryMatcher(queryMatcherData.doc); + }; + var ret = { primaryKey: rxQuery.collection.schema.primaryPath, skip: queryJson.skip, limit: queryJson.limit, sortFields: getSortFieldsOfQuery(primaryKey, queryJson), - sortComparator: storage.getSortComparator(primaryKey, queryJson), - queryMatcher: storage.getQueryMatcher(primaryKey, queryJson) + sortComparator: useSortComparator, + queryMatcher: useQueryMatcher }; RXQUERY_QUERY_PARAMS_CACHE.set(rxQuery, ret); return ret; @@ -42,7 +79,7 @@ export function calculateNewResults(rxQuery, rxChangeEvents) { var previousResultsMap = rxQuery._resultsDataMap; var changed = false; var foundNonOptimizeable = rxChangeEvents.find(function (cE) { - var eventReduceEvent = cE.toEventReduceChangeEvent(); + var eventReduceEvent = rxChangeEventToEventReduceChangeEvent(cE); var actionName = calculateActionName({ queryParams: queryParams, changeEvent: eventReduceEvent, diff --git a/dist/es/hooks.js b/dist/es/hooks.js index 7d02e03d8b3..3000af1dd13 100644 --- a/dist/es/hooks.js +++ b/dist/es/hooks.js @@ -45,6 +45,34 @@ export var HOOKS = { createRxSchema: [], preCreateRxQuery: [], createRxQuery: [], + + /** + * Runs before a document is send to the query matcher. + */ + preQueryMatcher: [], + + /** + * Runs before a document is send to the sortComparator. + */ + preSortComparator: [], + + /** + * Runs before a query is send to the + * prepareQuery function of the storage engine. + */ + prePrepareQuery: [], + + /** + * Runs before the document data is send to the + * bulkWrite of the storage instance + */ + preWriteToStorageInstance: [], + + /** + * Runs after the document data is ready from + * the storage instance. + */ + postReadFromInstance: [], createRxDocument: [], /** @@ -54,15 +82,12 @@ export var HOOKS = { postCreateRxDocument: [], /** - * runs before a pouchdb-instance is created - * gets pouchParameters as attribute so you can manipulate them - * { - * location: string, - * adapter: any, - * settings: object - * } + * Runs before a RxStorageInstance is created + * gets the params of createStorageInstance() + * as attribute so you can manipulate them. + * Notice that you have to clone stuff before mutating the inputs. */ - preCreatePouchDb: [], + preCreateRxStorageInstance: [], /** * runs on the document-data before the document is migrated diff --git a/dist/es/index.js b/dist/es/index.js index 4effcca7493..56427544847 100644 --- a/dist/es/index.js +++ b/dist/es/index.js @@ -19,12 +19,8 @@ import { RxDBEncryptionPlugin } from './plugins/encryption'; addRxPlugin(RxDBEncryptionPlugin); import { RxDBUpdatePlugin } from './plugins/update'; addRxPlugin(RxDBUpdatePlugin); -import { RxDBWatchForChangesPlugin } from './plugins/watch-for-changes'; -addRxPlugin(RxDBWatchForChangesPlugin); -import { RxDBReplicationPlugin } from './plugins/replication'; -addRxPlugin(RxDBReplicationPlugin); -import { RxDBAdapterCheckPlugin } from './plugins/adapter-check'; -addRxPlugin(RxDBAdapterCheckPlugin); +import { RxDBReplicationCouchDBPlugin } from './plugins/replication-couchdb'; +addRxPlugin(RxDBReplicationCouchDBPlugin); import { RxDBJsonDumpPlugin } from './plugins/json-dump'; addRxPlugin(RxDBJsonDumpPlugin); import { RxDBInMemoryPlugin } from './plugins/in-memory'; @@ -37,4 +33,5 @@ import { RxDBQueryBuilderPlugin } from './plugins/query-builder'; addRxPlugin(RxDBQueryBuilderPlugin); // re-export things from core export * from './core'; +export * from './plugins/pouchdb'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/overwritable.js b/dist/es/overwritable.js index da91c070bd3..da1f9214f5f 100644 --- a/dist/es/overwritable.js +++ b/dist/es/overwritable.js @@ -12,6 +12,16 @@ export var overwritable = { return false; }, + /** + * Deep freezes and object when in dev-mode. + * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode. + * Also we can ensure the readonly state via typescript + * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ + deepFreezeWhenDevMode: function deepFreezeWhenDevMode(obj) { + return obj; + }, + /** * validates if a password can be used * @overwritten by plugin (optional) @@ -21,20 +31,6 @@ export var overwritable = { throw pluginMissing('encryption'); }, - /** - * creates a key-compressor for the given schema - */ - createKeyCompressor: function createKeyCompressor(_rxSchema) { - throw pluginMissing('key-compression'); - }, - - /** - * checks if the given adapter can be used - */ - checkAdapter: function checkAdapter(_adapter) { - throw pluginMissing('adapter-check'); - }, - /** * overwritte to map error-codes to text-messages */ diff --git a/dist/es/plugin.js b/dist/es/plugin.js index 0ae06d64244..dc5ef2ca07b 100644 --- a/dist/es/plugin.js +++ b/dist/es/plugin.js @@ -9,9 +9,9 @@ import { basePrototype as RxDocumentPrototype } from './rx-document'; import { RxQueryBase } from './rx-query'; import { RxCollectionBase } from './rx-collection'; import { RxDatabaseBase } from './rx-database'; -import { PouchDB } from './pouch-db'; import { overwritable } from './overwritable'; import { HOOKS, runPluginHooks } from './hooks'; +import { newRxTypeError } from './rx-error'; /** * prototypes that can be manipulated with a plugin */ @@ -25,6 +25,11 @@ var PROTOTYPES = { RxDatabase: RxDatabaseBase.prototype }; var ADDED_PLUGINS = new Set(); +/** + * Add a plugin to the RxDB library. + * Plugins are added globally and cannot be removed. + */ + export function addRxPlugin(plugin) { runPluginHooks('preAddRxPlugin', { plugin: plugin, @@ -36,17 +41,21 @@ export function addRxPlugin(plugin) { } else { ADDED_PLUGINS.add(plugin); } + /** + * Since version 10.0.0 we decoupled pouchdb from + * the rxdb core. Therefore pouchdb plugins must be added + * with the addPouchPlugin() method of the pouchdb plugin. + */ + if (!plugin.rxdb) { - // pouchdb-plugin - if (typeof plugin === 'object' && plugin["default"]) plugin = plugin["default"]; - PouchDB.plugin(plugin); - return; - } + throw newRxTypeError('PL1', { + plugin: plugin + }); + } // prototype-overwrites - var rxPlugin = plugin; // prototype-overwrites - if (rxPlugin.prototypes) { + if (plugin.prototypes) { Object.entries(plugin.prototypes).forEach(function (_ref) { var name = _ref[0], fun = _ref[1]; @@ -55,12 +64,12 @@ export function addRxPlugin(plugin) { } // overwritable-overwrites - if (rxPlugin.overwritable) { + if (plugin.overwritable) { Object.assign(overwritable, plugin.overwritable); } // extend-hooks - if (rxPlugin.hooks) { + if (plugin.hooks) { Object.entries(plugin.hooks).forEach(function (_ref2) { var name = _ref2[0], fun = _ref2[1]; diff --git a/dist/es/plugins/attachments.js b/dist/es/plugins/attachments.js index 1ff899d50fe..fdd273b894b 100644 --- a/dist/es/plugins/attachments.js +++ b/dist/es/plugins/attachments.js @@ -1,10 +1,9 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _regeneratorRuntime from "@babel/runtime/regenerator"; import { map } from 'rxjs/operators'; -import { createUpdateEvent } from './../rx-change-event'; -import { now, blobBufferUtil } from './../util'; +import { blobBufferUtil, flatClone } from './../util'; import { newRxError } from '../rx-error'; -import { pouchAttachmentBinaryHash } from '../pouch-db'; +import { writeSingle } from '../rx-storage-helper'; function ensureSchemaSupportsAttachments(doc) { var schemaJson = doc.collection.schema.jsonSchema; @@ -16,17 +15,6 @@ function ensureSchemaSupportsAttachments(doc) { } } -function resyncRxDocument(doc) { - var startTime = now(); - return doc.collection.pouch.get(doc.primary).then(function (docDataFromPouch) { - var data = doc.collection._handleFromPouch(docDataFromPouch); - - var endTime = now(); - var changeEvent = createUpdateEvent(doc.collection, data, null, startTime, endTime, doc); - doc.$emit(changeEvent); - }); -} - var _assignMethodsToAttachment = function _assignMethodsToAttachment(attachment) { Object.entries(attachment.doc.collection.attachments).forEach(function (_ref) { var funName = _ref[0], @@ -50,43 +38,122 @@ export var RxAttachment = /*#__PURE__*/function () { id = _ref2.id, type = _ref2.type, length = _ref2.length, - digest = _ref2.digest, - rev = _ref2.rev; + digest = _ref2.digest; this.doc = doc; this.id = id; this.type = type; this.length = length; this.digest = digest; - this.rev = rev; _assignMethodsToAttachment(this); } var _proto = RxAttachment.prototype; - _proto.remove = function remove() { - var _this = this; + _proto.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + var _this = this; + + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + this.doc._atomicQueue = this.doc._atomicQueue.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var docWriteData, writeResult, newData; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + docWriteData = flatClone(_this.doc._data); + docWriteData._attachments = flatClone(docWriteData._attachments); + delete docWriteData._attachments[_this.id]; + _context.next = 5; + return writeSingle(_this.doc.collection.storageInstance, { + previous: _this.doc._data, + document: docWriteData + }); + + case 5: + writeResult = _context.sent; + newData = flatClone(_this.doc._data); + newData._rev = writeResult._rev; + newData._attachments = writeResult._attachments; - return this.doc.collection.pouch.removeAttachment(this.doc.primary, this.id, this.doc._data._rev).then(function () { - return resyncRxDocument(_this.doc); - }); - } + _this.doc._dataSync$.next(newData); + + case 10: + case "end": + return _context.stop(); + } + } + }, _callee); + }))); + return _context2.abrupt("return", this.doc._atomicQueue); + + case 2: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function remove() { + return _remove.apply(this, arguments); + } + + return remove; + }() /** * returns the data for the attachment */ ; - _proto.getData = function getData() { - var _this2 = this; + _proto.getData = + /*#__PURE__*/ + function () { + var _getData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var plainData, dataString, ret; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.doc.collection.storageInstance.getAttachmentData(this.doc.primary, this.id); + + case 2: + plainData = _context3.sent; + + if (!shouldEncrypt(this.doc.collection.schema)) { + _context3.next = 11; + break; + } + + _context3.next = 6; + return blobBufferUtil.toString(plainData); + + case 6: + dataString = _context3.sent; + ret = blobBufferUtil.createBlobBuffer(this.doc.collection._crypter._decryptString(dataString), this.type); + return _context3.abrupt("return", ret); + + case 11: + return _context3.abrupt("return", plainData); + + case 12: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); - return this.doc.collection.pouch.getAttachment(this.doc.primary, this.id).then(function (data) { - if (shouldEncrypt(_this2.doc.collection.schema)) { - return blobBufferUtil.toString(data).then(function (dataString) { - return blobBufferUtil.createBlobBuffer(_this2.doc.collection._crypter._decryptValue(dataString), _this2.type); - }); - } else return data; - }); - }; + function getData() { + return _getData.apply(this, arguments); + } + + return getData; + }(); _proto.getStringData = function getStringData() { return this.getData().then(function (bufferBlob) { @@ -96,14 +163,13 @@ export var RxAttachment = /*#__PURE__*/function () { return RxAttachment; }(); -export function fromPouchDocument(id, pouchDocAttachment, rxDocument) { +export function fromStorageInstanceResult(id, attachmentData, rxDocument) { return new RxAttachment({ doc: rxDocument, id: id, - type: pouchDocAttachment.content_type, - length: pouchDocAttachment.length, - digest: pouchDocAttachment.digest, - rev: pouchDocAttachment.revpos + type: attachmentData.type, + length: attachmentData.length, + digest: attachmentData.digest }); } @@ -119,83 +185,110 @@ export function putAttachment(_x) { */ function _putAttachment() { - _putAttachment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref3) { - var _this5 = this; + _putAttachment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(_ref4) { + var _this4 = this; var id, data, - _ref3$type, + _ref4$type, type, skipIfSame, - blobBuffer, - _args2 = arguments; + dataString, + encrypted, + _args5 = arguments; - return _regeneratorRuntime.wrap(function _callee2$(_context2) { + return _regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context5.prev = _context5.next) { case 0: - id = _ref3.id, data = _ref3.data, _ref3$type = _ref3.type, type = _ref3$type === void 0 ? 'text/plain' : _ref3$type; - skipIfSame = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : false; + id = _ref4.id, data = _ref4.data, _ref4$type = _ref4.type, type = _ref4$type === void 0 ? 'text/plain' : _ref4$type; + skipIfSame = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : true; ensureSchemaSupportsAttachments(this); + /** + * Then encryption plugin is only able to encrypt strings, + * so unpack as string first. + */ - if (shouldEncrypt(this.collection.schema)) { - data = this.collection._crypter._encryptValue(data); + if (!shouldEncrypt(this.collection.schema)) { + _context5.next = 9; + break; } - blobBuffer = blobBufferUtil.createBlobBuffer(data, type); - this._atomicQueue = this._atomicQueue.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { - var currentMeta, newHash; - return _regeneratorRuntime.wrap(function _callee$(_context) { + _context5.next = 6; + return blobBufferUtil.toString(data); + + case 6: + dataString = _context5.sent; + encrypted = this.collection._crypter._encryptString(dataString); + data = blobBufferUtil.createBlobBuffer(encrypted, 'text/plain'); + + case 9: + this._atomicQueue = this._atomicQueue.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { + var currentMeta, newHash, docWriteData, useData, writeResult, attachmentData, attachment, newData; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { - switch (_context.prev = _context.next) { + switch (_context4.prev = _context4.next) { case 0: - if (!(skipIfSame && _this5._data._attachments && _this5._data._attachments[id])) { - _context.next = 7; + if (!(skipIfSame && _this4._data._attachments && _this4._data._attachments[id])) { + _context4.next = 7; break; } - currentMeta = _this5._data._attachments[id]; - _context.next = 4; - return pouchAttachmentBinaryHash(data); + currentMeta = _this4._data._attachments[id]; + _context4.next = 4; + return _this4.collection.database.storage.hash(data); case 4: - newHash = _context.sent; + newHash = _context4.sent; - if (!(currentMeta.content_type === type && currentMeta.digest === newHash)) { - _context.next = 7; + if (!(currentMeta.type === type && currentMeta.digest === newHash)) { + _context4.next = 7; break; } - return _context.abrupt("return", _this5.getAttachment(id)); + return _context4.abrupt("return", _this4.getAttachment(id)); case 7: - return _context.abrupt("return", _this5.collection.pouch.putAttachment(_this5.primary, id, _this5._data._rev, blobBuffer, type).then(function () { - return _this5.collection.pouch.get(_this5.primary); - }).then(function (docData) { - var attachmentData = docData._attachments[id]; - var attachment = fromPouchDocument(id, attachmentData, _this5); - _this5._data._rev = docData._rev; - _this5._data._attachments = docData._attachments; - return resyncRxDocument(_this5).then(function () { - return attachment; - }); - })); - - case 8: + docWriteData = flatClone(_this4._data); + docWriteData._attachments = flatClone(docWriteData._attachments); + useData = typeof data === 'string' ? Buffer.from(data) : data; + docWriteData._attachments[id] = { + type: type, + data: useData + }; + _context4.next = 13; + return writeSingle(_this4.collection.storageInstance, { + previous: _this4._data, + document: docWriteData + }); + + case 13: + writeResult = _context4.sent; + attachmentData = writeResult._attachments[id]; + attachment = fromStorageInstanceResult(id, attachmentData, _this4); + newData = flatClone(_this4._data); + newData._rev = writeResult._rev; + newData._attachments = writeResult._attachments; + + _this4._dataSync$.next(newData); + + return _context4.abrupt("return", attachment); + + case 21: case "end": - return _context.stop(); + return _context4.stop(); } } - }, _callee); + }, _callee4); }))); - return _context2.abrupt("return", this._atomicQueue); + return _context5.abrupt("return", this._atomicQueue); - case 7: + case 11: case "end": - return _context2.stop(); + return _context5.stop(); } } - }, _callee2, this); + }, _callee5, this); })); return _putAttachment.apply(this, arguments); } @@ -207,7 +300,7 @@ export function getAttachment(id) { if (!docData._attachments || !docData._attachments[id]) return null; var attachmentData = docData._attachments[id]; - var attachment = fromPouchDocument(id, attachmentData, this); + var attachment = fromStorageInstanceResult(id, attachmentData, this); return attachment; } /** @@ -215,16 +308,19 @@ export function getAttachment(id) { */ export function allAttachments() { - var _this3 = this; + var _this2 = this; ensureSchemaSupportsAttachments(this); var docData = this._dataSync$.getValue(); // if there are no attachments, the field is missing - if (!docData._attachments) return []; + if (!docData._attachments) { + return []; + } + return Object.keys(docData._attachments).map(function (id) { - return fromPouchDocument(id, docData._attachments[id], _this3); + return fromStorageInstanceResult(id, docData._attachments[id], _this2); }); } export function preMigrateDocument(_x2) { @@ -232,71 +328,66 @@ export function preMigrateDocument(_x2) { } function _preMigrateDocument() { - _preMigrateDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(data) { + _preMigrateDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(data) { var attachments, mustDecrypt, newAttachments; - return _regeneratorRuntime.wrap(function _callee4$(_context4) { + return _regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context7.prev = _context7.next) { case 0: attachments = data.docData._attachments; if (!attachments) { - _context4.next = 7; + _context7.next = 7; break; } mustDecrypt = !!shouldEncrypt(data.oldCollection.schema); newAttachments = {}; - _context4.next = 6; + _context7.next = 6; return Promise.all(Object.keys(attachments).map( /*#__PURE__*/function () { - var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(attachmentId) { + var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(attachmentId) { var attachment, docPrimary, rawAttachmentData; - return _regeneratorRuntime.wrap(function _callee3$(_context3) { + return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context6.prev = _context6.next) { case 0: attachment = attachments[attachmentId]; docPrimary = data.docData[data.oldCollection.schema.primaryPath]; - _context3.next = 4; - return data.oldCollection.pouchdb.getAttachment(docPrimary, attachmentId); + _context6.next = 4; + return data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId); case 4: - rawAttachmentData = _context3.sent; + rawAttachmentData = _context6.sent; if (!mustDecrypt) { - _context3.next = 9; + _context6.next = 9; break; } - _context3.next = 8; + _context6.next = 8; return blobBufferUtil.toString(rawAttachmentData).then(function (dataString) { - return blobBufferUtil.createBlobBuffer(data.oldCollection._crypter._decryptValue(dataString), attachment.content_type); + return blobBufferUtil.createBlobBuffer(data.oldCollection._crypter._decryptString(dataString), attachment.type); }); case 8: - rawAttachmentData = _context3.sent; + rawAttachmentData = _context6.sent; case 9: newAttachments[attachmentId] = { - digest: attachment.digest, - length: attachment.length, - revpos: attachment.revpos, - content_type: attachment.content_type, - stub: false, - // set this to false because now we have the full data + type: attachment.type, data: rawAttachmentData }; case 10: case "end": - return _context3.stop(); + return _context6.stop(); } } - }, _callee3); + }, _callee6); })); return function (_x4) { - return _ref6.apply(this, arguments); + return _ref7.apply(this, arguments); }; }())); @@ -309,10 +400,10 @@ function _preMigrateDocument() { case 7: case "end": - return _context4.stop(); + return _context7.stop(); } } - }, _callee4); + }, _callee7); })); return _preMigrateDocument.apply(this, arguments); } @@ -322,19 +413,19 @@ export function postMigrateDocument(_x3) { } function _postMigrateDocument() { - _postMigrateDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(action) { - return _regeneratorRuntime.wrap(function _callee5$(_context5) { + _postMigrateDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(_action) { + return _regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { - switch (_context5.prev = _context5.next) { + switch (_context8.prev = _context8.next) { case 0: - return _context5.abrupt("return"); + return _context8.abrupt("return"); case 1: case "end": - return _context5.stop(); + return _context8.stop(); } } - }, _callee5); + }, _callee8); })); return _postMigrateDocument.apply(this, arguments); } @@ -347,18 +438,21 @@ export var prototypes = { proto.allAttachments = allAttachments; Object.defineProperty(proto, 'allAttachments$', { get: function allAttachments$() { - var _this4 = this; + var _this3 = this; return this._dataSync$.pipe(map(function (data) { - if (!data['_attachments']) return {}; + if (!data['_attachments']) { + return {}; + } + return data['_attachments']; }), map(function (attachmentsData) { return Object.entries(attachmentsData); }), map(function (entries) { - return entries.map(function (_ref4) { - var id = _ref4[0], - attachmentData = _ref4[1]; - return fromPouchDocument(id, attachmentData, _this4); + return entries.map(function (_ref5) { + var id = _ref5[0], + attachmentData = _ref5[1]; + return fromStorageInstanceResult(id, attachmentData, _this3); }); })); } diff --git a/dist/es/plugins/backup/index.js b/dist/es/plugins/backup/index.js index ca7b6104af9..2fbad6a2bff 100644 --- a/dist/es/plugins/backup/index.js +++ b/dist/es/plugins/backup/index.js @@ -1,9 +1,11 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _regeneratorRuntime from "@babel/runtime/regenerator"; import * as path from 'path'; -import { BehaviorSubject, firstValueFrom, fromEvent, Subject } from 'rxjs'; +import { BehaviorSubject, firstValueFrom, Subject } from 'rxjs'; import { filter, map } from 'rxjs/operators'; -import { getNewestSequence } from '../../pouch-db'; +import { newRxError } from '../../rx-error'; +import { getNewestSequence } from '../../rx-storage-helper'; +import { getFromMapOrThrow } from '../../util'; import { clearFolder, deleteFolder, documentFolder, ensureFolderExists, getMeta, prepareFolders, setMeta, writeJsonToFile, writeToFile } from './file-util'; /** * Backups a single documents, @@ -96,10 +98,10 @@ function addToBackupStates(db, state) { BACKUP_STATES_BY_DB.set(db, []); } - var ar = BACKUP_STATES_BY_DB.get(db); + var ar = getFromMapOrThrow(BACKUP_STATES_BY_DB, db); if (!ar) { - throw new Error('this should never happen'); + throw newRxError('SNH'); } ar.push(state); @@ -193,7 +195,7 @@ export var RxBackupState = /*#__PURE__*/function () { case 4: _context5.next = 6; - return getNewestSequence(collection.pouch); + return getNewestSequence(collection.storageInstance); case 6: newestSeq = _context5.sent; @@ -208,7 +210,7 @@ export var RxBackupState = /*#__PURE__*/function () { lastSequence = meta.collectionStates[collectionName].lastSequence; hasMore = true; _loop = /*#__PURE__*/_regeneratorRuntime.mark(function _loop() { - var pouchChanges, docIds, docs; + var changesResult, docIds, docs; return _regeneratorRuntime.wrap(function _loop$(_context4) { while (1) { switch (_context4.prev = _context4.next) { @@ -218,28 +220,25 @@ export var RxBackupState = /*#__PURE__*/function () { case 2: _context4.next = 4; - return collection.pouch.changes({ - live: false, - since: lastSequence, + return collection.storageInstance.getChangedDocuments({ + startSequence: lastSequence, limit: _this2.options.batchSize, - include_docs: false + order: 'asc' }); case 4: - pouchChanges = _context4.sent; - lastSequence = pouchChanges.last_seq; + changesResult = _context4.sent; + lastSequence = changesResult.lastSequence; meta.collectionStates[collectionName].lastSequence = lastSequence; - docIds = pouchChanges.results.filter(function (doc) { - if (processedDocuments.has(doc.id) && doc.seq < newestSeq) { + docIds = changesResult.changedDocuments.filter(function (changedDocument) { + if (processedDocuments.has(changedDocument.id) && changedDocument.sequence < newestSeq) { return false; } else { - processedDocuments.add(doc.id); + processedDocuments.add(changedDocument.id); return true; } }).map(function (r) { return r.id; - }).filter(function (id) { - return !id.startsWith('_design/'); }) // unique . // unique filter(function (elem, pos, arr) { @@ -405,11 +404,7 @@ export var RxBackupState = /*#__PURE__*/function () { var collections = Object.values(this.database.collections); collections.forEach(function (collection) { - var changes$ = fromEvent(collection.pouch.changes({ - since: 'now', - live: true, - include_docs: false - }), 'change'); + var changes$ = collection.storageInstance.changeStream(); var sub = changes$.subscribe(function () { _this3.persistOnce(); }); diff --git a/dist/es/plugins/dev-mode/check-names.js b/dist/es/plugins/dev-mode/check-names.js new file mode 100644 index 00000000000..9dbee01531b --- /dev/null +++ b/dist/es/plugins/dev-mode/check-names.js @@ -0,0 +1,35 @@ +import { newRxError, newRxTypeError } from '../../rx-error'; +import { isFolderPath } from '../../util'; +var validCouchDBStringRegexStr = '^[a-z][_$a-z0-9]*$'; +var validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr); +/** + * Validates that a given string is ok to be used with couchdb-collection-names. + * We only allow these strings as database- or collectionnames because it ensures + * that you later do not get in troubble when you want to use the database together witch couchdb. + * + * @link https://wiki.apache.org/couchdb/HTTP_database_API + * @throws {Error} + */ + +export function validateDatabaseName(name) { + if (typeof name !== 'string' || name.length === 0) { + throw newRxTypeError('UT1', { + name: name + }); + } // do not check, if foldername is given + + + if (isFolderPath(name)) { + return true; + } + + if (!name.match(validCouchDBStringRegex)) { + throw newRxError('UT2', { + regex: validCouchDBStringRegexStr, + givenName: name + }); + } + + return true; +} +//# sourceMappingURL=check-names.js.map \ No newline at end of file diff --git a/dist/es/plugins/dev-mode/check-schema.js b/dist/es/plugins/dev-mode/check-schema.js index cbc9e0e4f4c..14db7a1f255 100644 --- a/dist/es/plugins/dev-mode/check-schema.js +++ b/dist/es/plugins/dev-mode/check-schema.js @@ -14,8 +14,9 @@ import { rxDocumentProperties } from './entity-properties'; */ export function checkFieldNameRegex(fieldName) { - if (fieldName === '') return; - if (fieldName === '_id') return; + if (fieldName === '') return; // TODO why is the fieldname allowed to be empty string? + + if (fieldName === '_deleted') return; if (['properties', 'language'].includes(fieldName)) { throw newRxError('SC23', { @@ -109,7 +110,7 @@ export function validateFieldsDeep(jsonSchema) { if (!isNested) { // check underscore fields if (fieldName.charAt(0) === '_') { - if (fieldName === '_id' && schemaObj.primary) { + if (fieldName === '_deleted') { return; } @@ -161,6 +162,12 @@ function getSchemaPropertyRealPath(shortPath) { export function checkSchema(jsonSchema) { + if (!jsonSchema.primaryKey) { + throw newRxError('SC30', { + schema: jsonSchema + }); + } + if (!jsonSchema.hasOwnProperty('properties')) { throw newRxError('SC29', { schema: jsonSchema @@ -182,20 +189,11 @@ export function checkSchema(jsonSchema) { } validateFieldsDeep(jsonSchema); - var primaryPath; Object.keys(jsonSchema.properties).forEach(function (key) { var value = jsonSchema.properties[key]; // check primary - if (value.primary) { - if (primaryPath) { - throw newRxError('SC12', { - value: value - }); - } - - primaryPath = key; - - if (value.index) { + if (key === jsonSchema.primaryKey) { + if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) { throw newRxError('SC13', { value: value }); @@ -207,7 +205,7 @@ export function checkSchema(jsonSchema) { }); } - if (value.encrypted) { + if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) { throw newRxError('SC15', { value: value }); diff --git a/dist/es/plugins/dev-mode/error-messages.js b/dist/es/plugins/dev-mode/error-messages.js index 131119730d7..f280b4068b7 100644 --- a/dist/es/plugins/dev-mode/error-messages.js +++ b/dist/es/plugins/dev-mode/error-messages.js @@ -9,6 +9,9 @@ export var ERROR_MESSAGES = { UT2: "collection- and database-names must match the regex\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\'", UT3: 'replication-direction must either be push or pull or both. But not none', UT4: 'given leveldown is no valid adapter', + // plugins + PL1: 'Given plugin is not RxDB plugin. Pouchdb plugins must be added via addPouchPlugin()', + PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.', // pouch-db.js P1: 'PouchDB.getBatch: limit must be > 2', // rx-query @@ -34,19 +37,19 @@ export var ERROR_MESSAGES = { MQ8: 'Can\'t mix sort syntaxes. Use either array or object', // rx-database DB1: 'RxDocument.prepare(): another instance on this adapter has a different password', - DB2: 'RxDatabase.collection(): collection-names cannot start with underscore _', - DB3: 'RxDatabase.collection(): collection already exists. use myDatabase.[collectionName] to get it', - DB4: 'RxDatabase.collection(): schema is missing', - DB5: 'RxDatabase.collection(): collection-name not allowed', - DB6: 'RxDatabase.collection(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', - DB7: 'RxDatabase.collection(): schema encrypted but no password given', + DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _', + DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it', + DB4: 'RxDatabase.addCollections(): schema is missing', + DB5: 'RxDatabase.addCollections(): collection-name not allowed', + DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', + DB7: 'RxDatabase.addCollections(): schema encrypted but no password given', DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\n' + 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional', DB9: 'RxDatabase.create(): Adapter not added. Use RxDB.plugin(require(\'pouchdb-adapter-[adaptername]\');', DB10: 'RxDatabase.create(): To use leveldown-adapters, you have to add the leveldb-plugin. Use RxDB.plugin(require(\'pouchdb-adapter-leveldb\'));', DB11: 'RxDatabase.create(): Invalid db-name, folder-paths must not have an ending slash', // rx-collection COL1: 'RxDocument.insert() You cannot insert an existing document', - COL2: 'RxCollection.insert() do not provide ._id when it is not the primary key', + // removed in 10.0.0 - COL2: 'RxCollection.insert() do not provide ._id when it is not the primary key', COL3: 'RxCollection.upsert() does not work without primary', COL4: 'RxCollection.atomicUpsert() does not work without primary', COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)', @@ -76,7 +79,7 @@ export var ERROR_MESSAGES = { DOC9: 'final fields cannot be modified', DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected', DOC11: 'RxDocument.save(): cant save deleted document', - DOC12: 'RxDocument.save(): error', + // removed in 10.0.0 DOC12: 'RxDocument.save(): error', DOC13: 'RxDocument.remove(): Document is already deleted', DOC14: 'RxDocument.destroy() does not exist', DOC15: 'query cannot be an array', @@ -93,8 +96,8 @@ export var ERROR_MESSAGES = { EN2: 'validatePassword: min-length of password not complied', // plugins/json-dump.js JD1: 'You must create the collections before you can import their data', - JD2: 'RxCollection.importDump(): the imported json relies on a different schema', - JD3: 'RxCollection.importDump(): json.passwordHash does not match the own', + JD2: 'RxCollection.importJSON(): the imported json relies on a different schema', + JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own', // plugins/leader-election.js // plugins/local-documents.js LD1: 'RxDocument.allAttachments$ cant use attachments on local documents', @@ -106,10 +109,10 @@ export var ERROR_MESSAGES = { LD7: 'Local document already exists', // plugins/replication.js RC1: 'Replication: already added', - RC2: 'RxCollection.sync() query must be from the same RxCollection', - RC3: 'RxCollection.sync() Do not use a collection\'s pouchdb as remote, use the collection instead', - RC4: 'RxReplicationState.awaitInitialReplication() cannot await inital replication when live: true', - RC5: 'RxReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance', + RC2: 'RxCollection.syncCouchDB() query must be from the same RxCollection', + RC3: 'RxCollection.syncCouchDB() Do not use a collection\'s pouchdb as remote, use the collection instead', + RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication when live: true', + RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance', // plugins/dev-mode/check-schema.js SC1: 'fieldnames do not match the regex', SC2: 'SchemaCheck: name \'item\' reserved for array-fields', @@ -120,7 +123,7 @@ export var ERROR_MESSAGES = { SC8: 'SchemaCheck: first level-fields cannot start with underscore _', SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically', SC11: 'SchemaCheck: schema needs a number >=0 as version', - SC12: 'SchemaCheck: primary can only be defined once', + // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once', SC13: 'SchemaCheck: primary is always index, do not declare it as index', SC14: 'SchemaCheck: primary is always unique, do not declare it as index', SC15: 'SchemaCheck: primary cannot be encrypted', @@ -138,16 +141,24 @@ export var ERROR_MESSAGES = { SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level', SC28: 'SchemaCheck: encrypted fields is not defined in the schema', SC29: 'SchemaCheck: missing object key \'properties\'', + SC30: 'SchemaCheck: primaryKey is required', // plugins/dev-mode DEV1: 'dev-mode added multiple times, ' + 'this is likely because you have mixed up the import from the the plugins/core and the full RxDB', // plugins/validate.js VD1: 'Sub-schema not found, does the schemaPath exists in your schema?', VD2: 'object does not match schema', // plugins/in-memory.js - IM1: 'InMemory: Memory-Adapter must be added. Use RxDB.plugin(require(\'pouchdb-adapter-memory\'));', + IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\'pouchdb-adapter-memory\'));', IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead', // plugins/server.js - S1: 'You cannot create collections after calling RxDatabase.server()' // plugins/replication-graphql.js + S1: 'You cannot create collections after calling RxDatabase.server()', + // plugins/replication-graphql.js + /** + * Should never be thrown, use this for + * null checks etc. so you do not have to increase the + * build size with error message strings. + */ + SNH: 'This should never happen' }; //# sourceMappingURL=error-messages.js.map \ No newline at end of file diff --git a/dist/es/plugins/dev-mode/index.js b/dist/es/plugins/dev-mode/index.js index 8fe40cb2e22..0988e8a1667 100644 --- a/dist/es/plugins/dev-mode/index.js +++ b/dist/es/plugins/dev-mode/index.js @@ -6,6 +6,25 @@ import { ensureCollectionNameValid, ensureDatabaseNameIsValid } from './unallowe import { checkQuery } from './check-query'; import { newRxError } from '../../rx-error'; export * from './check-schema'; +export * from './check-names'; + +var deepFreeze = require('deep-freeze'); +/** + * Deep freezes and object when in dev-mode. + * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode. + * Also we can ensure the readonly state via typescript + * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ + + +export function deepFreezeWhenDevMode(obj) { + // direct return if falsy + if (!obj) { + return obj; + } + + return deepFreeze(obj); +} var DEV_MODE_PLUGIN_NAME = 'dev-mode'; export var RxDBDevModePlugin = { name: DEV_MODE_PLUGIN_NAME, @@ -14,6 +33,7 @@ export var RxDBDevModePlugin = { isDevMode: function isDevMode() { return true; }, + deepFreezeWhenDevMode: deepFreezeWhenDevMode, tunnelErrorMessage: function tunnelErrorMessage(code) { if (!ERROR_MESSAGES[code]) { console.error('RxDB: Error-Code not known: ' + code); diff --git a/dist/es/plugins/dev-mode/unallowed-properties.js b/dist/es/plugins/dev-mode/unallowed-properties.js index 270ac6413ba..34cca3d2c0e 100644 --- a/dist/es/plugins/dev-mode/unallowed-properties.js +++ b/dist/es/plugins/dev-mode/unallowed-properties.js @@ -1,7 +1,7 @@ import { newRxError } from '../../rx-error'; import { rxDatabaseProperties } from './entity-properties'; -import { validateCouchDBString } from '../../pouch-db'; import { isFolderPath } from '../../util'; +import { validateDatabaseName } from './check-names'; /** * if the name of a collection * clashes with a property of RxDatabase, @@ -16,12 +16,7 @@ export function ensureCollectionNameValid(args) { } } export function ensureDatabaseNameIsValid(args) { - /** - * Not all strings can be used as couchdb collection name - * So we only allow couchdb-valid string as databse name - * which solves some strange bugs. - */ - validateCouchDBString(args.name); + validateDatabaseName(args.name); /** * The server-plugin has problems when a path with and ending slash is given * So we do not allow this. diff --git a/dist/es/plugins/encryption.js b/dist/es/plugins/encryption.js index 9d25122ea0b..7bbf19250cb 100644 --- a/dist/es/plugins/encryption.js +++ b/dist/es/plugins/encryption.js @@ -1,3 +1,6 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; + /** * this plugin adds the encryption-capabilities to rxdb * It's using crypto-js/aes for password-encryption @@ -6,7 +9,8 @@ import AES from 'crypto-js/aes'; import * as cryptoEnc from 'crypto-js/enc-utf8'; import { newRxTypeError, newRxError } from '../rx-error'; -import { hash, LOCAL_PREFIX } from '../util'; +import { hash } from '../util'; +import { findLocalDocument } from '../rx-storage-helper'; var minPassLength = 8; export function encrypt(value, password) { var encrypted = AES.encrypt(value, password); @@ -17,13 +21,13 @@ export function decrypt(cipherText, password) { return decrypted.toString(cryptoEnc); } -var _encryptValue = function _encryptValue(value) { - return encrypt(JSON.stringify(value), this.password); +var _encryptString = function _encryptString(value) { + return encrypt(value, this.password); }; -var _decryptValue = function _decryptValue(encryptedValue) { +var _decryptString = function _decryptString(encryptedValue) { var decrypted = decrypt(encryptedValue, this.password); - return JSON.parse(decrypted); + return decrypted; }; /** @@ -31,49 +35,87 @@ var _decryptValue = function _decryptValue(encryptedValue) { * to ensure there is/was no other instance with a different password * which would cause strange side effects when both instances save into the same db */ -export function storePasswordHashIntoDatabase(rxDatabase) { - if (!rxDatabase.password) { - return Promise.resolve(false); - } +export function storePasswordHashIntoDatabase(_x) { + return _storePasswordHashIntoDatabase.apply(this, arguments); +} - var pwHash = hash(rxDatabase.password); - return rxDatabase.internalStore.get(LOCAL_PREFIX + 'pwHash')["catch"](function () { - return null; - }).then(function (pwHashDoc) { - /** - * if pwHash was not saved, we save it, - * this operation might throw because another instance runs save at the same time, - */ - if (!pwHashDoc) { - return rxDatabase.internalStore.put({ - _id: LOCAL_PREFIX + 'pwHash', - value: pwHash - })["catch"](function () { - return null; - }).then(function () { - return true; - }); - } else if (pwHash !== pwHashDoc.value) { - // different hash was already set by other instance - return rxDatabase.destroy().then(function () { - throw newRxError('DB1', { - passwordHash: hash(rxDatabase.password), - existingPasswordHash: pwHashDoc.value - }); - }); - } +function _storePasswordHashIntoDatabase() { + _storePasswordHashIntoDatabase = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(rxDatabase) { + var pwHash, pwHashDocumentId, pwHashDoc, docData; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (rxDatabase.password) { + _context.next = 2; + break; + } + + return _context.abrupt("return", Promise.resolve(false)); + + case 2: + pwHash = hash(rxDatabase.password); + pwHashDocumentId = 'pwHash'; + _context.next = 6; + return findLocalDocument(rxDatabase.localDocumentsStore, pwHashDocumentId); + + case 6: + pwHashDoc = _context.sent; - return true; - }); + if (pwHashDoc) { + _context.next = 14; + break; + } + + docData = { + _id: pwHashDocumentId, + value: pwHash, + _attachments: {} + }; + _context.next = 11; + return rxDatabase.localDocumentsStore.bulkWrite([{ + document: docData + }]); + + case 11: + return _context.abrupt("return", true); + + case 14: + if (!(pwHash !== pwHashDoc.value)) { + _context.next = 20; + break; + } + + _context.next = 17; + return rxDatabase.destroy(); + + case 17: + throw newRxError('DB1', { + passwordHash: hash(rxDatabase.password), + existingPasswordHash: pwHashDoc.value + }); + + case 20: + return _context.abrupt("return", true); + + case 21: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _storePasswordHashIntoDatabase.apply(this, arguments); } + export var rxdb = true; export var prototypes = { /** * set crypto-functions for the Crypter.prototype */ Crypter: function Crypter(proto) { - proto._encryptValue = _encryptValue; - proto._decryptValue = _decryptValue; + proto._encryptString = _encryptString; + proto._decryptString = _decryptString; } }; export var overwritable = { diff --git a/dist/es/plugins/in-memory.js b/dist/es/plugins/in-memory.js index 800490c809d..1a5c14207e3 100644 --- a/dist/es/plugins/in-memory.js +++ b/dist/es/plugins/in-memory.js @@ -1,5 +1,7 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * This plugin adds RxCollection.inMemory() @@ -11,16 +13,13 @@ import { Subject, fromEvent as ObservableFromEvent, firstValueFrom } from 'rxjs' import { filter, map, mergeMap, delay } from 'rxjs/operators'; import { RxCollectionBase } from '../rx-collection'; import { clone, randomCouchString } from '../util'; -import { addRxPlugin } from '../core'; +import { PouchDB, getRxStoragePouch, pouchSwapIdToPrimary, pouchSwapPrimaryToId } from '../plugins/pouchdb'; import { createCrypter } from '../crypter'; import { createChangeEventBuffer } from '../change-event-buffer'; import { createRxSchema } from '../rx-schema'; -import { PouchDB } from '../pouch-db'; import { newRxError } from '../rx-error'; -import { getRxStoragePouchDb } from '../rx-storage-pouchdb'; // add the watch-for-changes-plugin - -import { RxDBWatchForChangesPlugin } from '../plugins/watch-for-changes'; -addRxPlugin(RxDBWatchForChangesPlugin); +import { getDocumentDataOfRxChangeEvent } from '../rx-change-event'; +import { _handleFromStorageInstance, _handleToStorageInstance } from '../rx-collection-helper'; var collectionCacheMap = new WeakMap(); var collectionPromiseCacheMap = new WeakMap(); var BULK_DOC_OPTIONS = { @@ -32,20 +31,18 @@ var BULK_DOC_OPTIONS_FALSE = { export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _inheritsLoose(InMemoryRxCollection, _RxCollectionBase); - function InMemoryRxCollection(parentCollection) { + function InMemoryRxCollection(parentCollection, pouchSettings) { var _this; - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _this = _RxCollectionBase.call(this, parentCollection.database, parentCollection.name, toCleanSchema(parentCollection.schema), pouchSettings, // pouchSettings {}, parentCollection._methods) || this; _this._eventCounter = 0; + _this.parentCollection = parentCollection; + _this.pouchSettings = pouchSettings; _this._isInMemory = true; - _this._parentCollection = parentCollection; - - _this._parentCollection.onDestroy.then(function () { + parentCollection.onDestroy.then(function () { return _this.destroy(); }); - _this._crypter = createCrypter(_this.database.password, _this.schema); _this._changeStreams = []; /** @@ -56,9 +53,10 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _this.onDestroy.then(function () { _this._changeStreams.forEach(function (stream) { return stream.cancel(); - }); + }); // delete all data + - _this.pouch.destroy(); + _this.storageInstance.internals.pouch.destroy(); }); // add orm functions and options from parent @@ -72,8 +70,6 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { } }); }); - var storage = getRxStoragePouchDb('memory'); - _this.pouch = storage.createStorageInstance('rxdb-in-memory', randomCouchString(10), 0); _this._observable$ = new Subject(); _this._changeEventBuffer = createChangeEventBuffer(_assertThisInitialized(_this)); var parentProto = Object.getPrototypeOf(parentCollection); @@ -89,7 +85,7 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _proto.prepareChild = function prepareChild() { var _this2 = this; - return setIndexes(this.schema, this.pouch).then(function () { + return setIndexes(this.schema, this.storageInstance.internals.pouch).then(function () { _this2._subs.push(_this2._observable$.subscribe(function (cE) { // when data changes, send it to RxDocument in docCache var doc = _this2._docCache.get(cE.documentId); @@ -98,23 +94,13 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { })); }) // initial sync parent's docs to own .then(function () { - return replicateExistingDocuments(_this2._parentCollection, _this2); + return replicateExistingDocuments(_this2.parentCollection, _this2); }).then(function () { - /** - * call watchForChanges() on both sides, - * to ensure none-rxdb-changes like replication - * will fire into the change-event-stream - */ - _this2._parentCollection.watchForChanges(); - - _this2.watchForChanges(); /** * create an ongoing replications between both sides */ - - var thisToParentSub = streamChangedDocuments(_this2).pipe(mergeMap(function (doc) { - return applyChangedDocumentToPouch(_this2._parentCollection, doc).then(function () { + return applyChangedDocumentToPouch(_this2.parentCollection, doc).then(function () { return doc['_rev']; }); })).subscribe(function (changeRev) { @@ -125,7 +111,7 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _this2._subs.push(thisToParentSub); - var parentToThisSub = streamChangedDocuments(_this2._parentCollection).subscribe(function (doc) { + var parentToThisSub = streamChangedDocuments(_this2.parentCollection).subscribe(function (doc) { return applyChangedDocumentToPouch(_this2, doc); }); @@ -141,7 +127,10 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _proto.awaitPersistence = function awaitPersistence() { var _this3 = this; - if (this._nonPersistentRevisions.size === 0) return Promise.resolve(); + if (this._nonPersistentRevisions.size === 0) { + return Promise.resolve(); + } + return firstValueFrom(this._nonPersistentRevisionsSubject.pipe(filter(function () { return _this3._nonPersistentRevisions.size === 0; }))); @@ -164,7 +153,9 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { }; _proto.$emit = function $emit(changeEvent) { - if (this._changeEventBuffer.hasChangeWithRevision(changeEvent.documentData && changeEvent.documentData._rev)) { + var doc = getDocumentDataOfRxChangeEvent(changeEvent); + + if (this._changeEventBuffer.hasChangeWithRevision(doc && doc._rev)) { return; } @@ -175,7 +166,7 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { if (this._eventCounter === 10) { this._eventCounter = 0; - this.pouch.compact(); + this.storageInstance.internals.pouch.compact(); } } /** @@ -185,7 +176,7 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { */ ; - _proto.sync = function sync() { + _proto.syncCouchDB = function syncCouchDB() { throw newRxError('IM2'); }; @@ -201,7 +192,6 @@ export var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { function toCleanSchema(rxSchema) { var newSchemaJson = clone(rxSchema.jsonSchema); newSchemaJson.keyCompression = false; - delete newSchemaJson.properties._id; delete newSchemaJson.properties._rev; delete newSchemaJson.properties._attachments; @@ -224,7 +214,8 @@ function toCleanSchema(rxSchema) { export function replicateExistingDocuments(fromCollection, toCollection) { - return fromCollection.pouch.allDocs({ + var pouch = fromCollection.storageInstance.internals.pouch; + return pouch.allDocs({ attachments: false, include_docs: true }).then(function (allRows) { @@ -234,14 +225,15 @@ export function replicateExistingDocuments(fromCollection, toCollection) { return !doc.language; }) // do not replicate design-docs .map(function (doc) { - return fromCollection._handleFromPouch(doc); + return _handleFromStorageInstance(fromCollection, doc); }) // swap back primary because keyCompression:false .map(function (doc) { - return fromCollection.schema.swapPrimaryToId(doc); + var primaryKey = fromCollection.schema.primaryPath; + return pouchSwapPrimaryToId(primaryKey, doc); }); if (docs.length === 0) return Promise.resolve([]); // nothing to replicate else { - return toCollection.pouch.bulkDocs({ + return toCollection.storageInstance.internals.pouch.bulkDocs({ docs: docs }, BULK_DOC_OPTIONS_FALSE).then(function () { return docs; @@ -277,8 +269,12 @@ export function streamChangedDocuments(rxCollection) { var prevFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (_i) { return true; }; - if (!rxCollection._doNotEmitSet) rxCollection._doNotEmitSet = new Set(); - var observable = ObservableFromEvent(rxCollection.pouch.changes({ + + if (!rxCollection._doNotEmitSet) { + rxCollection._doNotEmitSet = new Set(); + } + + var observable = ObservableFromEvent(rxCollection.storageInstance.internals.pouch.changes({ since: 'now', live: true, include_docs: true @@ -295,11 +291,19 @@ export function streamChangedDocuments(rxCollection) { filter(function (change) { // changes on the doNotEmit-list shell not be fired var emitFlag = change.id + ':' + change.doc._rev; - if (rxCollection._doNotEmitSet.has(emitFlag)) return false;else return true; + + if (rxCollection._doNotEmitSet.has(emitFlag)) { + return false; + } else { + return true; + } }), filter(function (change) { return prevFilter(change); }), map(function (change) { - return rxCollection._handleFromPouch(change.doc); + return _handleFromStorageInstance(rxCollection, change.doc); + }), map(function (d) { + var primaryKey = rxCollection.schema.primaryPath; + return pouchSwapIdToPrimary(primaryKey, d); })); return observable; } @@ -309,17 +313,22 @@ export function streamChangedDocuments(rxCollection) { */ export function applyChangedDocumentToPouch(rxCollection, docData) { - if (!rxCollection._doNotEmitSet) rxCollection._doNotEmitSet = new Set(); + if (!rxCollection._doNotEmitSet) { + rxCollection._doNotEmitSet = new Set(); + } + + var primaryKey = rxCollection.schema.primaryPath; - var transformedDoc = rxCollection._handleToPouch(docData); + var transformedDoc = _handleToStorageInstance(rxCollection, docData); - return rxCollection.pouch.get(transformedDoc._id).then(function (oldDoc) { + transformedDoc = pouchSwapPrimaryToId(primaryKey, transformedDoc); + return rxCollection.storageInstance.internals.pouch.get(transformedDoc._id).then(function (oldDoc) { return transformedDoc._rev = oldDoc._rev; })["catch"](function () { // doc not found, do not use a revision delete transformedDoc._rev; }).then(function () { - return rxCollection.pouch.bulkDocs({ + return rxCollection.storageInstance.internals.pouch.bulkDocs({ docs: [transformedDoc] }, BULK_DOC_OPTIONS); }).then(function (bulkRet) { @@ -344,34 +353,104 @@ var INIT_DONE = false; * called in the proto of RxCollection */ -export function spawnInMemory() { - var _this5 = this; - - if (!INIT_DONE) { - INIT_DONE = true; // ensure memory-adapter is added +export function inMemory() { + return _inMemory.apply(this, arguments); +} - if (!PouchDB.adapters || !PouchDB.adapters.memory) throw newRxError('IM1'); - } +function _inMemory() { + _inMemory = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var _this5 = this; + + var col, preparePromise; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (INIT_DONE) { + _context.next = 4; + break; + } + + INIT_DONE = true; // ensure memory-adapter is added + + if (!(!PouchDB.adapters || !PouchDB.adapters.memory)) { + _context.next = 4; + break; + } + + throw newRxError('IM1'); + + case 4: + if (!collectionCacheMap.has(this)) { + _context.next = 6; + break; + } + + return _context.abrupt("return", collectionPromiseCacheMap.get(this).then(function () { + return collectionCacheMap.get(_this5); + })); + + case 6: + col = new InMemoryRxCollection(this); + _context.next = 9; + return prepareInMemoryRxCollection(col); + + case 9: + preparePromise = col.prepareChild(); + collectionCacheMap.set(this, col); + collectionPromiseCacheMap.set(this, preparePromise); + return _context.abrupt("return", preparePromise.then(function () { + return col; + })); + + case 13: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + return _inMemory.apply(this, arguments); +} - if (collectionCacheMap.has(this)) { - // already exists for this collection -> wait until synced - return collectionPromiseCacheMap.get(this).then(function () { - return collectionCacheMap.get(_this5); - }); - } +export function prepareInMemoryRxCollection(_x) { + return _prepareInMemoryRxCollection.apply(this, arguments); +} - var col = new InMemoryRxCollection(this); - var preparePromise = col.prepareChild(); - collectionCacheMap.set(this, col); - collectionPromiseCacheMap.set(this, preparePromise); - return preparePromise.then(function () { - return col; - }); +function _prepareInMemoryRxCollection() { + _prepareInMemoryRxCollection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(instance) { + var memoryStorage; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + memoryStorage = getRxStoragePouch('memory', {}); + _context2.next = 3; + return memoryStorage.createStorageInstance({ + databaseName: 'rxdb-in-memory', + collectionName: randomCouchString(10), + schema: instance.schema.jsonSchema, + options: instance.pouchSettings + }); + + case 3: + instance.storageInstance = _context2.sent; + instance.pouch = instance.storageInstance.internals.pouch; + + case 5: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _prepareInMemoryRxCollection.apply(this, arguments); } + export var rxdb = true; export var prototypes = { RxCollection: function RxCollection(proto) { - proto.inMemory = spawnInMemory; + proto.inMemory = inMemory; } }; export var RxDBInMemoryPlugin = { diff --git a/dist/es/plugins/json-dump.js b/dist/es/plugins/json-dump.js index 114df12b216..34fd4a22daf 100644 --- a/dist/es/plugins/json-dump.js +++ b/dist/es/plugins/json-dump.js @@ -4,7 +4,7 @@ import { hash, now } from '../util'; import { createRxQuery, _getDefaultQuery } from '../rx-query'; import { newRxError } from '../rx-error'; -import { createInsertEvent } from '../rx-change-event'; +import { _handleToStorageInstance } from '../rx-collection-helper'; function dumpRxDatabase() { var _this = this; @@ -32,7 +32,7 @@ function dumpRxDatabase() { return _this.collections[colName]; }); return Promise.all(useCollections.map(function (col) { - return col.dump(decrypted); + return col.exportJSON(decrypted); })).then(function (cols) { json.collections = cols; return json; @@ -59,7 +59,7 @@ var importDumpRxDatabase = function importDumpRxDatabase(dump) { } return Promise.all(dump.collections.map(function (colDump) { - return _this2.collections[colDump.name].importDump(colDump); + return _this2.collections[colDump.name].importJSON(colDump); })); }; @@ -80,7 +80,7 @@ var dumpRxCollection = function dumpRxCollection() { } var query = createRxQuery('find', _getDefaultQuery(this), this); - return this._pouchFind(query, undefined, encrypted).then(function (docs) { + return this._queryStorageInstance(query, undefined, encrypted).then(function (docs) { json.docs = docs.map(function (docData) { delete docData._rev; delete docData._attachments; @@ -115,35 +115,29 @@ function importDumpRxCollection(exportedJSON) { }) // validate schema .map(function (doc) { return _this3.schema.validate(doc); - }) // transform - .map(function (doc) { - return _this3._handleToPouch(doc); }); var startTime; return this.database.lockedRun( // write to disc function () { startTime = now(); - return _this3.pouch.bulkDocs(docs); - }).then(function () { - var endTime = now(); - docs.forEach(function (doc) { - // emit change events - var emitEvent = createInsertEvent(_this3, doc, startTime, endTime); - - _this3.$emit(emitEvent); + var writeMe = docs.map(function (doc) { + return { + document: _handleToStorageInstance(_this3, doc) + }; }); + return _this3.storageInstance.bulkWrite(writeMe); }); } export var rxdb = true; export var prototypes = { RxDatabase: function RxDatabase(proto) { - proto.dump = dumpRxDatabase; - proto.importDump = importDumpRxDatabase; + proto.exportJSON = dumpRxDatabase; + proto.importJSON = importDumpRxDatabase; }, RxCollection: function RxCollection(proto) { - proto.dump = dumpRxCollection; - proto.importDump = importDumpRxCollection; + proto.exportJSON = dumpRxCollection; + proto.importJSON = importDumpRxCollection; } }; export var overwritable = {}; diff --git a/dist/es/plugins/key-compression.js b/dist/es/plugins/key-compression.js index 504b12b6403..7b5f81ce9f3 100644 --- a/dist/es/plugins/key-compression.js +++ b/dist/es/plugins/key-compression.js @@ -1,85 +1,125 @@ -import _createClass from "@babel/runtime/helpers/createClass"; - /** * this plugin adds the keycompression-capabilities to rxdb * if you dont use this, ensure that you set disableKeyComression to false in your schema */ -import { createCompressionTable, compressObject, decompressObject, compressedPath, compressQuery as _compressQuery, DEFAULT_COMPRESSION_FLAG } from 'jsonschema-key-compression'; -import { overwriteGetterForCaching } from '../util'; -export var KeyCompressor = /*#__PURE__*/function () { - function KeyCompressor(schema) { - this.schema = schema; - } - /** - * @overwrites itself on the first call - */ - - - var _proto = KeyCompressor.prototype; +import { createCompressionTable, compressObject, decompressObject, compressedPath, compressQuery, DEFAULT_COMPRESSION_FLAG, createCompressedJsonSchema } from 'jsonschema-key-compression'; +/** + * Cache the compression table and the compressed schema + * by the storage instance for better performance. + */ +var COMPRESSION_STATE_BY_COLLECTION = new WeakMap(); +export function createCompressionState(schema) { + var primaryPath = schema.primaryKey; + var table = createCompressionTable(schema, DEFAULT_COMPRESSION_FLAG, [ /** - * compress the keys of an object via the compression-table + * Do not compress the primary path + * to make it easier to debug errors. */ - _proto.compress = function compress(obj) { - if (!this.schema.doKeyCompression()) { - return obj; - } else { - return compressObject(this.table, obj); - } - }; - - _proto.decompress = function decompress(compressedObject) { - if (!this.schema.doKeyCompression()) { - return compressedObject; - } else { - return decompressObject(this.table, compressedObject); - } - } + primaryPath, '_rev', '_attachments', '_deleted']); + var compressedSchema = createCompressedJsonSchema(table, schema); /** - * get the full compressed-key-path of a object-path + * the key compression module does not know about indexes + * in the schema, so we have to also compress them here. */ - ; - _proto.transformKey = function transformKey(objectPath) { - return compressedPath(this.table, objectPath); // > '|a.|b' + if (schema.indexes) { + var newIndexes = schema.indexes.map(function (idx) { + if (Array.isArray(idx)) { + return idx.map(function (subIdx) { + return compressedPath(table, subIdx); + }); + } else { + return compressedPath(table, idx); + } + }); + compressedSchema.indexes = newIndexes; } - /** - * replace the keys of a query-obj with the compressed keys - * @return compressed queryJSON - */ - ; - _proto.compressQuery = function compressQuery(queryJSON) { - if (!this.schema.doKeyCompression()) { - return queryJSON; - } else { - return _compressQuery(this.table, queryJSON); - } + return { + table: table, + schema: compressedSchema }; +} +export function getCompressionStateByStorageInstance(collection) { + var state = COMPRESSION_STATE_BY_COLLECTION.get(collection); - _createClass(KeyCompressor, [{ - key: "table", - get: function get() { - var jsonSchema = this.schema.normalized; - var table = createCompressionTable(jsonSchema, DEFAULT_COMPRESSION_FLAG, [this.schema.primaryPath, '_rev', '_attachments']); - return overwriteGetterForCaching(this, 'table', table); - } - }]); + if (!state) { + state = createCompressionState(collection.schema.jsonSchema); + COMPRESSION_STATE_BY_COLLECTION.set(collection, state); + } - return KeyCompressor; -}(); -export function create(schema) { - return new KeyCompressor(schema); + return state; } export var rxdb = true; export var prototypes = {}; -export var overwritable = { - createKeyCompressor: create -}; +export var overwritable = {}; export var RxDBKeyCompressionPlugin = { name: 'key-compression', rxdb: rxdb, prototypes: prototypes, - overwritable: overwritable + overwritable: overwritable, + hooks: { + /** + * replace the keys of a query-obj with the compressed keys + * because the storage instance only know the compressed schema + * @return compressed queryJSON + */ + prePrepareQuery: function prePrepareQuery(input) { + var rxQuery = input.rxQuery; + var mangoQuery = input.mangoQuery; + + if (!rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var compressionState = getCompressionStateByStorageInstance(rxQuery.collection); + var compressedQuery = compressQuery(compressionState.table, mangoQuery); + input.mangoQuery = compressedQuery; + }, + preCreateRxStorageInstance: function preCreateRxStorageInstance(params) { + /** + * When key compression is used, + * the storage instance only knows about the compressed schema + */ + if (params.schema.keyCompression) { + var compressionState = createCompressionState(params.schema); + params.schema = compressionState.schema; + } + }, + preQueryMatcher: function preQueryMatcher(params) { + if (!params.rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.rxQuery.collection); + params.doc = compressObject(state.table, params.doc); + }, + preSortComparator: function preSortComparator(params) { + if (!params.rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.rxQuery.collection); + params.docA = compressObject(state.table, params.docA); + params.docB = compressObject(state.table, params.docB); + }, + preWriteToStorageInstance: function preWriteToStorageInstance(params) { + if (!params.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.collection); + params.doc = compressObject(state.table, params.doc); + }, + postReadFromInstance: function postReadFromInstance(params) { + if (!params.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.collection); + params.doc = decompressObject(state.table, params.doc); + } + } }; //# sourceMappingURL=key-compression.js.map \ No newline at end of file diff --git a/dist/es/plugins/local-documents.js b/dist/es/plugins/local-documents.js index 1698ec9babd..cfef9d15d17 100644 --- a/dist/es/plugins/local-documents.js +++ b/dist/es/plugins/local-documents.js @@ -1,21 +1,16 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; import _regeneratorRuntime from "@babel/runtime/regenerator"; - -/** - * This plugin adds the local-documents-support - * Local documents behave equal then with pouchdb - * @link https://pouchdb.com/guides/local-documents.html - */ import objectPath from 'object-path'; import { createRxDocumentConstructor, basePrototype } from '../rx-document'; -import { RxChangeEvent } from '../rx-change-event'; import { createDocCache } from '../doc-cache'; import { newRxError, newRxTypeError } from '../rx-error'; -import { clone, now, LOCAL_PREFIX } from '../util'; -import { isInstanceOf as isRxDatabase } from '../rx-database'; -import { isInstanceOf as isRxCollection } from '../rx-collection'; +import { flatClone, getFromMapOrThrow } from '../util'; +import { isRxDatabase } from '../rx-database'; +import { isRxCollection } from '../rx-collection'; import { filter, map, distinctUntilChanged, startWith, mergeMap } from 'rxjs/operators'; +import { findLocalDocument, writeSingleLocal } from '../rx-storage-helper'; +import { overwritable } from '../overwritable'; var DOC_CACHE_BY_PARENT = new WeakMap(); var _getDocCache = function _getDocCache(parent) { @@ -36,7 +31,10 @@ var _getChangeSub = function _getChangeSub(parent) { var docCache = _getDocCache(parent); var doc = docCache.get(cE.documentId); - if (doc) doc._handleChangeEvent(cE); + + if (doc) { + doc._handleChangeEvent(cE); + } }); parent._subs.push(sub); @@ -63,25 +61,19 @@ export var RxLocalDocument = /*#__PURE__*/function (_RxDocumentParent) { return RxLocalDocument; }(RxDocumentParent); -var _getPouchByParent = function _getPouchByParent(parent) { - if (isRxDatabase(parent)) return parent.internalStore; // database - else return parent.pouch; // collection -}; +function _getKeyObjectStorageInstanceByParent(parent) { + if (isRxDatabase(parent)) { + return parent.localDocumentsStore; // database + } else { + return parent.localDocumentsStore; // collection + } +} var RxLocalDocumentPrototype = { - toPouchJson: function toPouchJson() { - var data = clone(this._data); - data._id = LOCAL_PREFIX + this.id; - }, - get isLocal() { return true; }, - get parentPouch() { - return _getPouchByParent(this.parent); - }, - // // overwrites // @@ -92,9 +84,9 @@ var RxLocalDocumentPrototype = { switch (changeEvent.operation) { case 'UPDATE': - var newData = clone(changeEvent.documentData); + var newData = changeEvent.documentData; - this._dataSync$.next(clone(newData)); + this._dataSync$.next(newData); break; @@ -104,7 +96,7 @@ var RxLocalDocumentPrototype = { docCache["delete"](this.primary); - this._deleted$.next(true); + this._isDeleted$.next(true); break; } @@ -133,7 +125,9 @@ var RxLocalDocumentPrototype = { return this.parent.$emit(changeEvent); }, get: function get(objPath) { - if (!this._data) return undefined; + if (!this._data) { + return undefined; + } if (typeof objPath !== 'string') { throw newRxTypeError('LD2', { @@ -142,7 +136,7 @@ var RxLocalDocumentPrototype = { } var valueObj = objectPath.get(this._data, objPath); - valueObj = clone(valueObj); + valueObj = overwritable.deepFreezeWhenDevMode(valueObj); return valueObj; }, get$: function get$(path) { @@ -160,7 +154,7 @@ var RxLocalDocumentPrototype = { set: function set(objPath, value) { if (!value) { // object path not set, overwrite whole data - var data = clone(objPath); + var data = flatClone(objPath); data._rev = this._data._rev; this._data = data; return this; @@ -173,38 +167,47 @@ var RxLocalDocumentPrototype = { }); } - if (Object.is(this.get(objPath), value)) return; + if (Object.is(this.get(objPath), value)) { + return; + } + objectPath.set(this._data, objPath, value); return this; }, _saveData: function _saveData(newData) { - var _this2 = this; - var oldData = this._dataSync$.getValue(); - newData = clone(newData); - newData._id = LOCAL_PREFIX + this.id; - var startTime = now(); - return this.parentPouch.put(newData).then(function (res) { - var endTime = now(); - newData._rev = res.rev; - var changeEvent = new RxChangeEvent('UPDATE', _this2.id, clone(newData), isRxDatabase(_this2.parent) ? _this2.parent.token : _this2.parent.database.token, isRxCollection(_this2.parent) ? _this2.parent.name : null, true, startTime, endTime, oldData, _this2); + var storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); + + newData._id = this.id; + return storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }]).then(function (res) { + var docResult = res.success.get(newData._id); + + if (!docResult) { + throw getFromMapOrThrow(res.error, newData._id); + } - _this2.$emit(changeEvent); + newData._rev = docResult._rev; }); }, remove: function remove() { - var _this3 = this; - - var removeId = LOCAL_PREFIX + this.id; - var startTime = now(); - return this.parentPouch.remove(removeId, this._data._rev).then(function () { - _getDocCache(_this3.parent)["delete"](_this3.id); + var _this2 = this; - var endTime = now(); - var changeEvent = new RxChangeEvent('DELETE', _this3.id, clone(_this3._data), isRxDatabase(_this3.parent) ? _this3.parent.token : _this3.parent.database.token, isRxCollection(_this3.parent) ? _this3.parent.name : null, true, startTime, endTime, null, _this3); + var storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); - _this3.$emit(changeEvent); + var writeData = { + _id: this.id, + _deleted: true, + _attachments: {} + }; + return writeSingleLocal(storageInstance, { + previous: this._data, + document: writeData + }).then(function () { + _getDocCache(_this2.parent)["delete"](_this2.id); }); } }; @@ -257,36 +260,29 @@ RxLocalDocument.create = function (id, data, parent) { */ -function insertLocal(id, data) { - var _this4 = this; +function insertLocal(id, docData) { + var _this3 = this; if (isRxCollection(this) && this._isInMemory) { - return this._parentCollection.insertLocal(id, data); + return this.parentCollection.insertLocal(id, docData); } - data = clone(data); return this.getLocal(id).then(function (existing) { if (existing) { throw newRxError('LD7', { id: id, - data: data + data: docData }); } // create new one - var pouch = _getPouchByParent(_this4); - - var saveData = clone(data); - saveData._id = LOCAL_PREFIX + id; - var startTime = now(); - return pouch.put(saveData).then(function (res) { - data._rev = res.rev; - var newDoc = RxLocalDocument.create(id, data, _this4); - var endTime = now(); - var changeEvent = new RxChangeEvent('INSERT', id, clone(data), isRxDatabase(_this4) ? _this4.token : _this4.database.token, isRxCollection(_this4) ? _this4.name : '', true, startTime, endTime, undefined, newDoc); - - _this4.$emit(changeEvent); - + docData = flatClone(docData); + docData._id = id; + return writeSingleLocal(_getKeyObjectStorageInstanceByParent(_this3), { + document: docData + }).then(function (res) { + docData._rev = res._rev; + var newDoc = RxLocalDocument.create(id, docData, _this3); return newDoc; }); }); @@ -298,7 +294,7 @@ function insertLocal(id, data) { function upsertLocal(id, data) { - var _this5 = this; + var _this4 = this; if (isRxCollection(this) && this._isInMemory) { return this._parentCollection.upsertLocal(id, data); @@ -307,7 +303,7 @@ function upsertLocal(id, data) { return this.getLocal(id).then(function (existing) { if (!existing) { // create new one - var docPromise = _this5.insertLocal(id, data); + var docPromise = _this4.insertLocal(id, data); return docPromise; } else { @@ -323,21 +319,30 @@ function upsertLocal(id, data) { } function getLocal(id) { - var _this6 = this; + var _this5 = this; - if (isRxCollection(this) && this._isInMemory) return this._parentCollection.getLocal(id); + if (isRxCollection(this) && this._isInMemory) { + return this.parentCollection.getLocal(id); + } - var pouch = _getPouchByParent(this); + var storageInstance = _getKeyObjectStorageInstanceByParent(this); var docCache = _getDocCache(this); // check in doc-cache var found = docCache.get(id); - if (found) return Promise.resolve(found); // if not found, check in pouch - return pouch.get(LOCAL_PREFIX + id).then(function (docData) { - if (!docData) return null; - var doc = RxLocalDocument.create(id, docData, _this6); + if (found) { + return Promise.resolve(found); + } // if not found, check in storage instance + + + return findLocalDocument(storageInstance, id).then(function (docData) { + if (!docData) { + return null; + } + + var doc = RxLocalDocument.create(id, docData, _this5); return doc; })["catch"](function () { return null; @@ -345,7 +350,7 @@ function getLocal(id) { } function getLocal$(id) { - var _this7 = this; + var _this6 = this; return this.$.pipe(startWith(null), mergeMap( /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(cE) { @@ -365,7 +370,7 @@ function getLocal$(id) { case 4: _context.next = 6; - return _this7.getLocal(id); + return _this6.getLocal(id); case 6: doc = _context.sent; @@ -392,7 +397,7 @@ function getLocal$(id) { switch (_context2.prev = _context2.next) { case 0: if (!changeEventOrDoc.changeEvent) { - _context2.next = 17; + _context2.next = 12; break; } @@ -408,40 +413,27 @@ function getLocal$(id) { }); case 6: - if (!cE.rxDocument) { - _context2.next = 10; - break; - } - - _context2.t0 = cE.rxDocument; - _context2.next = 13; - break; - - case 10: - _context2.next = 12; - return _this7.getLocal(id); - - case 12: - _context2.t0 = _context2.sent; + _context2.next = 8; + return _this6.getLocal(id); - case 13: - doc = _context2.t0; + case 8: + doc = _context2.sent; return _context2.abrupt("return", { use: true, doc: doc }); - case 15: - _context2.next = 18; + case 10: + _context2.next = 13; break; - case 17: + case 12: return _context2.abrupt("return", { use: true, doc: changeEventOrDoc.doc }); - case 18: + case 13: case "end": return _context2.stop(); } @@ -459,26 +451,23 @@ function getLocal$(id) { })); } -export var rxdb = true; -export var prototypes = { - RxCollection: function RxCollection(proto) { - proto.insertLocal = insertLocal; - proto.upsertLocal = upsertLocal; - proto.getLocal = getLocal; - proto.getLocal$ = getLocal$; - }, - RxDatabase: function RxDatabase(proto) { - proto.insertLocal = insertLocal; - proto.upsertLocal = upsertLocal; - proto.getLocal = getLocal; - proto.getLocal$ = getLocal$; - } -}; -export var overwritable = {}; export var RxDBLocalDocumentsPlugin = { name: 'local-documents', - rxdb: rxdb, - prototypes: prototypes, - overwritable: overwritable + rxdb: true, + prototypes: { + RxCollection: function RxCollection(proto) { + proto.insertLocal = insertLocal; + proto.upsertLocal = upsertLocal; + proto.getLocal = getLocal; + proto.getLocal$ = getLocal$; + }, + RxDatabase: function RxDatabase(proto) { + proto.insertLocal = insertLocal; + proto.upsertLocal = upsertLocal; + proto.getLocal = getLocal; + proto.getLocal$ = getLocal$; + } + }, + overwritable: {} }; //# sourceMappingURL=local-documents.js.map \ No newline at end of file diff --git a/dist/es/plugins/migration/data-migrator.js b/dist/es/plugins/migration/data-migrator.js index 00ed1635504..7de10da8f2d 100644 --- a/dist/es/plugins/migration/data-migrator.js +++ b/dist/es/plugins/migration/data-migrator.js @@ -1,3 +1,6 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; + /** * The DataMigrator handles the documents from collections with older schemas * and transforms/saves them into the newest collection @@ -5,23 +8,22 @@ /** * TODO this should be completely rewritten because: - * - The current implemetation does not use pouchdb'S bulkDocs which is much faster + * - The current implemetation does not use bulkDocs which is much faster * - This could have been done in much less code which would be easier to uderstand * */ import { Subject } from 'rxjs'; import deepEqual from 'deep-equal'; -import { countAllUndeleted, getBatch } from '../../pouch-db'; import { clone, toPromise, flatClone, getHeightOfRevision, createRevision } from '../../util'; import { createRxSchema } from '../../rx-schema'; import { newRxError } from '../../rx-error'; -import { overwritable } from '../../overwritable'; import { runAsyncPluginHooks } from '../../hooks'; import { getPreviousVersions } from '../../rx-schema'; import { createCrypter } from '../../crypter'; -import { _handleToPouch, _handleFromPouch } from '../../rx-collection-helper'; import { getMigrationStateByDatabase } from './migration-state'; import { map } from 'rxjs/operators'; +import { countAllUndeleted, getBatch, getSingleDocument } from '../../rx-storage-helper'; +import { _handleFromStorageInstance, _handleToStorageInstance } from '../../rx-collection-helper'; export var DataMigrator = /*#__PURE__*/function () { function DataMigrator(newestCollection, migrationStrategies) { this._migrated = false; @@ -71,6 +73,8 @@ export var DataMigrator = /*#__PURE__*/function () { * TODO this is a side-effect which might throw * We did this because it is not possible to create new Observer(async(...)) * @link https://github.com/ReactiveX/rxjs/issues/4074 + * In the future the whole migration plugin should be rewritten without rxjs + * so we do not have this problem. */ (function () { @@ -78,7 +82,7 @@ export var DataMigrator = /*#__PURE__*/function () { return _getOldCollections(_this).then(function (ret) { oldCols = ret; var countAll = Promise.all(oldCols.map(function (oldCol) { - return countAllUndeleted(oldCol.pouchdb); + return countAllUndeleted(oldCol.storageInstance); })); return countAll; }).then(function (countAll) { @@ -156,49 +160,100 @@ export var DataMigrator = /*#__PURE__*/function () { return DataMigrator; }(); -export function createOldCollection(version, schemaObj, dataMigrator) { - var database = dataMigrator.newestCollection.database; - var schema = createRxSchema(schemaObj, false); - var ret = { - version: version, - dataMigrator: dataMigrator, - newestCollection: dataMigrator.newestCollection, - database: database, - schema: createRxSchema(schemaObj, false), - pouchdb: database._spawnPouchDB(dataMigrator.newestCollection.name, version, dataMigrator.newestCollection.pouchSettings), - _crypter: createCrypter(database.password, schema) - }; - - if (schema.doKeyCompression()) { - ret._keyCompressor = overwritable.createKeyCompressor(schema); - } - - return ret; +export function createOldCollection(_x, _x2, _x3) { + return _createOldCollection.apply(this, arguments); } /** - * get an array with OldCollection-instances from all existing old pouchdb-instance + * get an array with OldCollection-instances from all existing old storage-instances */ -export function _getOldCollections(dataMigrator) { - return Promise.all(getPreviousVersions(dataMigrator.currentSchema.jsonSchema).map(function (v) { - return dataMigrator.database.internalStore.get(dataMigrator.name + '-' + v); - }).map(function (fun) { - return fun["catch"](function () { - return null; - }); - }) // auto-catch so Promise.all continues - ).then(function (oldColDocs) { - return oldColDocs.filter(function (colDoc) { - return colDoc !== null; - }).map(function (colDoc) { - return createOldCollection(colDoc.schema.version, colDoc.schema, dataMigrator); - }); - }); +function _createOldCollection() { + _createOldCollection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(version, schemaObj, dataMigrator) { + var database, schema, storageInstanceCreationParams, storageInstance, ret; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + database = dataMigrator.newestCollection.database; + schema = createRxSchema(schemaObj, false); + storageInstanceCreationParams = { + databaseName: database.name, + collectionName: dataMigrator.newestCollection.name, + schema: schemaObj, + options: dataMigrator.newestCollection.instanceCreationOptions + }; + _context.next = 5; + return database.storage.createStorageInstance(storageInstanceCreationParams); + + case 5: + storageInstance = _context.sent; + ret = { + version: version, + dataMigrator: dataMigrator, + newestCollection: dataMigrator.newestCollection, + database: database, + schema: createRxSchema(schemaObj, false), + storageInstance: storageInstance, + _crypter: createCrypter(database.password, schema) + }; + return _context.abrupt("return", ret); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _createOldCollection.apply(this, arguments); +} + +export function _getOldCollections(_x4) { + return _getOldCollections2.apply(this, arguments); } /** * returns true if a migration is needed */ +function _getOldCollections2() { + _getOldCollections2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(dataMigrator) { + var oldColDocs; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all(getPreviousVersions(dataMigrator.currentSchema.jsonSchema).map(function (v) { + return getSingleDocument(dataMigrator.database.internalStore, dataMigrator.name + '-' + v); + }).map(function (fun) { + return fun["catch"](function () { + return null; + }); + }) // auto-catch so Promise.all continues + ); + + case 2: + oldColDocs = _context2.sent; + return _context2.abrupt("return", Promise.all(oldColDocs.map(function (colDoc) { + if (!colDoc) { + return null; + } + + return createOldCollection(colDoc.schema.version, colDoc.schema, dataMigrator); + }).filter(function (colDoc) { + return colDoc !== null; + }))); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _getOldCollections2.apply(this, arguments); +} + export function mustMigrate(dataMigrator) { if (dataMigrator.currentSchema.version === 0) { return Promise.resolve(false); @@ -221,9 +276,11 @@ export function runStrategyIfNotNull(oldCollection, version, docOrNull) { } } export function getBatchOfOldCollection(oldCollection, batchSize) { - return getBatch(oldCollection.pouchdb, batchSize).then(function (docs) { + return getBatch(oldCollection.storageInstance, batchSize).then(function (docs) { return docs.map(function (doc) { - return _handleFromPouch(oldCollection, doc); + doc = flatClone(doc); + doc = _handleFromStorageInstance(oldCollection, doc); + return doc; }); }); } @@ -260,7 +317,10 @@ export function migrateDocumentData(oldCollection, docData) { } return currentPromise.then(function (doc) { - if (doc === null) return Promise.resolve(null); // check final schema + if (doc === null) { + return Promise.resolve(null); + } // check final schema + try { oldCollection.newestCollection.schema.validate(doc); @@ -346,16 +406,17 @@ export function _migrateDocument(oldCollection, docData) { */ var attachmentsBefore = migrated._attachments; - var saveData = oldCollection.newestCollection._handleToPouch(migrated); + var saveData = _handleToStorageInstance(oldCollection.newestCollection, migrated); saveData._attachments = attachmentsBefore; - return oldCollection.newestCollection.pouch.bulkDocs([saveData], { - /** - * We need new_edits: false - * because we provide the _rev by our own - */ - new_edits: false - }).then(function () { + /** + * We need to add as revision + * because we provide the _rev by our own + * to have deterministic revisions in case the migration + * runs on multiple nodes which must lead to the equal storage state. + */ + + return oldCollection.newestCollection.storageInstance.bulkAddRevisions([saveData]).then(function () { action.res = saveData; action.type = 'success'; return runAsyncPluginHooks('postMigrateDocument', action); @@ -368,24 +429,29 @@ export function _migrateDocument(oldCollection, docData) { */ action.type = 'deleted'; } - }).then(function () { - // remove from old collection - return oldCollection.pouchdb.remove(_handleToPouch(oldCollection, docData))["catch"](function () {}); + }) // remove the migrated document from the old collection + .then(function () { + var writeDeleted = flatClone(docData); + writeDeleted._deleted = true; + return oldCollection.storageInstance.bulkWrite([{ + previous: _handleToStorageInstance(oldCollection, docData), + document: _handleToStorageInstance(oldCollection, writeDeleted) + }]); }).then(function () { return action; }); } /** - * deletes this.pouchdb and removes it from the database.collectionsCollection + * deletes this.storageInstance and removes it from the database.collectionsCollection */ export function deleteOldCollection(oldCollection) { - return oldCollection.pouchdb.destroy().then(function () { + return oldCollection.storageInstance.remove().then(function () { return oldCollection.database.removeCollectionDoc(oldCollection.dataMigrator.name, oldCollection.schema); }); } /** - * runs the migration on all documents and deletes the pouchdb afterwards + * runs the migration on all documents and deletes the storage instance afterwards */ export function migrateOldCollection(oldCollection) { diff --git a/dist/es/plugins/adapter-check.js b/dist/es/plugins/pouchdb/adapter-check.js similarity index 81% rename from dist/es/plugins/adapter-check.js rename to dist/es/plugins/pouchdb/adapter-check.js index 1e61537f698..21ff2e3e1cf 100644 --- a/dist/es/plugins/adapter-check.js +++ b/dist/es/plugins/pouchdb/adapter-check.js @@ -2,8 +2,8 @@ * this plugin adds the checkAdapter-function to rxdb * you can use it to check if the given adapter is working in the current environmet */ -import { PouchDB } from '../pouch-db'; -import { generateId, adapterObject } from '../util'; +import { PouchDB } from './pouch-db'; +import { adapterObject, randomCouchString } from '../../util'; /** * The same pouchdb-location is used on each run @@ -13,7 +13,7 @@ import { generateId, adapterObject } from '../util'; export var POUCHDB_LOCATION = 'rxdb-adapter-check'; export function checkAdapter(adapter) { // id of the document which is stored and removed to ensure everything works - var _id = POUCHDB_LOCATION + '-' + generateId(); + var _id = POUCHDB_LOCATION + '-' + randomCouchString(12); var pouch; @@ -61,15 +61,4 @@ export function checkAdapter(adapter) { * calling destroy would possibly crash the other call */ } -export var rxdb = true; -export var prototypes = {}; -export var overwritable = { - checkAdapter: checkAdapter -}; -export var RxDBAdapterCheckPlugin = { - name: 'adapter-check', - rxdb: rxdb, - prototypes: prototypes, - overwritable: overwritable -}; //# sourceMappingURL=adapter-check.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/custom-events-plugin.js b/dist/es/plugins/pouchdb/custom-events-plugin.js new file mode 100644 index 00000000000..79ffec67acd --- /dev/null +++ b/dist/es/plugins/pouchdb/custom-events-plugin.js @@ -0,0 +1,238 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; + +/* + * Instead of listening to pouch.changes, + * we overwrite pouchdbs bulkDocs() + * and create our own event stream, this will work more reliable + * and has less strange behaviors. + * Also we can better define what data we need for our events. + * @link http://jsbin.com/pagebi/1/edit?js,output + * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273 + */ +import PouchDBCore from 'pouchdb-core'; +import { Subject } from 'rxjs'; +import { flatClone, now } from '../../util'; +import { newRxError } from '../../rx-error'; +import { ObliviousSet } from 'oblivious-set'; // ensure only added once + +var addedToPouch = false; +export var EVENT_EMITTER_BY_POUCH_INSTANCE = new Map(); +export function getCustomEventEmitterByPouch(pouch) { + var key = [pouch.name, pouch.adapter].join('|'); + var emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key); + + if (!emitter) { + emitter = { + subject: new Subject(), + obliviousSet: new ObliviousSet(60 * 1000) + }; + EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter); + } + + return emitter; +} +var i = 0; +export function addCustomEventsPluginToPouch() { + if (addedToPouch) { + return; + } + + addedToPouch = true; + var oldBulkDocs = PouchDBCore.prototype.bulkDocs; + + var newBulkDocs = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(body, options, callback) { + var _this = this; + + var startTime, t, docs, previousDocs, ids, viaChanges, previousDocsResult, deeperOptions; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + startTime = now(); + t = i++; // normalize input + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (!options) { + options = {}; + } + + if (Array.isArray(body)) { + docs = body; + } else if (body === undefined) { + docs = []; + } else { + docs = body.docs; + + if (body.hasOwnProperty('new_edits')) { + options.new_edits = body.new_edits; + } + } + + if (!(docs.length === 0)) { + _context2.next = 7; + break; + } + + throw newRxError('SNH', { + args: { + body: body, + options: options + } + }); + + case 7: + /** + * If new_edits=false we have to first find the current state + * of the document and can later check if the state was changed + * because a new revision was written and we have to emit an event. + */ + previousDocs = new Map(); + + if (!(options.hasOwnProperty('new_edits') && options.new_edits === false)) { + _context2.next = 18; + break; + } + + ids = docs.map(function (doc) { + return doc._id; + }); + /** + * Pouchdb does not return deleted documents via allDocs() + * So have to do use our hack with getting the newest revisions from the + * changes. + */ + + _context2.next = 12; + return this.changes({ + live: false, + since: 0, + doc_ids: ids, + style: 'all_docs' + }); + + case 12: + viaChanges = _context2.sent; + _context2.next = 15; + return Promise.all(viaChanges.results.map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(result) { + var firstDoc; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.get(result.id, { + rev: result.changes[0].rev, + deleted: 'ok', + revs: options.set_new_edit_as_latest_revision ? true : false, + style: 'all_docs' + }); + + case 2: + firstDoc = _context.sent; + return _context.abrupt("return", firstDoc); + + case 4: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }())); + + case 15: + previousDocsResult = _context2.sent; + previousDocsResult.forEach(function (doc) { + return previousDocs.set(doc._id, doc); + }); + + if (options.set_new_edit_as_latest_revision) { + docs.forEach(function (doc) { + var id = doc._id; + var previous = previousDocs.get(id); + + if (previous) { + var splittedRev = doc._rev.split('-'); + + var revHeight = parseInt(splittedRev[0], 10); + var revLabel = splittedRev[1]; + doc._revisions = { + start: revHeight, + ids: previous._revisions.ids + }; + + doc._revisions.ids.unshift(revLabel); + + delete previous._revisions; + } + }); + } + + case 18: + /** + * pouchdb calls this function again with transformed input. + * This would lead to duplicate events. So we marks the deeper calls via the options + * parameter and do not emit events if it is set. + */ + deeperOptions = flatClone(options); + deeperOptions.isDeeper = true; + return _context2.abrupt("return", oldBulkDocs.call(this, docs, deeperOptions, function (err, result) { + if (err) { + if (callback) { + callback(err); + } else { + throw err; + } + } else { + if (!options.isDeeper) { + var endTime = now(); + var emitData = { + emitId: t, + writeDocs: docs, + writeOptions: options, + writeResult: result, + previousDocs: previousDocs, + startTime: startTime, + endTime: endTime + }; + var emitter = getCustomEventEmitterByPouch(_this); + emitter.subject.next(emitData); + } + + if (callback) { + callback(null, result); + } else { + return result; + } + } + })); + + case 21: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function newBulkDocs(_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; + }(); + + PouchDBCore.plugin({ + bulkDocs: newBulkDocs + }); +} +//# sourceMappingURL=custom-events-plugin.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/index.js b/dist/es/plugins/pouchdb/index.js new file mode 100644 index 00000000000..19dd50206e9 --- /dev/null +++ b/dist/es/plugins/pouchdb/index.js @@ -0,0 +1,5 @@ +export * from './pouch-db'; +export * from './rx-storage-pouchdb'; +export * from './adapter-check'; +export * from './custom-events-plugin'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/pouch-db.js b/dist/es/plugins/pouchdb/pouch-db.js new file mode 100644 index 00000000000..bbb103bcf4c --- /dev/null +++ b/dist/es/plugins/pouchdb/pouch-db.js @@ -0,0 +1,81 @@ +/** + * this handles the pouchdb-instance + * to easy add modules and manipulate things + * Adapters can be found here: + * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules + */ +import PouchDBCore from 'pouchdb-core'; // pouchdb-find + +import PouchDBFind from 'pouchdb-find'; +/* +// comment in to debug +const pouchdbDebug = require('pouchdb-debug'); +PouchDB.plugin(pouchdbDebug); +PouchDB.debug.enable('*'); +*/ +// TODO we can delete most of these functions in the file because it was migrated to rx-storage-pouchdb + +import { newRxError, newRxTypeError } from '../../rx-error'; +import { addCustomEventsPluginToPouch } from './custom-events-plugin'; +addPouchPlugin(PouchDBFind); +addCustomEventsPluginToPouch(); +/** + * check if the given module is a leveldown-adapter + * throws if not + */ + +export function isLevelDown(adapter) { + if (!adapter || typeof adapter.super_ !== 'function') { + throw newRxError('UT4', { + adapter: adapter + }); + } +} +/** + * get the correct function-name for pouchdb-replication + */ + +export function pouchReplicationFunction(pouch, _ref) { + var _ref$pull = _ref.pull, + pull = _ref$pull === void 0 ? true : _ref$pull, + _ref$push = _ref.push, + push = _ref$push === void 0 ? true : _ref$push; + if (pull && push) return pouch.sync.bind(pouch); + if (!pull && push) return pouch.replicate.to.bind(pouch); + if (pull && !push) return pouch.replicate.from.bind(pouch); + + if (!pull && !push) { + throw newRxError('UT3', { + pull: pull, + push: push + }); + } +} +export function isInstanceOf(obj) { + return obj instanceof PouchDBCore; +} +/** + * Add a pouchdb plugin to the pouchdb library. + */ + +export function addPouchPlugin(plugin) { + if (plugin.rxdb) { + throw newRxTypeError('PL2', { + plugin: plugin + }); + } + /** + * Pouchdb has confusing typings and modules. + * So we monkeypatch the plugin to use the default property + * when it was imported or packaged this way. + */ + + + if (typeof plugin === 'object' && plugin["default"]) { + plugin = plugin["default"]; + } + + PouchDBCore.plugin(plugin); +} +export var PouchDB = PouchDBCore; +//# sourceMappingURL=pouch-db.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/rx-storage-pouchdb.js b/dist/es/plugins/pouchdb/rx-storage-pouchdb.js new file mode 100644 index 00000000000..3419ab1c08d --- /dev/null +++ b/dist/es/plugins/pouchdb/rx-storage-pouchdb.js @@ -0,0 +1,1797 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { filterInMemoryFields, massageSelector } from 'pouchdb-selector-core'; +import { binaryMd5 } from 'pouchdb-md5'; +import { flatClone, adapterObject, getFromMapOrThrow, getHeightOfRevision, promiseWait, blobBufferUtil, now } from '../../util'; +import { isLevelDown, PouchDB } from './pouch-db'; +import { newRxError } from '../../rx-error'; +import { Subject } from 'rxjs'; +import { getSchemaByObjectPath } from '../../rx-schema-helper'; +import { getCustomEventEmitterByPouch } from './custom-events-plugin'; +/** + * prefix of local pouchdb documents + */ + +export var POUCHDB_LOCAL_PREFIX = '_local/'; +/** + * Pouchdb stores indexes as design documents, + * we have to filter them out and not return the + * design documents to the outside. + */ + +export var POUCHDB_DESIGN_PREFIX = '_design/'; + +/** + * Used to check in tests if all instances have been cleaned up. + */ +export var OPEN_POUCHDB_STORAGE_INSTANCES = new Set(); +export var RxStorageKeyObjectInstancePouch = /*#__PURE__*/function () { + function RxStorageKeyObjectInstancePouch(databaseName, collectionName, internals, options) { + this.changes$ = new Subject(); + this.databaseName = databaseName; + this.collectionName = collectionName; + this.internals = internals; + this.options = options; + OPEN_POUCHDB_STORAGE_INSTANCES.add(this); + } + + var _proto = RxStorageKeyObjectInstancePouch.prototype; + + _proto.close = function close() { + OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); // TODO this did not work because a closed pouchdb cannot be recreated in the same process run + // await this.internals.pouch.close(); + + return Promise.resolve(); + }; + + _proto.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.internals.pouch.destroy(); + + case 2: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function remove() { + return _remove.apply(this, arguments); + } + + return remove; + }(); + + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(documentWrites) { + var _this = this; + + var writeRowById, insertDocs, startTime, pouchResult, endTime, ret; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + writeRowById = new Map(); + insertDocs = documentWrites.map(function (writeRow) { + writeRowById.set(writeRow.document._id, writeRow); + var storeDocumentData = flatClone(writeRow.document); + /** + * add local prefix + * Local documents always have _id as primary + */ + + storeDocumentData._id = POUCHDB_LOCAL_PREFIX + storeDocumentData._id; // if previous document exists, we have to send the previous revision to pouchdb. + + if (writeRow.previous) { + storeDocumentData._rev = writeRow.previous._rev; + } + + return storeDocumentData; + }); + startTime = now(); + _context2.next = 5; + return this.internals.pouch.bulkDocs(insertDocs); + + case 5: + pouchResult = _context2.sent; + endTime = now(); + ret = { + success: new Map(), + error: new Map() + }; + pouchResult.forEach(function (resultRow) { + resultRow.id = pouchStripLocalFlagFromPrimary(resultRow.id); + var writeRow = getFromMapOrThrow(writeRowById, resultRow.id); + + if (resultRow.error) { + var err = { + isError: true, + status: 409, + documentId: resultRow.id, + writeRow: writeRow + }; + ret.error.set(resultRow.id, err); + } else { + var pushObj = flatClone(writeRow.document); + pushObj._rev = resultRow.rev; // local document cannot have attachments + + pushObj._attachments = {}; + ret.success.set(resultRow.id, pushObj); + /** + * Emit a write event to the changestream. + * We do this here and not by observing the internal pouchdb changes + * because here we have the previous document data and do + * not have to fill previous with 'UNKNOWN'. + */ + + var event; + + if (!writeRow.previous) { + // was insert + event = { + operation: 'INSERT', + doc: pushObj, + id: resultRow.id, + previous: null + }; + } else if (writeRow.document._deleted) { + // was delete + // we need to add the new revision to the previous doc + // so that the eventkey is calculated correctly. + // Is this a hack? idk. + var previousDoc = flatClone(writeRow.previous); + previousDoc._rev = resultRow.rev; + event = { + operation: 'DELETE', + doc: null, + id: resultRow.id, + previous: previousDoc + }; + } else { + // was update + event = { + operation: 'UPDATE', + doc: pushObj, + id: resultRow.id, + previous: writeRow.previous + }; + } + + if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) { + /** + * A deleted document was newly added to the storage engine, + * do not emit an event. + */ + } else { + var doc = event.operation === 'DELETE' ? event.previous : event.doc; + var eventId = getEventKey(true, doc._id, doc._rev ? doc._rev : ''); + var storageChangeEvent = { + eventId: eventId, + documentId: resultRow.id, + change: event, + startTime: startTime, + endTime: endTime + }; + + _this.changes$.next(storageChangeEvent); + } + } + }); + return _context2.abrupt("return", ret); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function bulkWrite(_x) { + return _bulkWrite.apply(this, arguments); + } + + return bulkWrite; + }(); + + _proto.findLocalDocumentsById = /*#__PURE__*/function () { + var _findLocalDocumentsById = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(ids) { + var _this2 = this; + + var ret; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + ret = new Map(); + /** + * Pouchdb is not able to bulk-request local documents + * with the pouch.allDocs() method. + * so we need to get each by a single call. + * TODO create an issue at the pouchdb repo + */ + + _context4.next = 3; + return Promise.all(ids.map( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(id) { + var prefixedId, docData; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + prefixedId = POUCHDB_LOCAL_PREFIX + id; + _context3.prev = 1; + _context3.next = 4; + return _this2.internals.pouch.get(prefixedId); + + case 4: + docData = _context3.sent; + docData._id = id; + ret.set(id, docData); + _context3.next = 11; + break; + + case 9: + _context3.prev = 9; + _context3.t0 = _context3["catch"](1); + + case 11: + case "end": + return _context3.stop(); + } + } + }, _callee3, null, [[1, 9]]); + })); + + return function (_x3) { + return _ref.apply(this, arguments); + }; + }())); + + case 3: + return _context4.abrupt("return", ret); + + case 4: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + + function findLocalDocumentsById(_x2) { + return _findLocalDocumentsById.apply(this, arguments); + } + + return findLocalDocumentsById; + }(); + + _proto.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + + return RxStorageKeyObjectInstancePouch; +}(); +export var RxStorageInstancePouch = /*#__PURE__*/function () { + function RxStorageInstancePouch(databaseName, collectionName, schema, internals, options) { + var _this3 = this; + + this.changes$ = new Subject(); + this.subs = []; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + OPEN_POUCHDB_STORAGE_INSTANCES.add(this); + /** + * Instead of listening to pouch.changes, + * we have overwritten pouchdbs bulkDocs() + * and create our own event stream, this will work more relyable + * and does not mix up with write events from other sources. + */ + + var emitter = getCustomEventEmitterByPouch(this.internals.pouch); + this.emittedEventIds = emitter.obliviousSet; + var eventSub = emitter.subject.subscribe( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(ev) { + var writeDocsById, writeMap; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + if (!(ev.writeOptions.hasOwnProperty('new_edits') && !ev.writeOptions.new_edits)) { + _context8.next = 4; + break; + } + + _context8.next = 3; + return Promise.all(ev.writeDocs.map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(writeDoc) { + var id, previousDoc, event; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + id = writeDoc._id; + writeDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeDoc); + _context5.next = 4; + return writeAttachmentsToAttachments(writeDoc._attachments); + + case 4: + writeDoc._attachments = _context5.sent; + previousDoc = ev.previousDocs.get(id); + + if (previousDoc) { + previousDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, previousDoc); + } + + if (!(previousDoc && getHeightOfRevision(previousDoc._rev) > getHeightOfRevision(writeDoc._rev))) { + _context5.next = 9; + break; + } + + return _context5.abrupt("return"); + + case 9: + if (!(!previousDoc && writeDoc._deleted)) { + _context5.next = 11; + break; + } + + return _context5.abrupt("return"); + + case 11: + if (!(previousDoc && previousDoc._deleted && writeDoc._deleted)) { + _context5.next = 13; + break; + } + + return _context5.abrupt("return"); + + case 13: + if (!(!previousDoc && !writeDoc._deleted)) { + _context5.next = 17; + break; + } + + // was insert + event = { + operation: 'INSERT', + doc: writeDoc, + id: id, + previous: null + }; + _context5.next = 27; + break; + + case 17: + if (!(writeDoc._deleted && previousDoc && !previousDoc._deleted)) { + _context5.next = 22; + break; + } + + // was delete + previousDoc._rev = writeDoc._rev; + event = { + operation: 'DELETE', + doc: null, + id: id, + previous: previousDoc + }; + _context5.next = 27; + break; + + case 22: + if (!previousDoc) { + _context5.next = 26; + break; + } + + // was update + event = { + operation: 'UPDATE', + doc: writeDoc, + id: id, + previous: previousDoc + }; + _context5.next = 27; + break; + + case 26: + throw newRxError('SNH', { + args: { + writeDoc: writeDoc + } + }); + + case 27: + _this3.addEventToChangeStream(event, ev.startTime, ev.endTime); + + case 28: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + + return function (_x5) { + return _ref3.apply(this, arguments); + }; + }())); + + case 3: + return _context8.abrupt("return"); + + case 4: + if (ev.writeOptions.custom) { + _context8.next = 10; + break; + } + + writeDocsById = new Map(); + ev.writeDocs.forEach(function (writeDoc) { + return writeDocsById.set(writeDoc._id, writeDoc); + }); + _context8.next = 9; + return Promise.all(ev.writeResult.map( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(resultRow) { + var id, writeDoc, event; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + id = resultRow.id; + + if (!(id.startsWith(POUCHDB_DESIGN_PREFIX) || id.startsWith(POUCHDB_LOCAL_PREFIX))) { + _context6.next = 3; + break; + } + + return _context6.abrupt("return"); + + case 3: + writeDoc = getFromMapOrThrow(writeDocsById, resultRow.id); + _context6.next = 6; + return writeAttachmentsToAttachments(writeDoc._attachments); + + case 6: + writeDoc._attachments = _context6.sent; + event = pouchChangeRowToChangeEvent(_this3.schema.primaryKey, writeDoc); + + _this3.addEventToChangeStream(event); + + case 9: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + + return function (_x6) { + return _ref4.apply(this, arguments); + }; + }())); + + case 9: + return _context8.abrupt("return"); + + case 10: + writeMap = ev.writeOptions.custom.writeRowById; + _context8.next = 13; + return Promise.all(ev.writeResult.map( /*#__PURE__*/function () { + var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(resultRow) { + var id, writeRow, newDoc, event, previousDoc; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + if (!resultRow.error) { + _context7.next = 2; + break; + } + + return _context7.abrupt("return"); + + case 2: + id = resultRow.id; + writeRow = getFromMapOrThrow(writeMap, id); + newDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeRow.document); + _context7.next = 7; + return writeAttachmentsToAttachments(newDoc._attachments); + + case 7: + newDoc._attachments = _context7.sent; + newDoc._rev = resultRow.rev; + + if (writeRow.previous) { + _context7.next = 13; + break; + } + + // was insert + event = { + operation: 'INSERT', + doc: newDoc, + id: id, + previous: null + }; + _context7.next = 23; + break; + + case 13: + if (!writeRow.document._deleted) { + _context7.next = 22; + break; + } + + // was delete + // we need to add the new revision to the previous doc + // so that the eventkey is calculated correctly. + // Is this a hack? idk. + previousDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeRow.previous); + _context7.next = 17; + return writeAttachmentsToAttachments(previousDoc._attachments); + + case 17: + previousDoc._attachments = _context7.sent; + previousDoc._rev = resultRow.rev; + event = { + operation: 'DELETE', + doc: null, + id: resultRow.id, + previous: previousDoc + }; + _context7.next = 23; + break; + + case 22: + // was update + event = { + operation: 'UPDATE', + doc: newDoc, + id: resultRow.id, + previous: writeRow.previous + }; + + case 23: + if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) { + /** + * A deleted document was newly added to the storage engine, + * do not emit an event. + */ + } else { + _this3.addEventToChangeStream(event, ev.startTime, ev.endTime); + } + + case 24: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + + return function (_x7) { + return _ref5.apply(this, arguments); + }; + }())); + + case 13: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }()); + this.subs.push(eventSub); + } + + var _proto2 = RxStorageInstancePouch.prototype; + + _proto2.addEventToChangeStream = function addEventToChangeStream(change, startTime, endTime) { + var doc = change.operation === 'DELETE' ? change.previous : change.doc; + var primaryKey = this.schema.primaryKey; + var primary = doc[primaryKey]; + var eventId = getEventKey(false, primary, doc._rev); + + if (this.emittedEventIds.has(eventId)) { + return; + } + + this.emittedEventIds.add(eventId); + var storageChangeEvent = { + eventId: eventId, + documentId: primary, + change: change, + startTime: startTime, + endTime: endTime + }; + this.changes$.next(storageChangeEvent); + }; + + _proto2.close = function close() { + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); // TODO this did not work because a closed pouchdb cannot be recreated in the same process run + // await this.internals.pouch.close(); + + return Promise.resolve(); + }; + + _proto2.remove = /*#__PURE__*/function () { + var _remove2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9() { + return _regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return this.internals.pouch.destroy(); + + case 2: + case "end": + return _context9.stop(); + } + } + }, _callee9, this); + })); + + function remove() { + return _remove2.apply(this, arguments); + } + + return remove; + }(); + + _proto2.getSortComparator = function getSortComparator(query) { + var _ref6; + + var primaryKey = this.schema.primaryKey; + var sortOptions = query.sort ? query.sort : [(_ref6 = {}, _ref6[primaryKey] = 'asc', _ref6)]; + var massagedSelector = massageSelector(query.selector); + var inMemoryFields = Object.keys(query.selector); + + var fun = function fun(a, b) { + // TODO use createFieldSorter + // TODO make a performance test + var rows = [a, b].map(function (doc) { + // swap primary to _id + var cloned = flatClone(doc); + var primaryValue = cloned[primaryKey]; + delete cloned[primaryKey]; + cloned._id = primaryValue; + return { + doc: cloned + }; + }); + var sortedRows = filterInMemoryFields(rows, { + selector: massagedSelector, + sort: sortOptions + }, inMemoryFields); + + if (sortedRows[0].doc._id === rows[0].doc._id) { + return -1; + } else { + return 1; + } + }; + + return fun; + } + /** + * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js + */ + ; + + _proto2.getQueryMatcher = function getQueryMatcher(query) { + var primaryKey = this.schema.primaryKey; + var massagedSelector = massageSelector(query.selector); + + var fun = function fun(doc) { + var cloned = pouchSwapPrimaryToId(primaryKey, doc); + var row = { + doc: cloned + }; + var rowsMatched = filterInMemoryFields([row], { + selector: massagedSelector + }, Object.keys(query.selector)); + var ret = rowsMatched && rowsMatched.length === 1; + return ret; + }; + + return fun; + } + /** + * pouchdb has many bugs and strange behaviors + * this functions takes a normal mango query + * and transforms it to one that fits for pouchdb + */ + ; + + _proto2.prepareQuery = function prepareQuery(mutateableQuery) { + var _this4 = this; + + var primaryKey = this.schema.primaryKey; + var query = mutateableQuery; + /** + * because sort wont work on unused keys we have to workaround + * so we add the key to the selector if necessary + * @link https://github.com/nolanlawson/pouchdb-find/issues/204 + */ + + if (query.sort) { + query.sort.forEach(function (sortPart) { + var key = Object.keys(sortPart)[0]; + var comparisonOperators = ['$gt', '$gte', '$lt', '$lte']; + var keyUsed = query.selector[key] && Object.keys(query.selector[key]).some(function (op) { + return comparisonOperators.includes(op); + }) || false; + + if (!keyUsed) { + var schemaObj = getSchemaByObjectPath(_this4.schema, key); + + if (!schemaObj) { + throw newRxError('QU5', { + key: key + }); + } + + if (!query.selector[key]) { + query.selector[key] = {}; + } + + switch (schemaObj.type) { + case 'number': + case 'integer': + // TODO change back to -Infinity when issue resolved + // @link https://github.com/pouchdb/pouchdb/issues/6454 + // -Infinity does not work since pouchdb 6.2.0 + query.selector[key].$gt = -9999999999999999999999999999; + break; + + case 'string': + /** + * strings need an empty string, see + * @link https://github.com/pubkey/rxdb/issues/585 + */ + if (typeof query.selector[key] !== 'string') { + query.selector[key].$gt = ''; + } + + break; + + default: + query.selector[key].$gt = null; + break; + } + } + }); + } // regex does not work over the primary key + // TODO move this to dev mode + + + if (query.selector[primaryKey] && query.selector[primaryKey].$regex) { + throw newRxError('QU4', { + path: primaryKey, + query: mutateableQuery + }); + } // primary-swap sorting + + + if (query.sort) { + var sortArray = query.sort.map(function (part) { + var _newPart; + + var key = Object.keys(part)[0]; + var direction = Object.values(part)[0]; + var useKey = key === primaryKey ? '_id' : key; + var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); + return newPart; + }); + query.sort = sortArray; + } // strip empty selectors + + + Object.entries(query.selector).forEach(function (_ref7) { + var k = _ref7[0], + v = _ref7[1]; + + if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { + delete query.selector[k]; + } + }); + query.selector = primarySwapPouchDbQuerySelector(query.selector, primaryKey); + return query; + }; + + _proto2.bulkAddRevisions = /*#__PURE__*/function () { + var _bulkAddRevisions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(documents) { + var _this5 = this; + + var writeData; + return _regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + writeData = documents.map(function (doc) { + return pouchSwapPrimaryToId(_this5.schema.primaryKey, doc); + }); // we do not need the response here because pouchdb returns an empty array on new_edits: false + + _context10.next = 3; + return this.internals.pouch.bulkDocs(writeData, { + new_edits: false, + set_new_edit_as_latest_revision: true + }); + + case 3: + case "end": + return _context10.stop(); + } + } + }, _callee10, this); + })); + + function bulkAddRevisions(_x8) { + return _bulkAddRevisions.apply(this, arguments); + } + + return bulkAddRevisions; + }(); + + _proto2.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(documentWrites) { + var primaryKey, writeRowById, insertDocs, pouchResult, ret; + return _regeneratorRuntime.wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + primaryKey = this.schema.primaryKey; + writeRowById = new Map(); + insertDocs = documentWrites.map(function (writeData) { + var primary = writeData.document[primaryKey]; + writeRowById.set(primary, writeData); + var storeDocumentData = rxDocumentDataToPouchDocumentData(primaryKey, writeData.document); // if previous document exists, we have to send the previous revision to pouchdb. + + if (writeData.previous) { + storeDocumentData._rev = writeData.previous._rev; + } + + return storeDocumentData; + }); + _context12.next = 5; + return this.internals.pouch.bulkDocs(insertDocs, { + custom: { + writeRowById: writeRowById + } + }); + + case 5: + pouchResult = _context12.sent; + ret = { + success: new Map(), + error: new Map() + }; + _context12.next = 9; + return Promise.all(pouchResult.map( /*#__PURE__*/function () { + var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(resultRow) { + var writeRow, err, pushObj; + return _regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + writeRow = getFromMapOrThrow(writeRowById, resultRow.id); + + if (!resultRow.error) { + _context11.next = 6; + break; + } + + err = { + isError: true, + status: 409, + documentId: resultRow.id, + writeRow: writeRow + }; + ret.error.set(resultRow.id, err); + _context11.next = 18; + break; + + case 6: + pushObj = flatClone(writeRow.document); + pushObj = pouchSwapIdToPrimary(primaryKey, pushObj); + pushObj._rev = resultRow.rev; // replace the inserted attachments with their diggest + + // replace the inserted attachments with their diggest + pushObj._attachments = {}; + + if (writeRow.document._attachments) { + _context11.next = 14; + break; + } + + writeRow.document._attachments = {}; + _context11.next = 17; + break; + + case 14: + _context11.next = 16; + return writeAttachmentsToAttachments(writeRow.document._attachments); + + case 16: + pushObj._attachments = _context11.sent; + + case 17: + ret.success.set(resultRow.id, pushObj); + + case 18: + case "end": + return _context11.stop(); + } + } + }, _callee11); + })); + + return function (_x10) { + return _ref8.apply(this, arguments); + }; + }())); + + case 9: + _context12.next = 11; + return promiseWait(0).then(function () { + return promiseWait(0); + }); + + case 11: + return _context12.abrupt("return", ret); + + case 12: + case "end": + return _context12.stop(); + } + } + }, _callee12, this); + })); + + function bulkWrite(_x9) { + return _bulkWrite2.apply(this, arguments); + } + + return bulkWrite; + }(); + + _proto2.query = /*#__PURE__*/function () { + var _query = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(preparedQuery) { + var primaryKey, findResult, ret; + return _regeneratorRuntime.wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + primaryKey = this.schema.primaryKey; + _context13.next = 3; + return this.internals.pouch.find(preparedQuery); + + case 3: + findResult = _context13.sent; + ret = { + documents: findResult.docs.map(function (pouchDoc) { + var useDoc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); + return useDoc; + }) + }; + return _context13.abrupt("return", ret); + + case 6: + case "end": + return _context13.stop(); + } + } + }, _callee13, this); + })); + + function query(_x11) { + return _query.apply(this, arguments); + } + + return query; + }(); + + _proto2.getAttachmentData = /*#__PURE__*/function () { + var _getAttachmentData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(documentId, attachmentId) { + var attachmentData; + return _regeneratorRuntime.wrap(function _callee14$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return this.internals.pouch.getAttachment(documentId, attachmentId); + + case 2: + attachmentData = _context14.sent; + return _context14.abrupt("return", attachmentData); + + case 4: + case "end": + return _context14.stop(); + } + } + }, _callee14, this); + })); + + function getAttachmentData(_x12, _x13) { + return _getAttachmentData.apply(this, arguments); + } + + return getAttachmentData; + }(); + + _proto2.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(ids, deleted) { + var _this6 = this; + + var primaryKey, viaChanges, retDocs, pouchResult, ret; + return _regeneratorRuntime.wrap(function _callee16$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + primaryKey = this.schema.primaryKey; + /** + * On deleted documents, pouchdb will only return the tombstone. + * So we have to get the properties directly for each document + * with the hack of getting the changes and then make one request per document + * with the latest revision. + * TODO create an issue at pouchdb on how to get the document data of deleted documents, + * when one past revision was written via new_edits=false + * @link https://stackoverflow.com/a/63516761/3443137 + */ + + if (!deleted) { + _context16.next = 9; + break; + } + + _context16.next = 4; + return this.internals.pouch.changes({ + live: false, + since: 0, + doc_ids: ids, + style: 'all_docs' + }); + + case 4: + viaChanges = _context16.sent; + retDocs = new Map(); + _context16.next = 8; + return Promise.all(viaChanges.results.map( /*#__PURE__*/function () { + var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(result) { + var firstDoc, useFirstDoc; + return _regeneratorRuntime.wrap(function _callee15$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + _context15.next = 2; + return _this6.internals.pouch.get(result.id, { + rev: result.changes[0].rev, + deleted: 'ok', + style: 'all_docs' + }); + + case 2: + firstDoc = _context15.sent; + useFirstDoc = pouchDocumentDataToRxDocumentData(primaryKey, firstDoc); + retDocs.set(result.id, useFirstDoc); + + case 5: + case "end": + return _context15.stop(); + } + } + }, _callee15); + })); + + return function (_x16) { + return _ref9.apply(this, arguments); + }; + }())); + + case 8: + return _context16.abrupt("return", retDocs); + + case 9: + _context16.next = 11; + return this.internals.pouch.allDocs({ + include_docs: true, + keys: ids + }); + + case 11: + pouchResult = _context16.sent; + ret = new Map(); + pouchResult.rows.filter(function (row) { + return !!row.doc; + }).forEach(function (row) { + var docData = row.doc; + docData = pouchDocumentDataToRxDocumentData(primaryKey, docData); + ret.set(row.id, docData); + }); + return _context16.abrupt("return", ret); + + case 15: + case "end": + return _context16.stop(); + } + } + }, _callee16, this); + })); + + function findDocumentsById(_x14, _x15) { + return _findDocumentsById.apply(this, arguments); + } + + return findDocumentsById; + }(); + + _proto2.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + + _proto2.getChangedDocuments = /*#__PURE__*/function () { + var _getChangedDocuments = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(options) { + var pouchChangesOpts, pouchResults, changedDocuments, lastSequence; + return _regeneratorRuntime.wrap(function _callee17$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + pouchChangesOpts = { + live: false, + limit: options.limit, + include_docs: false, + since: options.startSequence, + descending: options.order === 'desc' ? true : false + }; + _context17.next = 3; + return this.internals.pouch.changes(pouchChangesOpts); + + case 3: + pouchResults = _context17.sent; + changedDocuments = pouchResults.results.filter(function (row) { + return !row.id.startsWith(POUCHDB_DESIGN_PREFIX); + }).map(function (row) { + return { + id: row.id, + sequence: row.seq + }; + }); + lastSequence = pouchResults.last_seq; + return _context17.abrupt("return", { + changedDocuments: changedDocuments, + lastSequence: lastSequence + }); + + case 7: + case "end": + return _context17.stop(); + } + } + }, _callee17, this); + })); + + function getChangedDocuments(_x17) { + return _getChangedDocuments.apply(this, arguments); + } + + return getChangedDocuments; + }(); + + return RxStorageInstancePouch; +}(); +export var RxStoragePouch = /*#__PURE__*/function () { + function RxStoragePouch(adapter) { + var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.name = 'pouchdb'; + this.adapter = adapter; + this.pouchSettings = pouchSettings; + checkPouchAdapter(adapter); + } + /** + * create the same diggest as an attachment with that data + * would have created by pouchdb internally. + */ + + + var _proto3 = RxStoragePouch.prototype; + + _proto3.hash = function hash(data) { + return pouchHash(data); + }; + + _proto3.createPouch = /*#__PURE__*/function () { + var _createPouch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(location, options) { + var pouchDbParameters, pouchDBOptions, pouch; + return _regeneratorRuntime.wrap(function _callee18$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + pouchDbParameters = { + location: location, + adapter: adapterObject(this.adapter), + settings: options + }; + pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); + pouch = new PouchDB(pouchDbParameters.location, pouchDBOptions); + /** + * In the past we found some errors where the PouchDB is not directly useable + * so we we had to call .info() first to ensure it can be used. + * I commented this out for now to get faster database/collection creation. + * We might have to add this again if something fails. + */ + // await pouch.info(); + + return _context18.abrupt("return", pouch); + + case 4: + case "end": + return _context18.stop(); + } + } + }, _callee18, this); + })); + + function createPouch(_x18, _x19) { + return _createPouch.apply(this, arguments); + } + + return createPouch; + }(); + + _proto3.createStorageInstance = /*#__PURE__*/function () { + var _createStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19(params) { + var pouchLocation, pouch; + return _regeneratorRuntime.wrap(function _callee19$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + pouchLocation = getPouchLocation(params.databaseName, params.collectionName, params.schema.version); + _context19.next = 3; + return this.createPouch(pouchLocation, params.options); + + case 3: + pouch = _context19.sent; + _context19.next = 6; + return createIndexesOnPouch(pouch, params.schema); + + case 6: + return _context19.abrupt("return", new RxStorageInstancePouch(params.databaseName, params.collectionName, params.schema, { + pouch: pouch + }, params.options)); + + case 7: + case "end": + return _context19.stop(); + } + } + }, _callee19, this); + })); + + function createStorageInstance(_x20) { + return _createStorageInstance.apply(this, arguments); + } + + return createStorageInstance; + }(); + + _proto3.createKeyObjectStorageInstance = /*#__PURE__*/function () { + var _createKeyObjectStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee20(databaseName, collectionName, options) { + var useOptions, pouchLocation, pouch; + return _regeneratorRuntime.wrap(function _callee20$(_context20) { + while (1) { + switch (_context20.prev = _context20.next) { + case 0: + useOptions = flatClone(options); // no compaction because this only stores local documents + + useOptions.auto_compaction = false; + useOptions.revs_limit = 1; + pouchLocation = getPouchLocation(databaseName, collectionName, 0); + _context20.next = 6; + return this.createPouch(pouchLocation, options); + + case 6: + pouch = _context20.sent; + return _context20.abrupt("return", new RxStorageKeyObjectInstancePouch(databaseName, collectionName, { + pouch: pouch + }, options)); + + case 8: + case "end": + return _context20.stop(); + } + } + }, _callee20, this); + })); + + function createKeyObjectStorageInstance(_x21, _x22, _x23) { + return _createKeyObjectStorageInstance.apply(this, arguments); + } + + return createKeyObjectStorageInstance; + }(); + + return RxStoragePouch; +}(); +export function writeAttachmentsToAttachments(_x24) { + return _writeAttachmentsToAttachments.apply(this, arguments); +} +/** + * Checks if all is ok with the given adapter, + * else throws an error. + */ + +function _writeAttachmentsToAttachments() { + _writeAttachmentsToAttachments = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee22(attachments) { + var ret; + return _regeneratorRuntime.wrap(function _callee22$(_context22) { + while (1) { + switch (_context22.prev = _context22.next) { + case 0: + if (attachments) { + _context22.next = 2; + break; + } + + return _context22.abrupt("return", {}); + + case 2: + ret = {}; + _context22.next = 5; + return Promise.all(Object.entries(attachments).map( /*#__PURE__*/function () { + var _ref14 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee21(_ref13) { + var key, obj, asWrite, hash, asString, length; + return _regeneratorRuntime.wrap(function _callee21$(_context21) { + while (1) { + switch (_context21.prev = _context21.next) { + case 0: + key = _ref13[0], obj = _ref13[1]; + + if (obj.type) { + _context21.next = 3; + break; + } + + throw newRxError('SNH', { + args: obj + }); + + case 3: + if (!obj.data) { + _context21.next = 15; + break; + } + + asWrite = obj; + _context21.next = 7; + return pouchHash(asWrite.data); + + case 7: + hash = _context21.sent; + _context21.next = 10; + return blobBufferUtil.toString(asWrite.data); + + case 10: + asString = _context21.sent; + length = asString.length; + ret[key] = { + digest: hash, + length: length, + type: asWrite.type + }; + _context21.next = 16; + break; + + case 15: + ret[key] = obj; + + case 16: + case "end": + return _context21.stop(); + } + } + }, _callee21); + })); + + return function (_x27) { + return _ref14.apply(this, arguments); + }; + }())); + + case 5: + return _context22.abrupt("return", ret); + + case 6: + case "end": + return _context22.stop(); + } + } + }, _callee22); + })); + return _writeAttachmentsToAttachments.apply(this, arguments); +} + +export function checkPouchAdapter(adapter) { + if (typeof adapter === 'string') { + // TODO make a function hasAdapter() + if (!PouchDB.adapters || !PouchDB.adapters[adapter]) { + throw newRxError('DB9', { + adapter: adapter + }); + } + } else { + isLevelDown(adapter); + + if (!PouchDB.adapters || !PouchDB.adapters.leveldb) { + throw newRxError('DB10', { + adapter: adapter + }); + } + } +} +export function pouchHash(data) { + return new Promise(function (res) { + binaryMd5(data, function (digest) { + res('md5-' + digest); + }); + }); +} +export function pouchSwapIdToPrimary(primaryKey, docData) { + if (primaryKey === '_id' || docData[primaryKey]) { + return docData; + } + + docData = flatClone(docData); + docData[primaryKey] = docData._id; + delete docData._id; + return docData; +} +export function pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc) { + var useDoc = pouchSwapIdToPrimary(primaryKey, pouchDoc); // always flat clone becaues we mutate the _attachments property. + + useDoc = flatClone(useDoc); + delete useDoc._revisions; + useDoc._attachments = {}; + + if (pouchDoc._attachments) { + Object.entries(pouchDoc._attachments).forEach(function (_ref10) { + var key = _ref10[0], + value = _ref10[1]; + + if (value.data) { + useDoc._attachments[key] = { + data: value.data, + type: value.type + }; + } else { + useDoc._attachments[key] = { + digest: value.digest, + // TODO why do we need to access value.type? + type: value.type ? value.type : value.content_type, + length: value.length + }; + } + }); + } + + return useDoc; +} +export function rxDocumentDataToPouchDocumentData(primaryKey, doc) { + var pouchDoc = pouchSwapPrimaryToId(primaryKey, doc); // always flat clone becaues we mutate the _attachments property. + + pouchDoc = flatClone(pouchDoc); + pouchDoc._attachments = {}; + + if (doc._attachments) { + Object.entries(doc._attachments).forEach(function (_ref11) { + var key = _ref11[0], + value = _ref11[1]; + var useValue = value; + + if (useValue.data) { + pouchDoc._attachments[key] = { + data: useValue.data, + content_type: useValue.type + }; + } else { + pouchDoc._attachments[key] = { + digest: useValue.digest, + content_type: useValue.type, + length: useValue.length, + stub: true + }; + } + }); + } + + return pouchDoc; +} +export function pouchSwapPrimaryToId(primaryKey, docData) { + if (primaryKey === '_id') { + return docData; + } + + var ret = {}; + Object.entries(docData).forEach(function (entry) { + var newKey = entry[0] === primaryKey ? '_id' : entry[0]; + ret[newKey] = entry[1]; + }); + return ret; +} +/** + * in: '_local/foobar' + * out: 'foobar' + */ + +export function pouchStripLocalFlagFromPrimary(str) { + return str.substring(POUCHDB_LOCAL_PREFIX.length); +} +export function getEventKey(isLocal, primary, revision) { + if (!primary) { + throw new Error('primary missing !!'); + } + + var prefix = isLocal ? 'local' : 'non-local'; + var eventKey = prefix + '|' + primary + '|' + revision; + return eventKey; +} +export function pouchChangeRowToChangeEvent(primaryKey, pouchDoc) { + if (!pouchDoc) { + throw newRxError('SNH', { + args: { + pouchDoc: pouchDoc + } + }); + } + + var id = pouchDoc._id; + var doc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); + var revHeight = getHeightOfRevision(doc._rev); + + if (pouchDoc._deleted) { + return { + operation: 'DELETE', + id: id, + doc: null, + previous: doc + }; + } else if (revHeight === 1) { + return { + operation: 'INSERT', + id: id, + doc: doc, + previous: null + }; + } else { + return { + operation: 'UPDATE', + id: id, + doc: doc, + previous: 'UNKNOWN' + }; + } +} +export function pouchChangeRowToChangeStreamEvent(primaryKey, pouchRow) { + var doc = pouchRow.doc; + + if (!doc) { + throw newRxError('SNH', { + args: { + pouchRow: pouchRow + } + }); + } + + var revHeight = getHeightOfRevision(doc._rev); + + if (pouchRow.deleted) { + var previousDoc = flatClone(pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc)); + delete previousDoc._deleted; + var ev = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'DELETE', + doc: null, + previous: previousDoc + }; + return ev; + } else if (revHeight === 1) { + var _ev = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'INSERT', + doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), + previous: null + }; + return _ev; + } else { + var _ev2 = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'UPDATE', + doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), + previous: 'UNKNOWN' + }; + return _ev2; + } +} +/** + * Runs a primary swap with transform all custom primaryKey occurences + * into '_id' + * @recursive + */ + +export function primarySwapPouchDbQuerySelector(selector, primaryKey) { + if (primaryKey === '_id') { + return selector; + } + + if (Array.isArray(selector)) { + return selector.map(function (item) { + return primarySwapPouchDbQuerySelector(item, primaryKey); + }); + } else if (typeof selector === 'object') { + var ret = {}; + Object.entries(selector).forEach(function (_ref12) { + var k = _ref12[0], + v = _ref12[1]; + + if (k === primaryKey) { + ret._id = v; + } else { + if (k.startsWith('$')) { + ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); + } else { + ret[k] = v; + } + } + }); + return ret; + } else { + return selector; + } +} +/** + * Creates the indexes of the schema inside of the pouchdb instance. + * Will skip indexes that already exist. + */ + +export function createIndexesOnPouch(_x25, _x26) { + return _createIndexesOnPouch.apply(this, arguments); +} +/** + * returns the pouchdb-database-name + */ + +function _createIndexesOnPouch() { + _createIndexesOnPouch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee24(pouch, schema) { + var primaryKey, before, existingIndexes; + return _regeneratorRuntime.wrap(function _callee24$(_context24) { + while (1) { + switch (_context24.prev = _context24.next) { + case 0: + if (schema.indexes) { + _context24.next = 2; + break; + } + + return _context24.abrupt("return"); + + case 2: + primaryKey = schema.primaryKey; + _context24.next = 5; + return pouch.getIndexes(); + + case 5: + before = _context24.sent; + existingIndexes = new Set(before.indexes.map(function (idx) { + return idx.name; + })); + _context24.next = 9; + return Promise.all(schema.indexes.map( /*#__PURE__*/function () { + var _ref15 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23(indexMaybeArray) { + var indexArray, indexName; + return _regeneratorRuntime.wrap(function _callee23$(_context23) { + while (1) { + switch (_context23.prev = _context23.next) { + case 0: + indexArray = Array.isArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; + /** + * replace primary key with _id + * because that is the enforced primary key on pouchdb. + */ + + /** + * replace primary key with _id + * because that is the enforced primary key on pouchdb. + */ + indexArray = indexArray.map(function (key) { + if (key === primaryKey) { + return '_id'; + } else { + return key; + } + }); + indexName = 'idx-rxdb-index-' + indexArray.join(','); + + if (!existingIndexes.has(indexName)) { + _context23.next = 5; + break; + } + + return _context23.abrupt("return"); + + case 5: + return _context23.abrupt("return", pouch.createIndex({ + name: indexName, + ddoc: indexName, + index: { + fields: indexArray + } + })); + + case 6: + case "end": + return _context23.stop(); + } + } + }, _callee23); + })); + + return function (_x28) { + return _ref15.apply(this, arguments); + }; + }())); + + case 9: + case "end": + return _context24.stop(); + } + } + }, _callee24); + })); + return _createIndexesOnPouch.apply(this, arguments); +} + +export function getPouchLocation(dbName, collectionName, schemaVersion) { + var prefix = dbName + '-rxdb-' + schemaVersion + '-'; + + if (!collectionName.includes('/')) { + return prefix + collectionName; + } else { + // if collectionName is a path, we have to prefix the last part only + var split = collectionName.split('/'); + var last = split.pop(); + var ret = split.join('/'); + ret += '/' + prefix + last; + return ret; + } +} +export function getRxStoragePouch(adapter, pouchSettings) { + if (!adapter) { + throw new Error('adapter missing'); + } + + var storage = new RxStoragePouch(adapter, pouchSettings); + return storage; +} +//# sourceMappingURL=rx-storage-pouchdb.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication.js b/dist/es/plugins/replication-couchdb.js similarity index 73% rename from dist/es/plugins/replication.js rename to dist/es/plugins/replication-couchdb.js index f72bcb2b732..87a1f8339c4 100644 --- a/dist/es/plugins/replication.js +++ b/dist/es/plugins/replication-couchdb.js @@ -1,3 +1,6 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; + /** * this plugin adds the RxCollection.sync()-function to rxdb * you can use it to sync collections with remote or local couchdb-instances @@ -6,15 +9,12 @@ import PouchReplicationPlugin from 'pouchdb-replication'; import { BehaviorSubject, Subject, fromEvent, firstValueFrom } from 'rxjs'; import { skipUntil, filter, first, mergeMap } from 'rxjs/operators'; import { promiseWait, flatClone } from '../util'; -import { addRxPlugin } from '../core'; import { newRxError } from '../rx-error'; -import { pouchReplicationFunction, isInstanceOf as isInstanceOfPouchDB } from '../pouch-db'; -import { isInstanceOf as isRxCollection } from '../rx-collection'; -import { RxDBWatchForChangesPlugin } from './watch-for-changes'; // add pouchdb-replication-plugin - -addRxPlugin(PouchReplicationPlugin); // add the watch-for-changes-plugin +import { pouchReplicationFunction, isInstanceOf as isInstanceOfPouchDB, addPouchPlugin } from '../plugins/pouchdb'; +import { isRxCollection } from '../rx-collection'; +import { _handleFromStorageInstance } from '../rx-collection-helper'; // add pouchdb-replication-plugin -addRxPlugin(RxDBWatchForChangesPlugin); +addPouchPlugin(PouchReplicationPlugin); /** * Contains all pouchdb instances that * are used inside of RxDB by collections or databases. @@ -22,8 +22,8 @@ addRxPlugin(RxDBWatchForChangesPlugin); */ var INTERNAL_POUCHDBS = new WeakSet(); -export var RxReplicationStateBase = /*#__PURE__*/function () { - function RxReplicationStateBase(collection, syncOptions) { +export var RxCouchDBReplicationStateBase = /*#__PURE__*/function () { + function RxCouchDBReplicationStateBase(collection, syncOptions) { var _this = this; this._subs = []; @@ -49,7 +49,7 @@ export var RxReplicationStateBase = /*#__PURE__*/function () { }); } - var _proto = RxReplicationStateBase.prototype; + var _proto = RxCouchDBReplicationStateBase.prototype; _proto.awaitInitialReplication = function awaitInitialReplication() { if (this.syncOptions.options && this.syncOptions.options.live) { @@ -96,7 +96,7 @@ export var RxReplicationStateBase = /*#__PURE__*/function () { return Promise.resolve(true); }; - return RxReplicationStateBase; + return RxCouchDBReplicationStateBase; }(); export function setPouchEventEmitter(rxRepState, evEmitter) { if (rxRepState._pouchEventEmitterObject) { @@ -121,7 +121,7 @@ export function setPouchEventEmitter(rxRepState, evEmitter) { return doc.language !== 'query'; }) // remove internal docs .map(function (doc) { - return rxRepState.collection._handleFromPouch(doc); + return _handleFromStorageInstance(rxRepState.collection, doc); }) // do primary-swap and keycompression .forEach(function (doc) { return rxRepState._subjects.docs.next(doc); @@ -143,17 +143,30 @@ export function setPouchEventEmitter(rxRepState, evEmitter) { })); // complete - rxRepState._subs.push(fromEvent(evEmitter, 'complete').subscribe(function (info) { - /** - * when complete fires, it might be that not all changeEvents - * have passed throught, because of the delay of .wachtForChanges() - * Therefore we have to first ensure that all previous changeEvents have been handled - */ - var unhandledEvents = Array.from(rxRepState.collection._watchForChangesUnhandled); - Promise.all(unhandledEvents).then(function () { - return rxRepState._subjects.complete.next(info); - }); - })); // auto-cancel one-time replications on complelete to not cause memory leak + rxRepState._subs.push(fromEvent(evEmitter, 'complete').subscribe( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(info) { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return promiseWait(100); + + case 2: + rxRepState._subjects.complete.next(info); + + case 3: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); // auto-cancel one-time replications on complelete to not cause memory leak if (!rxRepState.syncOptions.options || !rxRepState.syncOptions.options.live) { @@ -196,26 +209,26 @@ export function setPouchEventEmitter(rxRepState, evEmitter) { }); })); } -export function createRxReplicationState(collection, syncOptions) { - return new RxReplicationStateBase(collection, syncOptions); +export function createRxCouchDBReplicationState(collection, syncOptions) { + return new RxCouchDBReplicationStateBase(collection, syncOptions); } -export function sync(_ref) { +export function syncCouchDB(_ref2) { var _this2 = this; - var remote = _ref.remote, - _ref$waitForLeadershi = _ref.waitForLeadership, - waitForLeadership = _ref$waitForLeadershi === void 0 ? true : _ref$waitForLeadershi, - _ref$direction = _ref.direction, - direction = _ref$direction === void 0 ? { + var remote = _ref2.remote, + _ref2$waitForLeadersh = _ref2.waitForLeadership, + waitForLeadership = _ref2$waitForLeadersh === void 0 ? true : _ref2$waitForLeadersh, + _ref2$direction = _ref2.direction, + direction = _ref2$direction === void 0 ? { pull: true, push: true - } : _ref$direction, - _ref$options = _ref.options, - options = _ref$options === void 0 ? { + } : _ref2$direction, + _ref2$options = _ref2.options, + options = _ref2$options === void 0 ? { live: true, retry: true - } : _ref$options, - query = _ref.query; + } : _ref2$options, + query = _ref2.query; var useOptions = flatClone(options); // prevent #641 by not allowing internal pouchdbs as remote if (isInstanceOfPouchDB(remote) && INTERNAL_POUCHDBS.has(remote)) { @@ -227,8 +240,7 @@ export function sync(_ref) { if (isRxCollection(remote)) { - remote.watchForChanges(); - remote = remote.pouch; + remote = remote.storageInstance.internals.pouch; } if (query && this !== query.collection) { @@ -237,13 +249,13 @@ export function sync(_ref) { }); } - var syncFun = pouchReplicationFunction(this.pouch, direction); + var syncFun = pouchReplicationFunction(this.storageInstance.internals.pouch, direction); if (query) { - useOptions.selector = query.keyCompress().selector; + useOptions.selector = query.toJSON().selector; } - var repState = createRxReplicationState(this, { + var repState = createRxCouchDBReplicationState(this, { remote: remote, waitForLeadership: waitForLeadership, direction: direction, @@ -258,8 +270,6 @@ export function sync(_ref) { return; } - _this2.watchForChanges(); - var pouchSync = syncFun(remote, useOptions); setPouchEventEmitter(repState, pouchSync); @@ -270,18 +280,22 @@ export function sync(_ref) { export var rxdb = true; export var prototypes = { RxCollection: function RxCollection(proto) { - proto.sync = sync; + proto.syncCouchDB = syncCouchDB; } }; export var hooks = { createRxCollection: function createRxCollection(collection) { - INTERNAL_POUCHDBS.add(collection.pouch); + var pouch = collection.storageInstance.internals.pouch; + + if (pouch) { + INTERNAL_POUCHDBS.add(collection.storageInstance.internals.pouch); + } } }; -export var RxDBReplicationPlugin = { - name: 'replication', +export var RxDBReplicationCouchDBPlugin = { + name: 'replication-couchdb', rxdb: rxdb, prototypes: prototypes, hooks: hooks }; -//# sourceMappingURL=replication.js.map \ No newline at end of file +//# sourceMappingURL=replication-couchdb.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/crawling-checkpoint.js b/dist/es/plugins/replication-graphql/crawling-checkpoint.js index e29c8ec928c..4cfff6227ec 100644 --- a/dist/es/plugins/replication-graphql/crawling-checkpoint.js +++ b/dist/es/plugins/replication-graphql/crawling-checkpoint.js @@ -1,13 +1,14 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _regeneratorRuntime from "@babel/runtime/regenerator"; -import { LOCAL_PREFIX } from '../../util'; -import { PLUGIN_IDENT, getDocFromPouchOrNull, wasRevisionfromPullReplication } from './helper'; - +import { wasRevisionfromPullReplication, GRAPHQL_REPLICATION_PLUGIN_IDENT } from './helper'; +import { findLocalDocument, writeSingleLocal } from '../../rx-storage-helper'; +import { flatClone } from '../../util'; +import { newRxError } from '../../rx-error'; /** * when the replication starts, * we need a way to find out where it ended the last time. * - * For push-replication, we use the pouchdb-sequence: + * For push-replication, we use the storageInstance-sequence: * We get the documents newer then the last sequence-id * and push them to the server. * @@ -18,8 +19,9 @@ import { PLUGIN_IDENT, getDocFromPouchOrNull, wasRevisionfromPullReplication } f // // things for the push-checkpoint // + var pushSequenceId = function pushSequenceId(endpointHash) { - return LOCAL_PREFIX + PLUGIN_IDENT + '-push-checkpoint-' + endpointHash; + return GRAPHQL_REPLICATION_PLUGIN_IDENT + '-push-checkpoint-' + endpointHash; }; /** * @return last sequence checkpoint @@ -38,7 +40,7 @@ function _getLastPushSequence() { switch (_context.prev = _context.next) { case 0: _context.next = 2; - return getDocFromPouchOrNull(collection, pushSequenceId(endpointHash)); + return findLocalDocument(collection.localDocumentsStore, pushSequenceId(endpointHash)); case 2: doc = _context.sent; @@ -68,8 +70,8 @@ export function setLastPushSequence(_x3, _x4, _x5) { } function _setLastPushSequence() { - _setLastPushSequence = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(collection, endpointHash, seq) { - var _id, doc, res; + _setLastPushSequence = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(collection, endpointHash, sequence) { + var _id, doc, res, newDoc, _res; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { @@ -77,28 +79,47 @@ function _setLastPushSequence() { case 0: _id = pushSequenceId(endpointHash); _context2.next = 3; - return getDocFromPouchOrNull(collection, _id); + return findLocalDocument(collection.localDocumentsStore, _id); case 3: doc = _context2.sent; - if (!doc) { - doc = { - _id: _id, - value: seq - }; - } else { - doc.value = seq; + if (doc) { + _context2.next = 11; + break; } _context2.next = 7; - return collection.pouch.put(doc); + return writeSingleLocal(collection.localDocumentsStore, { + document: { + _id: _id, + value: sequence, + _attachments: {} + } + }); case 7: res = _context2.sent; return _context2.abrupt("return", res); - case 9: + case 11: + newDoc = flatClone(doc); + newDoc.value = sequence; + _context2.next = 15; + return writeSingleLocal(collection.localDocumentsStore, { + previous: doc, + document: { + _id: _id, + value: sequence, + _attachments: {} + } + }); + + case 15: + _res = _context2.sent; + return _context2.abrupt("return", _res); + + case 17: case "end": return _context2.stop(); } @@ -108,120 +129,156 @@ function _setLastPushSequence() { return _setLastPushSequence.apply(this, arguments); } -export function getChangesSinceLastPushSequence(_x6, _x7, _x8) { +export function getChangesSinceLastPushSequence(_x6, _x7) { return _getChangesSinceLastPushSequence.apply(this, arguments); } // // things for pull-checkpoint // function _getChangesSinceLastPushSequence() { - _getChangesSinceLastPushSequence = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(collection, endpointHash, lastPulledRevField) { + _getChangesSinceLastPushSequence = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(collection, endpointHash) { var batchSize, - syncRevisions, lastPushSequence, retry, - changes, - filteredResults, - useResults, - docsSearch, - bulkGetDocs, - _args3 = arguments; - return _regeneratorRuntime.wrap(function _callee3$(_context3) { + lastSequence, + changedDocs, + _loop, + _ret, + _args4 = arguments; + + return _regeneratorRuntime.wrap(function _callee3$(_context4) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context4.prev = _context4.next) { case 0: - batchSize = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : 10; - syncRevisions = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : false; - _context3.next = 4; + batchSize = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : 10; + _context4.next = 3; return getLastPushSequence(collection, endpointHash); - case 4: - lastPushSequence = _context3.sent; + case 3: + lastPushSequence = _context4.sent; retry = true; + lastSequence = lastPushSequence; + changedDocs = new Map(); + /** + * it can happen that all docs in the batch + * do not have to be replicated. + * Then we have to continue grapping the feed + * until we reach the end of it + */ + + _loop = /*#__PURE__*/_regeneratorRuntime.mark(function _loop() { + var changesResults, docs; + return _regeneratorRuntime.wrap(function _loop$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return collection.storageInstance.getChangedDocuments({ + startSequence: lastPushSequence, + limit: batchSize, + order: 'asc' + }); + + case 2: + changesResults = _context3.sent; + lastSequence = changesResults.lastSequence; // optimisation shortcut, do not proceed if there are no changed documents + + if (!(changesResults.changedDocuments.length === 0)) { + _context3.next = 7; + break; + } + + retry = false; + return _context3.abrupt("return", "continue"); + + case 7: + _context3.next = 9; + return collection.storageInstance.findDocumentsById(changesResults.changedDocuments.map(function (row) { + return row.id; + }), true); + + case 9: + docs = _context3.sent; + changesResults.changedDocuments.forEach(function (row) { + var id = row.id; + + if (changedDocs.has(id)) { + return; + } + + var changedDoc = docs.get(id); + + if (!changedDoc) { + throw newRxError('SNH', { + args: { + docs: docs + } + }); + } + /** + * filter out changes with revisions resulting from the pull-stream + * so that they will not be upstreamed again + */ + + + if (wasRevisionfromPullReplication(endpointHash, changedDoc._rev)) { + return false; + } + + changedDocs.set(id, { + id: id, + doc: changedDoc, + sequence: row.sequence + }); + }); + + if (changedDocs.size < batchSize && changesResults.changedDocuments.length === batchSize) { + // no pushable docs found but also not reached the end -> re-run + lastPushSequence = lastSequence; + retry = true; + } else { + retry = false; + } + + case 12: + case "end": + return _context3.stop(); + } + } + }, _loop); + }); - case 6: + case 8: if (!retry) { - _context3.next = 21; + _context4.next = 15; break; } - _context3.next = 9; - return collection.pouch.changes({ - since: lastPushSequence, - limit: batchSize, - include_docs: true // style: 'all_docs' + return _context4.delegateYield(_loop(), "t0", 10); - }); - - case 9: - changes = _context3.sent; - filteredResults = changes.results.filter(function (change) { - /** - * filter out changes with revisions resulting from the pull-stream - * so that they will not be upstreamed again - */ - if (wasRevisionfromPullReplication(endpointHash, change.doc._rev)) return false; - if (change.doc[lastPulledRevField] === change.doc._rev) return false; - /** - * filter out internal docs - * that are used for views or indexes in pouchdb - */ - - if (change.id.startsWith('_design/')) return false; - return true; - }); - useResults = filteredResults; + case 10: + _ret = _context4.t0; - if (!(filteredResults.length > 0 && syncRevisions)) { - _context3.next = 18; + if (!(_ret === "continue")) { + _context4.next = 13; break; } - docsSearch = filteredResults.map(function (result) { - return { - id: result.id, - rev: result.doc._rev - }; - }); - _context3.next = 16; - return collection.pouch.bulkGet({ - docs: docsSearch, - revs: true, - latest: true - }); + return _context4.abrupt("continue", 8); - case 16: - bulkGetDocs = _context3.sent; - useResults = bulkGetDocs.results.map(function (result) { - return { - id: result.id, - doc: result.docs[0]['ok'], - deleted: result.docs[0]['ok']._deleted - }; - }); - - case 18: - if (useResults.length === 0 && changes.results.length === batchSize) { - // no pushable docs found but also not reached the end -> re-run - lastPushSequence = changes.last_seq; - retry = true; - } else { - changes.results = useResults; - retry = false; - } - - _context3.next = 6; + case 13: + _context4.next = 8; break; - case 21: - changes.results.forEach(function (change) { - change.doc = collection._handleFromPouch(change.doc); + case 15: + return _context4.abrupt("return", { + changedDocs: changedDocs, + lastSequence: lastSequence }); - return _context3.abrupt("return", changes); - case 23: + case 16: case "end": - return _context3.stop(); + return _context4.stop(); } } }, _callee3); @@ -230,39 +287,39 @@ function _getChangesSinceLastPushSequence() { } var pullLastDocumentId = function pullLastDocumentId(endpointHash) { - return LOCAL_PREFIX + PLUGIN_IDENT + '-pull-checkpoint-' + endpointHash; + return GRAPHQL_REPLICATION_PLUGIN_IDENT + '-pull-checkpoint-' + endpointHash; }; -export function getLastPullDocument(_x9, _x10) { +export function getLastPullDocument(_x8, _x9) { return _getLastPullDocument.apply(this, arguments); } function _getLastPullDocument() { _getLastPullDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(collection, endpointHash) { var localDoc; - return _regeneratorRuntime.wrap(function _callee4$(_context4) { + return _regeneratorRuntime.wrap(function _callee4$(_context5) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context5.prev = _context5.next) { case 0: - _context4.next = 2; - return getDocFromPouchOrNull(collection, pullLastDocumentId(endpointHash)); + _context5.next = 2; + return findLocalDocument(collection.localDocumentsStore, pullLastDocumentId(endpointHash)); case 2: - localDoc = _context4.sent; + localDoc = _context5.sent; if (localDoc) { - _context4.next = 7; + _context5.next = 7; break; } - return _context4.abrupt("return", null); + return _context5.abrupt("return", null); case 7: - return _context4.abrupt("return", localDoc.doc); + return _context5.abrupt("return", localDoc.doc); case 8: case "end": - return _context4.stop(); + return _context5.stop(); } } }, _callee4); @@ -270,39 +327,49 @@ function _getLastPullDocument() { return _getLastPullDocument.apply(this, arguments); } -export function setLastPullDocument(_x11, _x12, _x13) { +export function setLastPullDocument(_x10, _x11, _x12) { return _setLastPullDocument.apply(this, arguments); } function _setLastPullDocument() { _setLastPullDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(collection, endpointHash, doc) { - var _id, localDoc; + var _id, localDoc, newDoc; - return _regeneratorRuntime.wrap(function _callee5$(_context5) { + return _regeneratorRuntime.wrap(function _callee5$(_context6) { while (1) { - switch (_context5.prev = _context5.next) { + switch (_context6.prev = _context6.next) { case 0: _id = pullLastDocumentId(endpointHash); - _context5.next = 3; - return getDocFromPouchOrNull(collection, _id); + _context6.next = 3; + return findLocalDocument(collection.localDocumentsStore, _id); case 3: - localDoc = _context5.sent; + localDoc = _context6.sent; - if (!localDoc) { - localDoc = { - _id: _id, - doc: doc - }; - } else { - localDoc.doc = doc; + if (localDoc) { + _context6.next = 8; + break; } - return _context5.abrupt("return", collection.pouch.put(localDoc)); + return _context6.abrupt("return", writeSingleLocal(collection.localDocumentsStore, { + document: { + _id: _id, + doc: doc, + _attachments: {} + } + })); - case 6: + case 8: + newDoc = flatClone(localDoc); + newDoc.doc = doc; + return _context6.abrupt("return", writeSingleLocal(collection.localDocumentsStore, { + previous: localDoc, + document: newDoc + })); + + case 11: case "end": - return _context5.stop(); + return _context6.stop(); } } }, _callee5); diff --git a/dist/es/plugins/replication-graphql/helper.js b/dist/es/plugins/replication-graphql/helper.js index af1df0b5017..d722cf954c7 100644 --- a/dist/es/plugins/replication-graphql/helper.js +++ b/dist/es/plugins/replication-graphql/helper.js @@ -1,119 +1,23 @@ -import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; -import _regeneratorRuntime from "@babel/runtime/regenerator"; import { hash } from '../../util'; -export var PLUGIN_IDENT = 'rxdbreplicationgraphql'; // does nothing +export var GRAPHQL_REPLICATION_PLUGIN_IDENT = 'rxdbreplicationgraphql'; // does nothing export var DEFAULT_MODIFIER = function DEFAULT_MODIFIER(d) { return Promise.resolve(d); }; /** - * pouchdb will throw if a document is not found - * this instead return null + * Returns a new revision key without the revision height. + * The revision is crafted for the graphql replication + * and contains the information that this document data was pulled + * from the remote server and not saved by the client. */ -export function getDocFromPouchOrNull(collection, id) { - return collection.pouch.get(id, { - open_revs: true - }).then(function (docData) { - return docData; - })["catch"](function () { - return null; - }); -} -/** - * - * @return revisions and docs, indexed by id - */ - -export function getDocsWithRevisionsFromPouch(_x, _x2) { - return _getDocsWithRevisionsFromPouch.apply(this, arguments); -} - -function _getDocsWithRevisionsFromPouch() { - _getDocsWithRevisionsFromPouch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(collection, docIds) { - var pouch, allDocs, docsSearch, bulkGetDocs, ret; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(docIds.length === 0)) { - _context.next = 2; - break; - } - - return _context.abrupt("return", {}); - - case 2: - // optimisation shortcut - pouch = collection.pouch; - _context.next = 5; - return pouch.allDocs({ - keys: docIds, - revs: true, - deleted: 'ok' - }); - - case 5: - allDocs = _context.sent; - // console.log('allDocs:'); - // console.log(JSON.stringify(allDocs, null, 2)); - docsSearch = allDocs.rows.filter(function (row) { - return !row.error; - }).map(function (row) { - return { - id: row.id, - rev: row.value.rev - }; - }); - - if (!(docsSearch.length === 0)) { - _context.next = 9; - break; - } - - return _context.abrupt("return", {}); - - case 9: - _context.next = 11; - return pouch.bulkGet({ - docs: docsSearch, - revs: true, - latest: true - }); - - case 11: - bulkGetDocs = _context.sent; - // console.log('bulkGetDocs:'); - // console.log(JSON.stringify(bulkGetDocs, null, 2)); - ret = {}; - bulkGetDocs.results.forEach(function (result) { - var doc = result.docs[0].ok; - var data = { - revisions: doc._revisions, - deleted: !!doc._deleted, - doc: doc - }; - ret[result.id] = data; - }); - return _context.abrupt("return", ret); - - case 15: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - return _getDocsWithRevisionsFromPouch.apply(this, arguments); -} - export function createRevisionForPulledDocument(endpointHash, doc) { var dataHash = hash(doc); - var ret = dataHash.substring(0, 8) + endpointHash.substring(0, 8) + PLUGIN_IDENT; + var ret = dataHash.substring(0, 8) + endpointHash.substring(0, 8) + GRAPHQL_REPLICATION_PLUGIN_IDENT; return ret; } export function wasRevisionfromPullReplication(endpointHash, revision) { - var ending = endpointHash.substring(0, 8) + PLUGIN_IDENT; + var ending = endpointHash.substring(0, 8) + GRAPHQL_REPLICATION_PLUGIN_IDENT; var ret = revision.endsWith(ending); return ret; } diff --git a/dist/es/plugins/replication-graphql/index.js b/dist/es/plugins/replication-graphql/index.js index 63af7b6afb8..d3b1423ae07 100644 --- a/dist/es/plugins/replication-graphql/index.js +++ b/dist/es/plugins/replication-graphql/index.js @@ -15,24 +15,18 @@ import _regeneratorRuntime from "@babel/runtime/regenerator"; import { BehaviorSubject, Subject, firstValueFrom } from 'rxjs'; import { filter } from 'rxjs/operators'; import GraphQLClient from 'graphql-client'; -import { promiseWait, flatClone, now } from '../../util'; +import { promiseWait, getHeightOfRevision, flatClone } from '../../util'; import { addRxPlugin } from '../../core'; import { hash } from '../../util'; -import { DEFAULT_MODIFIER, wasRevisionfromPullReplication, createRevisionForPulledDocument, getDocsWithRevisionsFromPouch } from './helper'; +import { DEFAULT_MODIFIER, wasRevisionfromPullReplication, createRevisionForPulledDocument } from './helper'; import { setLastPushSequence, getLastPullDocument, setLastPullDocument, getChangesSinceLastPushSequence } from './crawling-checkpoint'; -import { RxDBWatchForChangesPlugin } from '../watch-for-changes'; import { RxDBLeaderElectionPlugin } from '../leader-election'; -import { changeEventfromPouchChange } from '../../rx-change-event'; import { overwritable } from '../../overwritable'; +import { getDocumentDataOfRxChangeEvent } from '../../rx-change-event'; +import { _handleToStorageInstance } from '../../rx-collection-helper'; addRxPlugin(RxDBLeaderElectionPlugin); -/** - * add the watch-for-changes-plugin - * so pouchdb will emit events when something gets written to it - */ - -addRxPlugin(RxDBWatchForChangesPlugin); export var RxGraphQLReplicationState = /*#__PURE__*/function () { - function RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, lastPulledRevField, live, liveInterval, retryTime, syncRevisions) { + function RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, live, liveInterval, retryTime) { this._subjects = { recieved: new Subject(), // all documents that are recieved from the endpoint @@ -63,11 +57,9 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { this.pull = pull; this.push = push; this.deletedFlag = deletedFlag; - this.lastPulledRevField = lastPulledRevField; this.live = live; this.liveInterval = liveInterval; this.retryTime = retryTime; - this.syncRevisions = syncRevisions; this.client = GraphQLClient({ url: url, headers: headers @@ -104,7 +96,7 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { return true; } - if (!this.live && this._subjects.initialReplicationComplete['_value']) { + if (!this.live && this._subjects.initialReplicationComplete.getValue()) { return true; } @@ -169,7 +161,7 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { _this2._subjects.active.next(false); - if (retryOnFail && !willRetry && _this2._subjects.initialReplicationComplete['_value'] === false) { + if (retryOnFail && !willRetry && _this2._subjects.initialReplicationComplete.getValue() === false) { _this2._subjects.initialReplicationComplete.next(true); } @@ -288,7 +280,9 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { return _run; }() /** - * @return true if sucessfull + * Pull all changes from the server, + * start from the last pulled change. + * @return true if sucessfull, false if something errored */ ; @@ -298,7 +292,7 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { var _runPull = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() { var _this4 = this; - var latestDocument, latestDocumentData, pullGraphQL, result, err, data, modified, docIds, docsWithRevisions, newLatestDocument; + var latestDocument, latestDocumentData, pullGraphQL, result, err, data, modified, newLatestDocument; return _regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { @@ -361,8 +355,17 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { case 27: // this assumes that there will be always only one property in the response // is this correct? - data = result.data[Object.keys(result.data)[0]]; - _context5.next = 30; + data = result.data[Object.keys(result.data)[0]]; // optimisation shortcut, do not proceed if there are no documents. + + if (!(data.length === 0)) { + _context5.next = 30; + break; + } + + return _context5.abrupt("return", true); + + case 30: + _context5.next = 32; return Promise.all(data.map( /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(doc) { return _regeneratorRuntime.wrap(function _callee4$(_context4) { @@ -388,63 +391,53 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { }; }())); - case 30: + case 32: modified = _context5.sent.filter(function (doc) { return !!doc; }); if (!overwritable.isDevMode()) { - _context5.next = 40; + _context5.next = 42; break; } - _context5.prev = 32; + _context5.prev = 34; modified.forEach(function (doc) { - var withoutDeleteFlag = Object.assign({}, doc); + var withoutDeleteFlag = flatClone(doc); delete withoutDeleteFlag[_this4.deletedFlag]; - delete withoutDeleteFlag._revisions; _this4.collection.schema.validate(withoutDeleteFlag); }); - _context5.next = 40; + _context5.next = 42; break; - case 36: - _context5.prev = 36; - _context5.t1 = _context5["catch"](32); + case 38: + _context5.prev = 38; + _context5.t1 = _context5["catch"](34); this._subjects.error.next(_context5.t1); return _context5.abrupt("return", false); - case 40: - docIds = modified.map(function (doc) { - return doc[_this4.collection.schema.primaryPath]; - }); - _context5.next = 43; - return getDocsWithRevisionsFromPouch(this.collection, docIds); - - case 43: - docsWithRevisions = _context5.sent; - + case 42: if (!this.isStopped()) { - _context5.next = 46; + _context5.next = 44; break; } return _context5.abrupt("return", true); - case 46: - _context5.next = 48; - return this.handleDocumentsFromRemote(modified, docsWithRevisions); + case 44: + _context5.next = 46; + return this.handleDocumentsFromRemote(modified); - case 48: + case 46: modified.map(function (doc) { return _this4._subjects.recieved.next(doc); }); if (!(modified.length === 0)) { - _context5.next = 53; + _context5.next = 51; break; } @@ -452,27 +445,27 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { } else {// console.log('RxGraphQLReplicationState._run(): no more docs and not live; complete = true'); } - _context5.next = 58; + _context5.next = 56; break; - case 53: + case 51: newLatestDocument = modified[modified.length - 1]; - _context5.next = 56; + _context5.next = 54; return setLastPullDocument(this.collection, this.endpointHash, newLatestDocument); - case 56: - _context5.next = 58; + case 54: + _context5.next = 56; return this.runPull(); - case 58: + case 56: return _context5.abrupt("return", true); - case 59: + case 57: case "end": return _context5.stop(); } } - }, _callee5, this, [[9, 23], [32, 36]]); + }, _callee5, this, [[9, 23], [34, 38]]); })); function runPull() { @@ -492,55 +485,45 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { var _runPush = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { var _this5 = this; - var changes, changesWithDocs, lastSuccessfullChange, i, changeWithDoc, pushObj, result, err; + var changesResult, changesWithDocs, lastSuccessfullChange, i, changeWithDoc, pushObj, result, err; return _regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; - return getChangesSinceLastPushSequence(this.collection, this.endpointHash, this.lastPulledRevField, this.push.batchSize, this.syncRevisions); + return getChangesSinceLastPushSequence(this.collection, this.endpointHash, this.push.batchSize); case 2: - changes = _context7.sent; + changesResult = _context7.sent; _context7.next = 5; - return Promise.all(changes.results.map( /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(change) { - var doc, seq; + return Promise.all(Array.from(changesResult.changedDocs.values()).map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(row) { + var changedDoc; return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: - doc = change['doc']; - doc[_this5.deletedFlag] = !!change['deleted']; - delete doc._deleted; - delete doc._attachments; - delete doc[_this5.lastPulledRevField]; - - if (!_this5.syncRevisions) { - delete doc._rev; - } - - _context6.next = 8; - return _this5.push.modifier(doc); + changedDoc = row.doc; + _context6.next = 3; + return _this5.push.modifier(changedDoc); - case 8: - doc = _context6.sent; + case 3: + changedDoc = _context6.sent; - if (doc) { - _context6.next = 11; + if (changedDoc) { + _context6.next = 6; break; } return _context6.abrupt("return", null); - case 11: - seq = change.seq; + case 6: return _context6.abrupt("return", { - doc: doc, - seq: seq + doc: changedDoc, + sequence: row.sequence }); - case 13: + case 7: case "end": return _context6.stop(); } @@ -555,7 +538,7 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { case 5: changesWithDocs = _context7.sent.filter(function (doc) { - return doc; + return !!doc; }); lastSuccessfullChange = null; _context7.prev = 7; @@ -563,81 +546,87 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { case 9: if (!(i < changesWithDocs.length)) { - _context7.next = 32; + _context7.next = 33; break; } - changeWithDoc = changesWithDocs[i]; - _context7.next = 13; + changeWithDoc = changesWithDocs[i]; // TODO _deleted should be required on type RxDocumentData + // so we do not need this check here + + if (!changeWithDoc.doc.hasOwnProperty('_deleted')) { + changeWithDoc.doc._deleted = false; + } + + _context7.next = 14; return this.push.queryBuilder(changeWithDoc.doc); - case 13: + case 14: pushObj = _context7.sent; - _context7.next = 16; + _context7.next = 17; return this.client.query(pushObj.query, pushObj.variables); - case 16: + case 17: result = _context7.sent; if (!result.errors) { - _context7.next = 27; + _context7.next = 28; break; } if (!(typeof result.errors === 'string')) { - _context7.next = 22; + _context7.next = 23; break; } throw new Error(result.errors); - case 22: + case 23: err = new Error('unknown errors occured - see innerErrors for more details'); err.innerErrors = result.errors; throw err; - case 25: - _context7.next = 29; + case 26: + _context7.next = 30; break; - case 27: + case 28: this._subjects.send.next(changeWithDoc.doc); lastSuccessfullChange = changeWithDoc; - case 29: + case 30: i++; _context7.next = 9; break; - case 32: - _context7.next = 41; + case 33: + _context7.next = 42; break; - case 34: - _context7.prev = 34; + case 35: + _context7.prev = 35; _context7.t0 = _context7["catch"](7); if (!lastSuccessfullChange) { - _context7.next = 39; + _context7.next = 40; break; } - _context7.next = 39; - return setLastPushSequence(this.collection, this.endpointHash, lastSuccessfullChange.seq); + _context7.next = 40; + return setLastPushSequence(this.collection, this.endpointHash, lastSuccessfullChange.sequence); - case 39: + case 40: this._subjects.error.next(_context7.t0); return _context7.abrupt("return", false); - case 41: - _context7.next = 43; - return setLastPushSequence(this.collection, this.endpointHash, changes.last_seq); + case 42: + _context7.next = 44; + return setLastPushSequence(this.collection, this.endpointHash, changesResult.lastSequence); - case 43: - if (!(changes.results.length === 0)) { - _context7.next = 47; + case 44: + if (!(changesResult.changedDocs.size === 0)) { + _context7.next = 48; break; } @@ -645,22 +634,22 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { } else {// console.log('RxGraphQLReplicationState._runPull(): no more docs to push and not live; complete = true'); } - _context7.next = 49; + _context7.next = 50; break; - case 47: - _context7.next = 49; + case 48: + _context7.next = 50; return this.runPush(); - case 49: + case 50: return _context7.abrupt("return", true); - case 50: + case 51: case "end": return _context7.stop(); } } - }, _callee7, this, [[7, 34]]); + }, _callee7, this, [[7, 35]]); })); function runPush() { @@ -671,67 +660,64 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { }(); _proto.handleDocumentsFromRemote = /*#__PURE__*/function () { - var _handleDocumentsFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(docs, docsWithRevisions) { + var _handleDocumentsFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(docs) { var _this6 = this; - var toPouchDocs, _iterator, _step, doc, deletedValue, toPouch, primaryValue, pouchState, newRevision, newRevisionHeight, revisionId, startTime, endTime, _i, _toPouchDocs, tpd, originalDoc, cE; + var toStorageDocs, docIds, docsFromLocal, _iterator, _step, doc, documentId, deletedValue, docStateInLocalStorageInstance, newRevision, hasHeight, newRevisionHeight; return _regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: - toPouchDocs = []; + toStorageDocs = []; + docIds = docs.map(function (doc) { + return doc[_this6.collection.schema.primaryPath]; + }); + _context9.next = 4; + return this.collection.storageInstance.findDocumentsById(docIds, true); + + case 4: + docsFromLocal = _context9.sent; for (_iterator = _createForOfIteratorHelperLoose(docs); !(_step = _iterator()).done;) { doc = _step.value; + documentId = doc[this.collection.schema.primaryPath]; deletedValue = doc[this.deletedFlag]; - toPouch = this.collection._handleToPouch(doc); - toPouch._deleted = deletedValue; - delete toPouch[this.deletedFlag]; - - if (!this.syncRevisions) { - primaryValue = toPouch._id; - pouchState = docsWithRevisions[primaryValue]; - newRevision = createRevisionForPulledDocument(this.endpointHash, toPouch); - - if (pouchState) { - newRevisionHeight = pouchState.revisions.start + 1; - revisionId = newRevision; - newRevision = newRevisionHeight + '-' + newRevision; - toPouch._revisions = { - start: newRevisionHeight, - ids: pouchState.revisions.ids - }; - - toPouch._revisions.ids.unshift(revisionId); - } else { - newRevision = '1-' + newRevision; - } - - toPouch._rev = newRevision; + doc._deleted = deletedValue; + delete doc[this.deletedFlag]; + docStateInLocalStorageInstance = docsFromLocal.get(documentId); + newRevision = createRevisionForPulledDocument(this.endpointHash, doc); + + if (docStateInLocalStorageInstance) { + hasHeight = getHeightOfRevision(docStateInLocalStorageInstance._rev); + newRevisionHeight = hasHeight + 1; + newRevision = newRevisionHeight + '-' + newRevision; } else { - toPouch[this.lastPulledRevField] = toPouch._rev; + newRevision = '1-' + newRevision; } - toPouchDocs.push({ - doc: toPouch, + doc._rev = newRevision; + toStorageDocs.push({ + doc: doc, deletedValue: deletedValue }); } - startTime = now(); - _context9.next = 5; + if (!(toStorageDocs.length > 0)) { + _context9.next = 9; + break; + } + + _context9.next = 9; return this.collection.database.lockedRun( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { return _regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; - return _this6.collection.pouch.bulkDocs(toPouchDocs.map(function (tpd) { - return tpd.doc; - }), { - new_edits: false - }); + return _this6.collection.storageInstance.bulkAddRevisions(toStorageDocs.map(function (row) { + return _handleToStorageInstance(_this6.collection, row.doc); + })); case 2: case "end": @@ -741,34 +727,10 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { }, _callee8); }))); - case 5: - endTime = now(); - /** - * because bulkDocs with new_edits: false - * does not stream changes to the pouchdb, - * we create the event and emit it, - * so other instances get informed about it - */ - - for (_i = 0, _toPouchDocs = toPouchDocs; _i < _toPouchDocs.length; _i++) { - tpd = _toPouchDocs[_i]; - originalDoc = flatClone(tpd.doc); - - if (tpd.deletedValue) { - originalDoc._deleted = tpd.deletedValue; - } else { - delete originalDoc._deleted; - } - - delete originalDoc[this.deletedFlag]; - delete originalDoc._revisions; - cE = changeEventfromPouchChange(originalDoc, this.collection, startTime, endTime); - this.collection.$emit(cE); - } - + case 9: return _context9.abrupt("return", true); - case 8: + case 10: case "end": return _context9.stop(); } @@ -776,7 +738,7 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function () { }, _callee9, this); })); - function handleDocumentsFromRemote(_x3, _x4) { + function handleDocumentsFromRemote(_x3) { return _handleDocumentsFromRemote.apply(this, arguments); } @@ -815,8 +777,6 @@ export function syncGraphQL(_ref5) { pull = _ref5.pull, push = _ref5.push, deletedFlag = _ref5.deletedFlag, - _ref5$lastPulledRevFi = _ref5.lastPulledRevField, - lastPulledRevField = _ref5$lastPulledRevFi === void 0 ? 'last_pulled_rev' : _ref5$lastPulledRevFi, _ref5$live = _ref5.live, live = _ref5$live === void 0 ? false : _ref5$live, _ref5$liveInterval = _ref5.liveInterval, @@ -824,9 +784,7 @@ export function syncGraphQL(_ref5) { _ref5$retryTime = _ref5.retryTime, retryTime = _ref5$retryTime === void 0 ? 1000 * 5 : _ref5$retryTime, _ref5$autoStart = _ref5.autoStart, - autoStart = _ref5$autoStart === void 0 ? true : _ref5$autoStart, - _ref5$syncRevisions = _ref5.syncRevisions, - syncRevisions = _ref5$syncRevisions === void 0 ? false : _ref5$syncRevisions; + autoStart = _ref5$autoStart === void 0 ? true : _ref5$autoStart; var collection = this; // fill in defaults for pull & push if (pull) { @@ -835,11 +793,9 @@ export function syncGraphQL(_ref5) { if (push) { if (!push.modifier) push.modifier = DEFAULT_MODIFIER; - } // ensure the collection is listening to plain-pouchdb writes - + } - collection.watchForChanges(); - var replicationState = new RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, lastPulledRevField, live, liveInterval, retryTime, syncRevisions); + var replicationState = new RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, live, liveInterval, retryTime); if (!autoStart) { return replicationState; @@ -900,13 +856,18 @@ export function syncGraphQL(_ref5) { if (push) { /** - * we have to use the rxdb changestream - * because the pouchdb.changes stream sometimes - * does not emit events or stucks + * When a document is written to the collection, + * we might have to run the replication run() once */ - var changeEventsSub = collection.$.subscribe(function (changeEvent) { - if (replicationState.isStopped()) return; - var rev = changeEvent.documentData._rev; + var changeEventsSub = collection.$.pipe(filter(function (cE) { + return !cE.isLocal; + })).subscribe(function (changeEvent) { + if (replicationState.isStopped()) { + return; + } + + var doc = getDocumentDataOfRxChangeEvent(changeEvent); + var rev = doc._rev; if (rev && !wasRevisionfromPullReplication(replicationState.endpointHash, rev)) { replicationState.run(); diff --git a/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js b/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js index ea137ee2f81..20f72595818 100644 --- a/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js +++ b/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js @@ -53,10 +53,14 @@ export function pushQueryBuilderFromRxSchema(collectionName, input) { var k = _ref[0], v = _ref[1]; - if (!input.ignoreInputKeys.includes(k)) { + if ( // skip if in ignoreInputKeys list + !input.ignoreInputKeys.includes(k) && // only use properties that are in the schema + input.schema.properties[k]) { sendDoc[k] = v; } - }); + }); // add deleted flag + + sendDoc[input.deletedFlag] = !!doc._deleted; var variables = (_variables = {}, _variables[collectionName] = sendDoc, _variables); return { query: query, diff --git a/dist/es/plugins/server.js b/dist/es/plugins/server.js index 2f59efe6f60..84b05bed656 100644 --- a/dist/es/plugins/server.js +++ b/dist/es/plugins/server.js @@ -1,16 +1,16 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _regeneratorRuntime from "@babel/runtime/regenerator"; +import * as os from 'os'; +import * as nodePath from 'path'; import express from 'express'; import corsFn from 'cors'; -import { PouchDB } from '../pouch-db'; +import { addPouchPlugin, PouchDB } from '../plugins/pouchdb'; import { newRxError } from '../rx-error'; -import { addRxPlugin } from '../core'; -import { RxDBReplicationPlugin } from './replication'; -addRxPlugin(RxDBReplicationPlugin); -import { RxDBWatchForChangesPlugin } from './watch-for-changes'; -addRxPlugin(RxDBWatchForChangesPlugin); +import { addRxPlugin, flatClone } from '../core'; +import { RxDBReplicationCouchDBPlugin } from './replication-couchdb'; +addRxPlugin(RxDBReplicationCouchDBPlugin); import PouchAdapterHttp from 'pouchdb-adapter-http'; -addRxPlugin(PouchAdapterHttp); +addPouchPlugin(PouchAdapterHttp); var ExpressPouchDB; try { @@ -41,9 +41,16 @@ var getPrefix = function getPrefix(db) { }); splitted.pop(); // last was the name - if (splitted.length === 0) return ''; + if (splitted.length === 0) { + return ''; + } + var ret = splitted.join('/') + '/'; - if (db.name.startsWith('/')) ret = '/' + ret; + + if (db.name.startsWith('/')) { + ret = '/' + ret; + } + return ret; }; /** @@ -52,7 +59,6 @@ var getPrefix = function getPrefix(db) { function tunnelCollectionPath(db, path, app, colName) { - db[colName].watchForChanges(); var pathWithSlash = path.endsWith('/') ? path : path + '/'; var collectionPath = pathWithSlash + colName; app.use(collectionPath, /*#__PURE__*/function () { @@ -104,129 +110,172 @@ function tunnelCollectionPath(db, path, app, colName) { }()); } -export function spawnServer(_ref2) { - var _ref2$path = _ref2.path, - path = _ref2$path === void 0 ? '/db' : _ref2$path, - _ref2$port = _ref2.port, - port = _ref2$port === void 0 ? 3000 : _ref2$port, - _ref2$cors = _ref2.cors, - cors = _ref2$cors === void 0 ? false : _ref2$cors, - _ref2$startServer = _ref2.startServer, - startServer = _ref2$startServer === void 0 ? true : _ref2$startServer, - _ref2$pouchdbExpressO = _ref2.pouchdbExpressOptions, - pouchdbExpressOptions = _ref2$pouchdbExpressO === void 0 ? {} : _ref2$pouchdbExpressO; - var db = this; - var collectionsPath = startServer ? path : '/'; - if (!SERVERS_OF_DB.has(db)) SERVERS_OF_DB.set(db, []); - var pseudo = PouchDB.defaults({ - adapter: db.adapter, - prefix: getPrefix(db), - log: false - }); - var app = express(); - APP_OF_DB.set(db, app); // tunnel requests so collection-names can be used as paths - - Object.keys(db.collections).forEach(function (colName) { - return tunnelCollectionPath(db, collectionsPath, app, colName); - }); // remember to throw error if collection is created after the server is already there - - DBS_WITH_SERVER.add(db); - - if (cors) { - app.use(corsFn({ - 'origin': function origin(_origin, callback) { - var originToSend = _origin || '*'; - callback(null, originToSend); - }, - 'credentials': true, - 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT' - })); - } +export function spawnServer(_x4) { + return _spawnServer.apply(this, arguments); +} +/** + * when a server is created, no more collections can be spawned + */ - var pouchApp = ExpressPouchDB(pseudo, pouchdbExpressOptions); - app.use(collectionsPath, pouchApp); - var server = null; - var startupPromise = Promise.resolve(); - - if (startServer) { - /** - * Listen for errors on server startup. - * TODO in the next major release we should make db.server() async - * and properly handle the error instead of returning a startupPromise - */ - startupPromise = new Promise(function (res, rej) { - var answered = false; - server = app.listen(port, function () { - if (!answered) { - answered = true; - res(); - } - }); - server.on('error', function (err) { - if (!answered) { - answered = true; - rej(err); - } - }); - }); - SERVERS_OF_DB.get(db).push(server); - /** - * When the database has no documents, there is no db file - * and so the replication would not work. - * This is a hack which ensures that the couchdb instance exists - * and we can replicate even if there is no document in the beginning. - */ - - Promise.all(Object.values(db.collections).map( /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(collection) { - var url, pingDb; - return _regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - url = 'http://localhost:' + port + collectionsPath + '/' + collection.name; - _context2.prev = 1; - pingDb = new PouchDB(url); - _context2.next = 5; - return pingDb.info(); - - case 5: - _context2.next = 7; - return pingDb.close(); - - case 7: - _context2.next = 11; - break; +function _spawnServer() { + _spawnServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref2) { + var _ref2$path, path, _ref2$port, port, _ref2$cors, cors, _ref2$startServer, startServer, _ref2$pouchdbExpressO, pouchdbExpressOptions, db, collectionsPath, storage, pseudo, app, usePouchExpressOptions, pouchApp, server, startupPromise, response; - case 9: - _context2.prev = 9; - _context2.t0 = _context2["catch"](1); + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _ref2$path = _ref2.path, path = _ref2$path === void 0 ? '/db' : _ref2$path, _ref2$port = _ref2.port, port = _ref2$port === void 0 ? 3000 : _ref2$port, _ref2$cors = _ref2.cors, cors = _ref2$cors === void 0 ? false : _ref2$cors, _ref2$startServer = _ref2.startServer, startServer = _ref2$startServer === void 0 ? true : _ref2$startServer, _ref2$pouchdbExpressO = _ref2.pouchdbExpressOptions, pouchdbExpressOptions = _ref2$pouchdbExpressO === void 0 ? {} : _ref2$pouchdbExpressO; + db = this; + collectionsPath = startServer ? path : '/'; - case 11: - case "end": - return _context2.stop(); + if (!SERVERS_OF_DB.has(db)) { + SERVERS_OF_DB.set(db, []); } - } - }, _callee2, null, [[1, 9]]); - })); - return function (_x4) { - return _ref3.apply(this, arguments); - }; - }())); - } + storage = db.storage; + + if (storage.adapter) { + _context3.next = 7; + break; + } + + throw new Error('The RxDB server plugin only works with pouchdb storage.'); + + case 7: + pseudo = PouchDB.defaults({ + adapter: storage.adapter, + prefix: getPrefix(db), + log: false + }); + app = express(); + APP_OF_DB.set(db, app); + Object.keys(db.collections).forEach(function (colName) { + // tunnel requests so collection-names can be used as paths + tunnelCollectionPath(db, collectionsPath, app, colName); + }); // remember to throw error if collection is created after the server is already there + + DBS_WITH_SERVER.add(db); + + if (cors) { + app.use(corsFn({ + 'origin': function origin(_origin, callback) { + var originToSend = _origin || '*'; + callback(null, originToSend); + }, + 'credentials': true, + 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT' + })); + } + /** + * Overwrite the defaults of PouchDBExpressServerOptions. + * In RxDB the defaults should not polute anything with folders so we store the config in memory + * and the logs in the tmp folder of the os. + */ + + + usePouchExpressOptions = flatClone(pouchdbExpressOptions); + + if (typeof usePouchExpressOptions.inMemoryConfig === 'undefined') { + usePouchExpressOptions.inMemoryConfig = true; + } + + if (typeof usePouchExpressOptions.logPath === 'undefined') { + usePouchExpressOptions.logPath = nodePath.join(os.tmpdir(), 'rxdb-server-log.txt'); + } - var response = { - app: app, - pouchApp: pouchApp, - server: server, - startupPromise: startupPromise - }; - return response; + pouchApp = ExpressPouchDB(pseudo, usePouchExpressOptions); + app.use(collectionsPath, pouchApp); + server = null; + startupPromise = Promise.resolve(); + + if (startServer) { + /** + * Listen for errors on server startup. + * and properly handle the error instead of returning a startupPromise + */ + startupPromise = new Promise(function (res, rej) { + var answered = false; + server = app.listen(port, function () { + if (!answered) { + answered = true; + res(); + } + }); + server.on('error', function (err) { + if (!answered) { + answered = true; + rej(err); + } + }); + }); + SERVERS_OF_DB.get(db).push(server); + /** + * When the database has no documents, there is no db file + * and so the replication would not work. + * This is a hack which ensures that the couchdb instance exists + * and we can replicate even if there is no document in the beginning. + */ + + Promise.all(Object.values(db.collections).map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(collection) { + var url, pingDb; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + url = 'http://localhost:' + port + collectionsPath + '/' + collection.name; + _context2.prev = 1; + pingDb = new PouchDB(url); + _context2.next = 5; + return pingDb.info(); + + case 5: + _context2.next = 7; + return pingDb.close(); + + case 7: + _context2.next = 11; + break; + + case 9: + _context2.prev = 9; + _context2.t0 = _context2["catch"](1); + + case 11: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[1, 9]]); + })); + + return function (_x5) { + return _ref3.apply(this, arguments); + }; + }())); + } + + _context3.next = 23; + return startupPromise; + + case 23: + response = { + app: app, + pouchApp: pouchApp, + server: server + }; + return _context3.abrupt("return", response); + + case 25: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + return _spawnServer.apply(this, arguments); } -/** - * when a server is created, no more collections can be spawned - */ function ensureNoMoreCollections(args) { if (DBS_WITH_SERVER.has(args.database)) { diff --git a/dist/es/plugins/update.js b/dist/es/plugins/update.js index 68faf3b03b0..623927b5f65 100644 --- a/dist/es/plugins/update.js +++ b/dist/es/plugins/update.js @@ -11,7 +11,9 @@ export function update(updateObj) { } export function RxQueryUpdate(updateObj) { return this.exec().then(function (docs) { - if (!docs) return null; + if (!docs) { + return null; + } if (Array.isArray(docs)) { return Promise.all(docs.map(function (doc) { diff --git a/dist/es/plugins/watch-for-changes.js b/dist/es/plugins/watch-for-changes.js deleted file mode 100644 index 98f498b135b..00000000000 --- a/dist/es/plugins/watch-for-changes.js +++ /dev/null @@ -1,103 +0,0 @@ -import { fromEvent } from 'rxjs'; -import { map } from 'rxjs/operators'; -import { promiseWait, nextTick, now } from '../util'; -import { changeEventfromPouchChange } from '../rx-change-event'; - -/** - * listens to changes of the internal pouchdb - * and ensures they are emitted to the internal RxChangeEvent-Stream - */ -export function watchForChanges() { - var _this = this; - - // do not call twice on same collection - if (this.synced) return; - this.synced = true; - this._watchForChangesUnhandled = new Set(); - /** - * this will grap the changes and publish them to the rx-stream - * this is to ensure that changes from 'synced' dbs will be published - */ - - var pouch$ = fromEvent(this.pouch.changes({ - since: 'now', - live: true, - include_docs: true - }), 'change').pipe(map(function (ar) { - return ar[0]; - }) // rxjs6.x fires an array for whatever reason - ).subscribe(function (change) { - var resPromise = _handleSingleChange(_this, change); // add and remove to the Set so RxReplicationState.complete$ can know when all events where handled - - - _this._watchForChangesUnhandled.add(resPromise); - - resPromise.then(function () { - _this._watchForChangesUnhandled["delete"](resPromise); - }); - }); - - this._subs.push(pouch$); -} -/** - * handles a single change-event - * and ensures that it is not already handled - */ - -function _handleSingleChange(collection, change) { - if (change.id.charAt(0) === '_') { - // do not handle changes of internal docs - return Promise.resolve(false); - } - - var startTime = now(); - var endTime = now(); // wait 2 ticks and 20 ms to give the internal event-handling time to run - - return promiseWait(20).then(function () { - return nextTick(); - }).then(function () { - return nextTick(); - }).then(function () { - var docData = change.doc; // already handled by internal event-stream - - if (collection._changeEventBuffer.hasChangeWithRevision(docData._rev)) { - return false; - } - - var cE = changeEventfromPouchChange(docData, collection, startTime, endTime); - collection.$emit(cE); - return true; - }); -} -/** - * After a collection is destroyed, - * we must await all promises of collection._watchForChangesUnhandled - * to ensure nothing is running anymore. - */ - - -function postDestroyRxCollection(collection) { - var unhandled = collection._watchForChangesUnhandled; - - if (!unhandled) { - return Promise.resolve(); - } - - return Promise.all(Array.from(unhandled)); -} - -export var rxdb = true; -export var prototypes = { - RxCollection: function RxCollection(proto) { - proto.watchForChanges = watchForChanges; - } -}; -export var RxDBWatchForChangesPlugin = { - name: 'watch-for-changes', - rxdb: rxdb, - prototypes: prototypes, - hooks: { - postDestroyRxCollection: postDestroyRxCollection - } -}; -//# sourceMappingURL=watch-for-changes.js.map \ No newline at end of file diff --git a/dist/es/pouch-db.js b/dist/es/pouch-db.js deleted file mode 100644 index 8964a0f6d50..00000000000 --- a/dist/es/pouch-db.js +++ /dev/null @@ -1,172 +0,0 @@ -import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; -import _regeneratorRuntime from "@babel/runtime/regenerator"; - -/** - * this handles the pouchdb-instance - * to easy add modules and manipulate things - * Adapters can be found here: - * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules - */ -import PouchDBCore from 'pouchdb-core'; // pouchdb-find - -import PouchDBFind from 'pouchdb-find'; -import { binaryMd5 } from 'pouchdb-md5'; -PouchDBCore.plugin(PouchDBFind); -/* -// comment in to debug -const pouchdbDebug = require('pouchdb-debug'); -PouchDB.plugin(pouchdbDebug); -PouchDB.debug.enable('*'); -*/ - -import { newRxError, newRxTypeError } from './rx-error'; -import { isFolderPath } from './util'; -/** - * get the number of all undeleted documents - */ - -export function countAllUndeleted(pouchdb) { - return pouchdb.allDocs({ - include_docs: false, - attachments: false - }).then(function (docs) { - return docs.rows.filter(function (row) { - return !row.id.startsWith('_design/'); - }).length; - }); -} -/** - * get a batch of documents from the pouch-instance - */ - -export function getBatch(pouchdb, limit) { - if (limit <= 1) { - throw newRxError('P1', { - limit: limit - }); - } - - return pouchdb.allDocs({ - include_docs: true, - attachments: false, - limit: limit - }).then(function (docs) { - return docs.rows.map(function (row) { - return row.doc; - }).filter(function (doc) { - return !doc._id.startsWith('_design'); - }); - }); -} -/** - * check if the given module is a leveldown-adapter - * throws if not - */ - -export function isLevelDown(adapter) { - if (!adapter || typeof adapter.super_ !== 'function') { - throw newRxError('UT4', { - adapter: adapter - }); - } -} -var validCouchDBStringRegexStr = '^[a-z][_$a-z0-9]*$'; -var validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr); -/** - * validates that a given string is ok to be used with couchdb-collection-names - * @link https://wiki.apache.org/couchdb/HTTP_database_API - * @throws {Error} - */ - -export function validateCouchDBString(name) { - if (typeof name !== 'string' || name.length === 0) { - throw newRxTypeError('UT1', { - name: name - }); - } // do not check, if foldername is given - - - if (isFolderPath(name)) { - return true; - } - - if (!name.match(validCouchDBStringRegex)) { - throw newRxError('UT2', { - regex: validCouchDBStringRegexStr, - givenName: name - }); - } - - return true; -} -/** - * get the correct function-name for pouchdb-replication - */ - -export function pouchReplicationFunction(pouch, _ref) { - var _ref$pull = _ref.pull, - pull = _ref$pull === void 0 ? true : _ref$pull, - _ref$push = _ref.push, - push = _ref$push === void 0 ? true : _ref$push; - if (pull && push) return pouch.sync.bind(pouch); - if (!pull && push) return pouch.replicate.to.bind(pouch); - if (pull && !push) return pouch.replicate.from.bind(pouch); - - if (!pull && !push) { - throw newRxError('UT3', { - pull: pull, - push: push - }); - } -} -/** - * create the same diggest as an attachment with that data - * would have - */ - -export function pouchAttachmentBinaryHash(data) { - return new Promise(function (res) { - binaryMd5(data, function (d) { - res('md5-' + d); - }); - }); -} -export function getNewestSequence(_x) { - return _getNewestSequence.apply(this, arguments); -} - -function _getNewestSequence() { - _getNewestSequence = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(pouch) { - var pouchChanges; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return pouch.changes({ - live: false, - since: 0, - limit: 1, - descending: true, - include_docs: false - }); - - case 2: - pouchChanges = _context.sent; - return _context.abrupt("return", pouchChanges.last_seq); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - return _getNewestSequence.apply(this, arguments); -} - -export function isInstanceOf(obj) { - return obj instanceof PouchDBCore; -} -export var PouchDB = PouchDBCore; -//# sourceMappingURL=pouch-db.js.map \ No newline at end of file diff --git a/dist/es/rx-change-event.js b/dist/es/rx-change-event.js index 23d598761fc..3596158a267 100644 --- a/dist/es/rx-change-event.js +++ b/dist/es/rx-change-event.js @@ -2,108 +2,46 @@ * RxChangeEvents a emitted when something in the database changes * they can be grabbed by the observables of database, collection and document */ -export var RxChangeEvent = /*#__PURE__*/function () { - function RxChangeEvent(operation, documentId, documentData, databaseToken, collectionName, isLocal, - /** - * timestam on when the operation was triggered - * and when it was finished - * This is optional because we do not have this time - * for events that come from pouchdbs changestream. - */ - startTime, endTime, previousData, rxDocument) { - this.operation = operation; - this.documentId = documentId; - this.documentData = documentData; - this.databaseToken = databaseToken; - this.collectionName = collectionName; - this.isLocal = isLocal; - this.startTime = startTime; - this.endTime = endTime; - this.previousData = previousData; - this.rxDocument = rxDocument; +import { overwritable } from './overwritable'; +export function getDocumentDataOfRxChangeEvent(rxChangeEvent) { + if (rxChangeEvent.documentData) { + return rxChangeEvent.documentData; + } else { + return rxChangeEvent.previousDocumentData; } - - var _proto = RxChangeEvent.prototype; - - _proto.isIntern = function isIntern() { - if (this.collectionName && this.collectionName.charAt(0) === '_') { - return true; - } else { - return false; - } - }; - - _proto.toJSON = function toJSON() { - var ret = { - operation: this.operation, - documentId: this.documentId, - documentData: this.documentData, - previousData: this.previousData ? this.previousData : undefined, - databaseToken: this.databaseToken, - collectionName: this.collectionName, - isLocal: this.isLocal, - startTime: this.startTime, - endTime: this.endTime - }; - return ret; - }; - - _proto.toEventReduceChangeEvent = function toEventReduceChangeEvent() { - switch (this.operation) { - case 'INSERT': - return { - operation: this.operation, - id: this.documentId, - doc: this.documentData, - previous: null - }; - - case 'UPDATE': - return { - operation: this.operation, - id: this.documentId, - doc: this.documentData, - previous: this.previousData ? this.previousData : 'UNKNOWN' - }; - - case 'DELETE': - return { - operation: this.operation, - id: this.documentId, - doc: null, - previous: this.previousData - }; - } - }; - - return RxChangeEvent; -}(); -export function changeEventfromPouchChange(changeDoc, collection, startTime, // time when the event was streamed out of pouchdb -endTime) { - var operation = changeDoc._rev.startsWith('1-') ? 'INSERT' : 'UPDATE'; - - if (changeDoc._deleted) { - operation = 'DELETE'; - } // decompress / primarySwap - - - var doc = collection._handleFromPouch(changeDoc); - - var documentId = doc[collection.schema.primaryPath]; - var cE = new RxChangeEvent(operation, documentId, doc, collection.database.token, collection.name, false, startTime, endTime); - return cE; -} -export function createInsertEvent(collection, docData, startTime, endTime, doc) { - var ret = new RxChangeEvent('INSERT', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, null, doc); - return ret; } -export function createUpdateEvent(collection, docData, previous, startTime, endTime, rxDocument) { - return new RxChangeEvent('UPDATE', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, previous, rxDocument); -} -export function createDeleteEvent(collection, docData, previous, startTime, endTime, rxDocument) { - return new RxChangeEvent('DELETE', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, previous, rxDocument); +export function isRxChangeEventIntern(rxChangeEvent) { + if (rxChangeEvent.collectionName && rxChangeEvent.collectionName.charAt(0) === '_') { + return true; + } else { + return false; + } } -export function isInstanceOf(obj) { - return obj instanceof RxChangeEvent; +export function rxChangeEventToEventReduceChangeEvent(rxChangeEvent) { + switch (rxChangeEvent.operation) { + case 'INSERT': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: rxChangeEvent.documentData, + previous: null + }; + + case 'UPDATE': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: overwritable.deepFreezeWhenDevMode(rxChangeEvent.documentData), + previous: rxChangeEvent.previousDocumentData ? rxChangeEvent.previousDocumentData : 'UNKNOWN' + }; + + case 'DELETE': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: null, + previous: rxChangeEvent.previousDocumentData + }; + } } //# sourceMappingURL=rx-change-event.js.map \ No newline at end of file diff --git a/dist/es/rx-collection-helper.js b/dist/es/rx-collection-helper.js index 63dfb5cb14a..9d06e667f7f 100644 --- a/dist/es/rx-collection-helper.js +++ b/dist/es/rx-collection-helper.js @@ -1,51 +1,163 @@ -import { generateId } from './util'; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { flatClone } from './util'; import { newRxError } from './rx-error'; +import { runPluginHooks } from './hooks'; +import { getSingleDocument, writeSingle } from './rx-storage-helper'; + +/** + * Every write access on the storage engine, + * goes throught this method + * so we can run hooks and resolve stuff etc. + */ +export function writeToStorageInstance(_x, _x2) { + return _writeToStorageInstance.apply(this, arguments); +} /** - * wrappers for Pouch.put/get to handle keycompression etc + * wrappers to process document data beofre/after it goes to the storage instnace. + * Used to handle keycompression, encryption etc */ -export function _handleToPouch(col, data) { - data = col._crypter.encrypt(data); - data = col.schema.swapPrimaryToId(data); +function _writeToStorageInstance() { + _writeToStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(collection, writeRow) { + var overwrite, + toStorageInstance, + writeResult, + ret, + _args2 = arguments; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + overwrite = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; + toStorageInstance = { + previous: writeRow.previous ? _handleToStorageInstance(collection, flatClone(writeRow.previous)) : undefined, + document: _handleToStorageInstance(collection, flatClone(writeRow.document)) + }; - if (col.schema.doKeyCompression()) { - data = col._keyCompressor.compress(data); - } + case 2: + if (!true) { + _context2.next = 16; + break; + } + + _context2.prev = 3; + _context2.next = 6; + return collection.database.lockedRun(function () { + return writeSingle(collection.storageInstance, toStorageInstance); + }); + + case 6: + writeResult = _context2.sent; + // on success, just return the result + ret = _handleFromStorageInstance(collection, writeResult); + return _context2.abrupt("return", ret); + + case 11: + _context2.prev = 11; + _context2.t0 = _context2["catch"](3); + return _context2.delegateYield( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var useErr, primary, singleRes; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + useErr = _context2.t0; + primary = useErr.documentId; + + if (!(overwrite && useErr.status === 409)) { + _context.next = 11; + break; + } + + _context.next = 5; + return collection.database.lockedRun(function () { + return getSingleDocument(collection.storageInstance, primary); + }); + + case 5: + singleRes = _context.sent; + + if (singleRes) { + _context.next = 8; + break; + } + + throw newRxError('SNH'); + + case 8: + toStorageInstance.previous = singleRes; // now we can retry - return data; + _context.next = 16; + break; + + case 11: + if (!(useErr.status === 409)) { + _context.next = 15; + break; + } + + throw newRxError('COL19', { + id: primary, + pouchDbError: useErr, + data: writeRow + }); + + case 15: + throw useErr; + + case 16: + case "end": + return _context.stop(); + } + } + }, _callee); + })(), "t1", 14); + + case 14: + _context2.next = 2; + break; + + case 16: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[3, 11]]); + })); + return _writeToStorageInstance.apply(this, arguments); +} + +export function _handleToStorageInstance(col, data) { + data = col._crypter.encrypt(data); + var hookParams = { + collection: col, + doc: data + }; + runPluginHooks('preWriteToStorageInstance', hookParams); + return hookParams.doc; } -export function _handleFromPouch(col, data) { +export function _handleFromStorageInstance(col, data) { var noDecrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - data = col.schema.swapIdToPrimary(data); - if (col.schema.doKeyCompression()) data = col._keyCompressor.decompress(data); + var hookParams = { + collection: col, + doc: data + }; + runPluginHooks('postReadFromInstance', hookParams); if (noDecrypt) { - return data; + return hookParams.doc; } - data = col._crypter.decrypt(data); - return data; + return col._crypter.decrypt(hookParams.doc); } /** - * fills in the _id and the - * default data. - * This also clones the data + * fills in the default data. + * This also clones the data. */ export function fillObjectDataBeforeInsert(collection, data) { var useJson = collection.schema.fillObjectWithDefaults(data); - - if (useJson._id && collection.schema.primaryPath !== '_id') { - throw newRxError('COL2', { - data: data - }); - } // fill _id - - - if (collection.schema.primaryPath === '_id' && !useJson._id) { - useJson._id = generateId(); - } - return useJson; } //# sourceMappingURL=rx-collection-helper.js.map \ No newline at end of file diff --git a/dist/es/rx-collection.js b/dist/es/rx-collection.js index 5eeabedf8d0..47d2055489e 100644 --- a/dist/es/rx-collection.js +++ b/dist/es/rx-collection.js @@ -1,28 +1,27 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _createClass from "@babel/runtime/helpers/createClass"; import _regeneratorRuntime from "@babel/runtime/regenerator"; -import { filter, startWith, mergeMap, shareReplay } from 'rxjs/operators'; -import { ucfirst, nextTick, flatClone, promiseSeries, pluginMissing, now, ensureNotFalsy } from './util'; -import { validateCouchDBString } from './pouch-db'; -import { _handleToPouch as _handleToPouch2, _handleFromPouch as _handleFromPouch2, fillObjectDataBeforeInsert } from './rx-collection-helper'; +import { filter, startWith, mergeMap, shareReplay, map } from 'rxjs/operators'; +import { ucfirst, nextTick, flatClone, promiseSeries, pluginMissing, ensureNotFalsy, getFromMapOrThrow, clone } from './util'; +import { _handleToStorageInstance, _handleFromStorageInstance, fillObjectDataBeforeInsert, writeToStorageInstance } from './rx-collection-helper'; import { createRxQuery, _getDefaultQuery } from './rx-query'; import { isInstanceOf as isInstanceOfRxSchema, createRxSchema } from './rx-schema'; -import { createInsertEvent, createDeleteEvent } from './rx-change-event'; import { newRxError, newRxTypeError } from './rx-error'; import { createCrypter } from './crypter'; import { createDocCache } from './doc-cache'; import { createQueryCache, defaultCacheReplacementPolicy } from './query-cache'; import { createChangeEventBuffer } from './change-event-buffer'; -import { overwritable } from './overwritable'; import { runAsyncPluginHooks, runPluginHooks } from './hooks'; -import { createWithConstructor as createRxDocumentWithConstructor, isInstanceOf as isRxDocument } from './rx-document'; +import { createWithConstructor as createRxDocumentWithConstructor, isRxDocument } from './rx-document'; import { createRxDocument, getRxDocumentConstructor } from './rx-document-prototype-merge'; +import { storageChangeEventToRxChangeEvent } from './rx-storage-helper'; +import { validateDatabaseName } from './plugins/dev-mode/check-names'; var HOOKS_WHEN = ['pre', 'post']; var HOOKS_KEYS = ['insert', 'save', 'remove', 'create']; var hooksApplied = false; export var RxCollectionBase = /*#__PURE__*/function () { function RxCollectionBase(database, name, schema) { - var pouchSettings = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var instanceCreationOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var migrationStrategies = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var methods = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; var attachments = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; @@ -36,15 +35,17 @@ export var RxCollectionBase = /*#__PURE__*/function () { this.hooks = {}; this._subs = []; this._repStates = new Set(); - this.pouch = {}; + this.storageInstance = {}; + this.localDocumentsStore = {}; this._docCache = createDocCache(); this._queryCache = createQueryCache(); this._crypter = {}; + this._observable$ = {}; this._changeEventBuffer = {}; this.database = database; this.name = name; this.schema = schema; - this.pouchSettings = pouchSettings; + this.instanceCreationOptions = instanceCreationOptions; this.migrationStrategies = migrationStrategies; this.methods = methods; this.attachments = attachments; @@ -61,49 +62,95 @@ export var RxCollectionBase = /*#__PURE__*/function () { var _proto = RxCollectionBase.prototype; - _proto.prepare = function prepare( - /** - * set to true if the collection data already exists on this storage adapter - */ - wasCreatedBefore) { - var _this = this; + _proto.prepare = /*#__PURE__*/function () { + var _prepare = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee( + /** + * set to true if the collection data already exists on this storage adapter + */ + wasCreatedBefore) { + var _this = this; - this.pouch = this.database._spawnPouchDB(this.name, this.schema.version, this.pouchSettings); + var storageInstanceCreationParams, _yield$Promise$all, storageInstance, localDocumentsStore, subDocs, subLocalDocs; - if (this.schema.doKeyCompression()) { - this._keyCompressor = overwritable.createKeyCompressor(this.schema); - } // we trigger the non-blocking things first and await them later so we can do stuff in the mean time + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + storageInstanceCreationParams = { + databaseName: this.database.name, + collectionName: this.name, + schema: this.schema.jsonSchema, + options: this.instanceCreationOptions + }; + runPluginHooks('preCreateRxStorageInstance', storageInstanceCreationParams); + _context.next = 4; + return Promise.all([this.database.storage.createStorageInstance(storageInstanceCreationParams), this.database.storage.createKeyObjectStorageInstance(this.database.name, + /** + * Use a different collection name for the local documents instance + * so that the local docs can be kept while deleting the normal instance + * after migration. + */ + this.name + '-local', this.instanceCreationOptions)]); + + case 4: + _yield$Promise$all = _context.sent; + storageInstance = _yield$Promise$all[0]; + localDocumentsStore = _yield$Promise$all[1]; + this.storageInstance = storageInstance; + this.localDocumentsStore = localDocumentsStore; // we trigger the non-blocking things first and await them later so we can do stuff in the mean time + + this._crypter = createCrypter(this.database.password, this.schema); + this._observable$ = this.database.$.pipe(filter(function (event) { + return event.collectionName === _this.name; + })); + this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection); + subDocs = storageInstance.changeStream().pipe(map(function (storageEvent) { + return storageChangeEventToRxChangeEvent(false, storageEvent, _this.database, _this); + })).subscribe(function (cE) { + _this.$emit(cE); + }); - /** - * Sometimes pouchdb emits before the instance is useable. - * To prevent random errors, we wait until the .info() call resolved - */ + this._subs.push(subDocs); + subLocalDocs = this.localDocumentsStore.changeStream().pipe(map(function (storageEvent) { + return storageChangeEventToRxChangeEvent(true, storageEvent, _this.database, _this); + })).subscribe(function (cE) { + return _this.$emit(cE); + }); - var spawnedPouchPromise = wasCreatedBefore ? Promise.resolve() : this.pouch.info(); - /** - * if wasCreatedBefore we can assume that the indexes already exist - * because changing them anyway requires a schema-version change - */ + this._subs.push(subLocalDocs); + /** + * When a write happens to the collection + * we find the changed document in the docCache + * and tell it that it has to change its data. + */ - var createIndexesPromise = wasCreatedBefore ? Promise.resolve() : _prepareCreateIndexes(this.asRxCollection, spawnedPouchPromise); - this._crypter = createCrypter(this.database.password, this.schema); - this._observable$ = this.database.$.pipe(filter(function (event) { - return event.collectionName === _this.name; - })); - this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection); - this._subs.push(this._observable$.pipe(filter(function (cE) { - return !cE.isLocal; - })).subscribe(function (cE) { - // when data changes, send it to RxDocument in docCache - var doc = _this._docCache.get(cE.documentId); + this._subs.push(this._observable$.pipe(filter(function (cE) { + return !cE.isLocal; + })).subscribe(function (cE) { + // when data changes, send it to RxDocument in docCache + var doc = _this._docCache.get(cE.documentId); + + if (doc) { + doc._handleChangeEvent(cE); + } + })); - if (doc) doc._handleChangeEvent(cE); + case 17: + case "end": + return _context.stop(); + } + } + }, _callee, this); })); - return Promise.all([spawnedPouchPromise, createIndexesPromise]); - } // overwritte by migration-plugin + function prepare(_x) { + return _prepare.apply(this, arguments); + } + + return prepare; + }() // overwritte by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { @@ -128,296 +175,286 @@ export var RxCollectionBase = /*#__PURE__*/function () { return this.getDataMigrator().migratePromise(batchSize); } /** - * wrappers for Pouch.put/get to handle keycompression etc + * wrapps pouch-find */ ; - _proto._handleToPouch = function _handleToPouch(docData) { - return _handleToPouch2(this, docData); - }; + _proto._queryStorageInstance = + /*#__PURE__*/ + function () { + var _queryStorageInstance2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rxQuery, limit) { + var _this2 = this; + + var noDecrypt, + preparedQuery, + queryResult, + docs, + _args2 = arguments; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + noDecrypt = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; + preparedQuery = rxQuery.toJSON(); - _proto._handleFromPouch = function _handleFromPouch(docData) { - var noDecrypt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - return _handleFromPouch2(this, docData, noDecrypt); - } - /** - * every write on the pouchdb - * is tunneld throught this function - */ - ; + if (limit) { + preparedQuery['limit'] = limit; + } - _proto._pouchPut = function _pouchPut(obj) { - var _this2 = this; - - var overwrite = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - obj = this._handleToPouch(obj); - return this.database.lockedRun(function () { - return _this2.pouch.put(obj); - })["catch"](function (err) { - if (overwrite && err.status === 409) { - return _this2.database.lockedRun(function () { - return _this2.pouch.get(obj._id); - }).then(function (exist) { - obj._rev = exist._rev; - return _this2.database.lockedRun(function () { - return _this2.pouch.put(obj); - }); - }); - } else if (err.status === 409) { - throw newRxError('COL19', { - id: obj._id, - pouchDbError: err, - data: obj - }); - } else throw err; - }); - } - /** - * get document from pouchdb by its _id - */ - ; + _context2.next = 5; + return this.database.lockedRun(function () { + return _this2.storageInstance.query(preparedQuery); + }); - _proto._pouchGet = function _pouchGet(key) { - var _this3 = this; + case 5: + queryResult = _context2.sent; + docs = queryResult.documents.map(function (doc) { + return _handleFromStorageInstance(_this2, doc, noDecrypt); + }); + return _context2.abrupt("return", docs); - return this.pouch.get(key).then(function (doc) { - return _this3._handleFromPouch(doc); - }); + case 8: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function _queryStorageInstance(_x2, _x3) { + return _queryStorageInstance2.apply(this, arguments); + } + + return _queryStorageInstance; + }(); + + _proto.$emit = function $emit(changeEvent) { + return this.database.$emit(changeEvent); } /** - * wrapps pouch-find + * TODO internally call bulkInsert + * to not have duplicated code. */ ; - _proto._pouchFind = function _pouchFind(rxQuery, limit) { - var _this4 = this; + _proto.insert = + /*#__PURE__*/ + function () { + var _insert = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(json) { + var tempDoc, useJson, newDoc, insertResult; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + // inserting a temporary-document + tempDoc = null; - var noDecrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var compressedQueryJSON = rxQuery.keyCompress(); + if (!isRxDocument(json)) { + _context3.next = 6; + break; + } - if (limit) { - compressedQueryJSON['limit'] = limit; - } + tempDoc = json; - return this.database.lockedRun(function () { - return _this4.pouch.find(compressedQueryJSON); - }).then(function (docsCompressed) { - var docs = docsCompressed.docs.map(function (doc) { - return _this4._handleFromPouch(doc, noDecrypt); - }); - return docs; - }); - }; + if (tempDoc._isTemporary) { + _context3.next = 5; + break; + } - _proto.$emit = function $emit(changeEvent) { - return this.database.$emit(changeEvent); - }; + throw newRxError('COL1', { + data: json + }); - _proto.insert = function insert(json) { - var _this5 = this; + case 5: + json = tempDoc.toJSON(); - // inserting a temporary-document - var tempDoc = null; + case 6: + useJson = fillObjectDataBeforeInsert(this, json); + newDoc = tempDoc; + _context3.next = 10; + return this._runHooks('pre', 'insert', useJson); + + case 10: + this.schema.validate(useJson); + _context3.next = 13; + return writeToStorageInstance(this, { + document: useJson + }); - if (isRxDocument(json)) { - tempDoc = json; + case 13: + insertResult = _context3.sent; - if (!tempDoc._isTemporary) { - throw newRxError('COL1', { - data: json - }); - } + if (tempDoc) { + tempDoc._dataSync$.next(insertResult); + } else { + newDoc = createRxDocument(this, insertResult); + } + + _context3.next = 17; + return this._runHooks('post', 'insert', useJson, newDoc); - json = tempDoc.toJSON(); + case 17: + return _context3.abrupt("return", newDoc); + + case 18: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function insert(_x4) { + return _insert.apply(this, arguments); } - var useJson = fillObjectDataBeforeInsert(this, json); - var newDoc = tempDoc; - var startTime; - var endTime; - return this._runHooks('pre', 'insert', useJson).then(function () { - _this5.schema.validate(useJson); + return insert; + }(); - startTime = now(); - return _this5._pouchPut(useJson); - }).then(function (insertResult) { - endTime = now(); - useJson[_this5.schema.primaryPath] = insertResult.id; - useJson._rev = insertResult.rev; + _proto.bulkInsert = /*#__PURE__*/function () { + var _bulkInsert = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(docsData) { + var _this3 = this; - if (tempDoc) { - tempDoc._dataSync$.next(useJson); - } else newDoc = createRxDocument(_this5, useJson); + var useDocs, docs, insertDocs, docsMap, results, successEntries, rxDocuments; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + useDocs = docsData.map(function (docData) { + var useDocData = fillObjectDataBeforeInsert(_this3, docData); + return useDocData; + }); + _context4.next = 3; + return Promise.all(useDocs.map(function (doc) { + return _this3._runHooks('pre', 'insert', doc).then(function () { + _this3.schema.validate(doc); - return _this5._runHooks('post', 'insert', useJson, newDoc); - }).then(function () { - // event - var emitEvent = createInsertEvent(_this5, useJson, startTime, endTime, newDoc); + return doc; + }); + })); - _this5.$emit(emitEvent); + case 3: + docs = _context4.sent; + insertDocs = docs.map(function (d) { + return { + document: _handleToStorageInstance(_this3, d) + }; + }); + docsMap = new Map(); + docs.forEach(function (d) { + docsMap.set(d[_this3.schema.primaryPath], d); + }); + _context4.next = 9; + return this.database.lockedRun(function () { + return _this3.storageInstance.bulkWrite(insertDocs); + }); - return newDoc; - }); - }; + case 9: + results = _context4.sent; + // create documents + successEntries = Array.from(results.success.entries()); + rxDocuments = successEntries.map(function (_ref) { + var key = _ref[0], + writtenDocData = _ref[1]; + var docData = getFromMapOrThrow(docsMap, key); + docData._rev = writtenDocData._rev; + var doc = createRxDocument(_this3, docData); + return doc; + }); + _context4.next = 14; + return Promise.all(rxDocuments.map(function (doc) { + return _this3._runHooks('post', 'insert', docsMap.get(doc.primary), doc); + })); - _proto.bulkInsert = function bulkInsert(docsData) { - var _this6 = this; + case 14: + return _context4.abrupt("return", { + success: rxDocuments, + error: Array.from(results.error.values()) + }); - var useDocs = docsData.map(function (docData) { - var useDocData = fillObjectDataBeforeInsert(_this6, docData); - return useDocData; - }); - return Promise.all(useDocs.map(function (doc) { - return _this6._runHooks('pre', 'insert', doc).then(function () { - _this6.schema.validate(doc); + case 15: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); - return doc; - }); - })).then(function (docs) { - var insertDocs = docs.map(function (d) { - return _this6._handleToPouch(d); - }); - var docsMap = new Map(); - docs.forEach(function (d) { - docsMap.set(d[_this6.schema.primaryPath], d); - }); - return _this6.database.lockedRun(function () { - var startTime = now(); - return _this6.pouch.bulkDocs(insertDocs).then(function (results) { - var okResults = results.filter(function (r) { - return r.ok; - }); // create documents - - var rxDocuments = okResults.map(function (r) { - var docData = docsMap.get(r.id); - docData._rev = r.rev; - var doc = createRxDocument(_this6, docData); - return doc; - }); - return Promise.all(rxDocuments.map(function (doc) { - return _this6._runHooks('post', 'insert', docsMap.get(doc.primary), doc); - })).then(function () { - var errorResults = results.filter(function (r) { - return !r.ok; - }); - return { - rxDocuments: rxDocuments, - errorResults: errorResults - }; - }); - }).then(function (_ref) { - var rxDocuments = _ref.rxDocuments, - errorResults = _ref.errorResults; - var endTime = now(); // emit events - - rxDocuments.forEach(function (doc) { - var emitEvent = createInsertEvent(_this6, doc.toJSON(true), startTime, endTime, doc); - - _this6.$emit(emitEvent); - }); - return { - success: rxDocuments, - error: errorResults - }; - }); - }); - }); - }; + function bulkInsert(_x5) { + return _bulkInsert.apply(this, arguments); + } + + return bulkInsert; + }(); _proto.bulkRemove = /*#__PURE__*/function () { - var _bulkRemove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(ids) { - var _this7 = this; + var _bulkRemove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(ids) { + var _this4 = this; - var rxDocumentMap, docsData, docsMap, removeDocs, startTime, results, endTime, okResults, rxDocuments; - return _regeneratorRuntime.wrap(function _callee2$(_context2) { + var rxDocumentMap, docsData, docsMap, removeDocs, results, successIds, rxDocuments; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context5.prev = _context5.next) { case 0: - _context2.next = 2; + _context5.next = 2; return this.findByIds(ids); case 2: - rxDocumentMap = _context2.sent; + rxDocumentMap = _context5.sent; docsData = []; docsMap = new Map(); Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { - var data = rxDocument.toJSON(true); + var data = clone(rxDocument.toJSON(true)); docsData.push(data); docsMap.set(rxDocument.primary, data); }); - _context2.next = 8; + _context5.next = 8; return Promise.all(docsData.map(function (doc) { - var primary = doc[_this7.schema.primaryPath]; - return _this7._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); + var primary = doc[_this4.schema.primaryPath]; + return _this4._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); })); case 8: - docsData.forEach(function (doc) { - return doc._deleted = true; - }); removeDocs = docsData.map(function (doc) { - return _this7._handleToPouch(doc); + var writeDoc = flatClone(doc); + writeDoc._deleted = true; + return { + previous: _handleToStorageInstance(_this4, doc), + document: _handleToStorageInstance(_this4, writeDoc) + }; }); - _context2.next = 12; - return this.database.lockedRun( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { - var bulkResults; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - startTime = now(); - _context.next = 3; - return _this7.pouch.bulkDocs(removeDocs); - - case 3: - bulkResults = _context.sent; - return _context.abrupt("return", bulkResults); - - case 5: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); - - case 12: - results = _context2.sent; - endTime = now(); - okResults = results.filter(function (r) { - return r.ok; + _context5.next = 11; + return this.database.lockedRun(function () { + return _this4.storageInstance.bulkWrite(removeDocs); }); - _context2.next = 17; - return Promise.all(okResults.map(function (r) { - return _this7._runHooks('post', 'remove', docsMap.get(r.id), rxDocumentMap.get(r.id)); - })); - case 17: - okResults.forEach(function (r) { - var rxDocument = rxDocumentMap.get(r.id); - var emitEvent = createDeleteEvent(_this7, docsMap.get(r.id), rxDocument._data, startTime, endTime, rxDocument); + case 11: + results = _context5.sent; + successIds = Array.from(results.success.keys()); // run hooks - _this7.$emit(emitEvent); - }); - rxDocuments = okResults.map(function (r) { - return rxDocumentMap.get(r.id); + _context5.next = 15; + return Promise.all(successIds.map(function (id) { + return _this4._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); + })); + + case 15: + rxDocuments = successIds.map(function (id) { + return rxDocumentMap.get(id); }); - return _context2.abrupt("return", { + return _context5.abrupt("return", { success: rxDocuments, - error: okResults.filter(function (r) { - return !r.ok; - }) + error: Array.from(results.error.values()) }); - case 20: + case 17: case "end": - return _context2.stop(); + return _context5.stop(); } } - }, _callee2, this); + }, _callee5, this); })); - function bulkRemove(_x) { + function bulkRemove(_x6) { return _bulkRemove.apply(this, arguments); } @@ -429,7 +466,7 @@ export var RxCollectionBase = /*#__PURE__*/function () { ; _proto.upsert = function upsert(json) { - var _this8 = this; + var _this5 = this; var useJson = flatClone(json); var primary = useJson[this.schema.primaryPath]; @@ -450,7 +487,7 @@ export var RxCollectionBase = /*#__PURE__*/function () { return existing; }); } else { - return _this8.insert(json); + return _this5.insert(json); } }); } @@ -460,7 +497,7 @@ export var RxCollectionBase = /*#__PURE__*/function () { ; _proto.atomicUpsert = function atomicUpsert(json) { - var _this9 = this; + var _this6 = this; var primary = json[this.schema.primaryPath]; @@ -480,13 +517,21 @@ export var RxCollectionBase = /*#__PURE__*/function () { } queue = queue.then(function () { - return _atomicUpsertEnsureRxDocumentExists(_this9, primary, json); + return _atomicUpsertEnsureRxDocumentExists(_this6, primary, json); }).then(function (wasInserted) { if (!wasInserted.inserted) { - return _atomicUpsertUpdate(wasInserted.doc, json).then(function () { - return nextTick(); - }) // tick here so the event can propagate + return _atomicUpsertUpdate(wasInserted.doc, json) + /** + * tick here so the event can propagate + * TODO we should not need that here + */ .then(function () { + return nextTick(); + }).then(function () { + return nextTick(); + }).then(function () { + return nextTick(); + }).then(function () { return wasInserted.doc; }); } else return wasInserted.doc; @@ -516,10 +561,10 @@ export var RxCollectionBase = /*#__PURE__*/function () { var query; if (typeof queryObj === 'string') { + var _selector; + query = createRxQuery('findOne', { - selector: { - _id: queryObj - } + selector: (_selector = {}, _selector[this.schema.primaryPath] = queryObj, _selector) }, this); } else { if (!queryObj) { @@ -551,19 +596,19 @@ export var RxCollectionBase = /*#__PURE__*/function () { _proto.findByIds = /*#__PURE__*/ function () { - var _findByIds = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(ids) { - var _this10 = this; + var _findByIds = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(ids) { + var _this7 = this; - var ret, mustBeQueried, result; - return _regeneratorRuntime.wrap(function _callee3$(_context3) { + var ret, mustBeQueried, docs; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context6.prev = _context6.next) { case 0: ret = new Map(); mustBeQueried = []; // first try to fill from docCache ids.forEach(function (id) { - var doc = _this10._docCache.get(id); + var doc = _this7._docCache.get(id); if (doc) { ret.set(id, doc); @@ -573,42 +618,33 @@ export var RxCollectionBase = /*#__PURE__*/function () { }); // find everything which was not in docCache if (!(mustBeQueried.length > 0)) { - _context3.next = 8; + _context6.next = 8; break; } - _context3.next = 6; - return this.pouch.allDocs({ - include_docs: true, - keys: mustBeQueried - }); + _context6.next = 6; + return this.storageInstance.findDocumentsById(mustBeQueried, false); case 6: - result = _context3.sent; - result.rows.forEach(function (row) { - if (!row.doc) { - // not found - return; - } - - var plainData = _this10._handleFromPouch(row.doc); - - var doc = createRxDocument(_this10, plainData); + docs = _context6.sent; + Array.from(docs.values()).forEach(function (docData) { + docData = _handleFromStorageInstance(_this7, docData); + var doc = createRxDocument(_this7, docData); ret.set(doc.primary, doc); }); case 8: - return _context3.abrupt("return", ret); + return _context6.abrupt("return", ret); case 9: case "end": - return _context3.stop(); + return _context6.stop(); } } - }, _callee3, this); + }, _callee6, this); })); - function findByIds(_x2) { + function findByIds(_x7) { return _findByIds.apply(this, arguments); } @@ -621,12 +657,12 @@ export var RxCollectionBase = /*#__PURE__*/function () { ; _proto.findByIds$ = function findByIds$(ids) { - var _this11 = this; + var _this8 = this; var currentValue = null; var lastChangeEvent = -1; var initialPromise = this.findByIds(ids).then(function (docsMap) { - lastChangeEvent = _this11._changeEventBuffer.counter; + lastChangeEvent = _this8._changeEventBuffer.counter; currentValue = docsMap; }); return this.$.pipe(startWith(null), mergeMap(function (ev) { @@ -641,32 +677,32 @@ export var RxCollectionBase = /*#__PURE__*/function () { * since the last subscription. */ mergeMap( /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(ev) { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(ev) { var resultMap, missedChangeEvents, newResult; - return _regeneratorRuntime.wrap(function _callee4$(_context4) { + return _regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context7.prev = _context7.next) { case 0: resultMap = ensureNotFalsy(currentValue); - missedChangeEvents = _this11._changeEventBuffer.getFrom(lastChangeEvent + 1); + missedChangeEvents = _this8._changeEventBuffer.getFrom(lastChangeEvent + 1); if (!(missedChangeEvents === null)) { - _context4.next = 10; + _context7.next = 10; break; } - _context4.next = 5; - return _this11.findByIds(ids); + _context7.next = 5; + return _this8.findByIds(ids); case 5: - newResult = _context4.sent; - lastChangeEvent = _this11._changeEventBuffer.counter; - Array.from(newResult.entries()).forEach(function (_ref4) { - var k = _ref4[0], - v = _ref4[1]; + newResult = _context7.sent; + lastChangeEvent = _this8._changeEventBuffer.counter; + Array.from(newResult.entries()).forEach(function (_ref3) { + var k = _ref3[0], + v = _ref3[1]; return resultMap.set(k, v); }); - _context4.next = 11; + _context7.next = 11; break; case 10: @@ -676,25 +712,25 @@ export var RxCollectionBase = /*#__PURE__*/function () { var op = rxChangeEvent.operation; if (op === 'INSERT' || op === 'UPDATE') { - resultMap.set(rxChangeEvent.documentId, _this11._docCache.get(rxChangeEvent.documentId)); + resultMap.set(rxChangeEvent.documentId, _this8._docCache.get(rxChangeEvent.documentId)); } else { resultMap["delete"](rxChangeEvent.documentId); } }); case 11: - return _context4.abrupt("return", resultMap); + return _context7.abrupt("return", resultMap); case 12: case "end": - return _context4.stop(); + return _context7.stop(); } } - }, _callee4); + }, _callee7); })); - return function (_x3) { - return _ref3.apply(this, arguments); + return function (_x8) { + return _ref2.apply(this, arguments); }; }()), filter(function (x) { return !!x; @@ -712,36 +748,26 @@ export var RxCollectionBase = /*#__PURE__*/function () { */ ; - _proto.dump = function dump() { + _proto.exportJSON = function exportJSON() { var _decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; throw pluginMissing('json-dump'); } /** * Import the parsed JSON export into the collection. - * @param _exportedJSON The previously exported data from the `.dump()` method. + * @param _exportedJSON The previously exported data from the `.exportJSON()` method. */ ; - _proto.importDump = function importDump(_exportedJSON) { + _proto.importJSON = function importJSON(_exportedJSON) { throw pluginMissing('json-dump'); } /** - * waits for external changes to the database - * and ensures they are emitted to the internal RxChangeEvent-Stream - * TODO this can be removed by listening to the pull-change-events of the RxReplicationState - */ - ; - - _proto.watchForChanges = function watchForChanges() { - throw pluginMissing('watch-for-changes'); - } - /** - * sync with another database + * sync with a CouchDB endpoint */ ; - _proto.sync = function sync(_syncOptions) { + _proto.syncCouchDB = function syncCouchDB(_syncOptions) { throw pluginMissing('replication'); } /** @@ -863,6 +889,8 @@ export var RxCollectionBase = /*#__PURE__*/function () { }; _proto.destroy = function destroy() { + var _this9 = this; + if (this.destroyed) { return Promise.resolve(false); } @@ -882,10 +910,12 @@ export var RxCollectionBase = /*#__PURE__*/function () { Array.from(this._repStates).forEach(function (replicationState) { return replicationState.cancel(); }); - delete this.database.collections[this.name]; - this.destroyed = true; - return runAsyncPluginHooks('postDestroyRxCollection', this).then(function () { - return true; + return this.storageInstance.close().then(function () { + delete _this9.database.collections[_this9.name]; + _this9.destroyed = true; + return runAsyncPluginHooks('postDestroyRxCollection', _this9).then(function () { + return true; + }); }); } /** @@ -926,11 +956,11 @@ export var RxCollectionBase = /*#__PURE__*/function () { }, { key: "onDestroy", get: function get() { - var _this12 = this; + var _this10 = this; if (!this._onDestroy) { this._onDestroy = new Promise(function (res) { - return _this12._onDestroyCall = res; + return _this10._onDestroyCall = res; }); } @@ -982,6 +1012,19 @@ function _atomicUpsertUpdate(doc, json) { function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { + /** + * Optimisation shortcut, + * first try to find the document in the doc-cache + */ + var docFromCache = rxCollection._docCache.get(primary); + + if (docFromCache) { + return Promise.resolve({ + doc: docFromCache, + inserted: false + }); + } + return rxCollection.findOne(primary).exec().then(function (doc) { if (!doc) { return rxCollection.insert(json).then(function (newDoc) { @@ -998,90 +1041,32 @@ function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { } }); } -/** - * creates the indexes in the pouchdb - */ - - -function _prepareCreateIndexes(rxCollection, spawnedPouchPromise) { - /** - * pouchdb does no check on already existing indexes - * which makes collection re-creation really slow on page reloads - * So we have to manually check if the index already exists - */ - return spawnedPouchPromise.then(function () { - return rxCollection.pouch.getIndexes(); - }).then(function (indexResult) { - var existingIndexes = new Set(); - indexResult.indexes.forEach(function (idx) { - return existingIndexes.add(idx.name); - }); - return existingIndexes; - }).then(function (existingIndexes) { - return Promise.all(rxCollection.schema.indexes.map(function (indexAr) { - var compressedIdx = indexAr.map(function (key) { - var primPath = rxCollection.schema.primaryPath; - var useKey = key === primPath ? '_id' : key; - - if (!rxCollection.schema.doKeyCompression()) { - return useKey; - } else { - var indexKey = rxCollection._keyCompressor.transformKey(useKey); - - return indexKey; - } - }); - var indexName = 'idx-rxdb-index-' + compressedIdx.join(','); - - if (existingIndexes.has(indexName)) { - // index already exists - return; - } - /** - * TODO - * we might have even better performance by doing a bulkDocs - * on index creation - */ - - - return spawnedPouchPromise.then(function () { - return rxCollection.pouch.createIndex({ - name: indexName, - ddoc: indexName, - index: { - fields: compressedIdx - } - }); - }); - })); - }); -} /** * creates and prepares a new collection */ -export function create(_ref5, wasCreatedBefore) { - var database = _ref5.database, - name = _ref5.name, - schema = _ref5.schema, - _ref5$pouchSettings = _ref5.pouchSettings, - pouchSettings = _ref5$pouchSettings === void 0 ? {} : _ref5$pouchSettings, - _ref5$migrationStrate = _ref5.migrationStrategies, - migrationStrategies = _ref5$migrationStrate === void 0 ? {} : _ref5$migrationStrate, - _ref5$autoMigrate = _ref5.autoMigrate, - autoMigrate = _ref5$autoMigrate === void 0 ? true : _ref5$autoMigrate, - _ref5$statics = _ref5.statics, - statics = _ref5$statics === void 0 ? {} : _ref5$statics, - _ref5$methods = _ref5.methods, - methods = _ref5$methods === void 0 ? {} : _ref5$methods, - _ref5$attachments = _ref5.attachments, - attachments = _ref5$attachments === void 0 ? {} : _ref5$attachments, - _ref5$options = _ref5.options, - options = _ref5$options === void 0 ? {} : _ref5$options, - _ref5$cacheReplacemen = _ref5.cacheReplacementPolicy, - cacheReplacementPolicy = _ref5$cacheReplacemen === void 0 ? defaultCacheReplacementPolicy : _ref5$cacheReplacemen; - validateCouchDBString(name); // ensure it is a schema-object +export function createRxCollection(_ref4, wasCreatedBefore) { + var database = _ref4.database, + name = _ref4.name, + schema = _ref4.schema, + _ref4$instanceCreatio = _ref4.instanceCreationOptions, + instanceCreationOptions = _ref4$instanceCreatio === void 0 ? {} : _ref4$instanceCreatio, + _ref4$migrationStrate = _ref4.migrationStrategies, + migrationStrategies = _ref4$migrationStrate === void 0 ? {} : _ref4$migrationStrate, + _ref4$autoMigrate = _ref4.autoMigrate, + autoMigrate = _ref4$autoMigrate === void 0 ? true : _ref4$autoMigrate, + _ref4$statics = _ref4.statics, + statics = _ref4$statics === void 0 ? {} : _ref4$statics, + _ref4$methods = _ref4.methods, + methods = _ref4$methods === void 0 ? {} : _ref4$methods, + _ref4$attachments = _ref4.attachments, + attachments = _ref4$attachments === void 0 ? {} : _ref4$attachments, + _ref4$options = _ref4.options, + options = _ref4$options === void 0 ? {} : _ref4$options, + _ref4$cacheReplacemen = _ref4.cacheReplacementPolicy, + cacheReplacementPolicy = _ref4$cacheReplacemen === void 0 ? defaultCacheReplacementPolicy : _ref4$cacheReplacemen; + validateDatabaseName(name); // ensure it is a schema-object if (!isInstanceOfRxSchema(schema)) { schema = createRxSchema(schema); @@ -1094,12 +1079,12 @@ export function create(_ref5, wasCreatedBefore) { funName: funName }); }); - var collection = new RxCollectionBase(database, name, schema, pouchSettings, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics); + var collection = new RxCollectionBase(database, name, schema, instanceCreationOptions, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics); return collection.prepare(wasCreatedBefore).then(function () { // ORM add statics - Object.entries(statics).forEach(function (_ref6) { - var funName = _ref6[0], - fun = _ref6[1]; + Object.entries(statics).forEach(function (_ref5) { + var funName = _ref5[0], + fun = _ref5[1]; Object.defineProperty(collection, funName, { get: function get() { return fun.bind(collection); @@ -1118,12 +1103,7 @@ export function create(_ref5, wasCreatedBefore) { return collection; }); } -export function isInstanceOf(obj) { +export function isRxCollection(obj) { return obj instanceof RxCollectionBase; } -export default { - create: create, - isInstanceOf: isInstanceOf, - RxCollectionBase: RxCollectionBase -}; //# sourceMappingURL=rx-collection.js.map \ No newline at end of file diff --git a/dist/es/rx-database-internal-store.js b/dist/es/rx-database-internal-store.js deleted file mode 100644 index 03f57d84c8e..00000000000 --- a/dist/es/rx-database-internal-store.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * In this file we handle all accesses to the internal store of the database - * This store is used to save hashes and checksums and metadata - * ATM this only works with PouchDB but in the future - * it should work by using the storage.interface - */ -import { LOCAL_PREFIX } from './util'; -// will be typed when we have more then one -export var INTERNAL_STORAGE_NAME = '_rxdb_internal'; -/** - * returns to local document with the given id - * or null if not exists - */ - -export function getLocalDocument(storageInstance, id) { - return storageInstance.get(LOCAL_PREFIX + id)["catch"](function () { - return null; - }); -} -export function setLocalDocument(storageInstance, id, value) { - return storageInstance.put({ - _id: id, - value: value - }).then(function () {}); -} -export function putDocument(storageInstance, doc) { - return storageInstance.put(doc).then(function (putResult) { - return Object.assign({ - _id: putResult.id, - _rev: putResult.rev - }, doc); - }); -} -/** - * returns all NON-LOCAL documents - */ - -export function getAllDocuments(storageInstance) { - return storageInstance.allDocs({ - include_docs: true - }).then(function (result) { - return result.rows; - }); -} -/** - * deletes the storage instance and all of it's data - */ - -export function deleteStorageInstance(storageInstance) { - return storageInstance.destroy(); -} -//# sourceMappingURL=rx-database-internal-store.js.map \ No newline at end of file diff --git a/dist/es/rx-database.js b/dist/es/rx-database.js index a59a9c184c5..89c4a65dde8 100644 --- a/dist/es/rx-database.js +++ b/dist/es/rx-database.js @@ -4,49 +4,50 @@ import _regeneratorRuntime from "@babel/runtime/regenerator"; import randomToken from 'random-token'; import { IdleQueue } from 'custom-idle-queue'; import { BroadcastChannel } from 'broadcast-channel'; -import { promiseWait, pluginMissing, LOCAL_PREFIX, flatClone } from './util'; +import { pluginMissing, flatClone } from './util'; import { newRxError } from './rx-error'; import { createRxSchema } from './rx-schema'; -import { isInstanceOf as isInstanceOfRxChangeEvent } from './rx-change-event'; +import { isRxChangeEventIntern } from './rx-change-event'; import { overwritable } from './overwritable'; import { runPluginHooks, runAsyncPluginHooks } from './hooks'; import { Subject } from 'rxjs'; -import { filter } from 'rxjs/operators'; -import { PouchDB, isLevelDown } from './pouch-db'; -import { create as createRxCollection } from './rx-collection'; -import { RxChangeEvent } from './rx-change-event'; -import { getRxStoragePouchDb } from './rx-storage-pouchdb'; -import { getAllDocuments, deleteStorageInstance } from './rx-database-internal-store'; - +import { createRxCollection } from './rx-collection'; +import { findLocalDocument, getAllDocuments, getSingleDocument, INTERNAL_STORAGE_NAME, storageChangeEventToRxChangeEvent, writeSingle } from './rx-storage-helper'; +import { getPseudoSchemaForVersion } from './rx-schema-helper'; /** - * stores the combinations - * of used database-names with their adapters - * so we can throw when the same database is created more then once + * stores the used database names + * so we can throw when the same database is created more then once. */ -var USED_COMBINATIONS = {}; -var DB_COUNT = 0; + +var USED_DATABASE_NAMES = new Set(); +var DB_COUNT = 0; // stores information about the collections + export var RxDatabaseBase = /*#__PURE__*/function () { - function RxDatabaseBase(name, adapter, password, multiInstance) { - var eventReduce = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; - var pouchSettings = arguments.length > 6 ? arguments[6] : undefined; + /** + * Stores information documents about the collections of the database + */ + + /** + * Stores the local documents which are attached to this database. + */ + function RxDatabaseBase(name, storage, instanceCreationOptions, password, multiInstance) { + var eventReduce = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + var options = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; this.internalStore = {}; + this.localDocumentsStore = {}; this.idleQueue = new IdleQueue(); this.token = randomToken(10); this._subs = []; this.destroyed = false; this.subject = new Subject(); - this.observable$ = this.subject.asObservable().pipe(filter(function (cEvent) { - return isInstanceOfRxChangeEvent(cEvent); - })); + this.observable$ = this.subject.asObservable(); this.name = name; - this.adapter = adapter; + this.storage = storage; + this.instanceCreationOptions = instanceCreationOptions; this.password = password; this.multiInstance = multiInstance; this.eventReduce = eventReduce; this.options = options; - this.pouchSettings = pouchSettings; - this.storage = getRxStoragePouchDb(adapter, pouchSettings); this.collections = {}; DB_COUNT++; } @@ -58,31 +59,45 @@ export var RxDatabaseBase = /*#__PURE__*/function () { * only use this if you have to upgrade from a major rxdb-version * do NEVER use this to change the schema of a collection */ - _proto.dangerousRemoveCollectionInfo = function dangerousRemoveCollectionInfo() { - var _this = this; - - return getAllDocuments(this.internalStore).then(function (docsRes) { - return Promise.all(docsRes.map(function (row) { - return { - _id: row.key, - _rev: row.value.rev - }; - }).map(function (doc) { - return _this.internalStore.remove(doc._id, doc._rev); - })); - }); - } - /** - * spawns a new pouch-instance - */ - ; + _proto.dangerousRemoveCollectionInfo = + /*#__PURE__*/ + function () { + var _dangerousRemoveCollectionInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var allDocs, writeData; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return getAllDocuments(this.internalStore); + + case 2: + allDocs = _context.sent; + writeData = allDocs.map(function (doc) { + var deletedDoc = flatClone(doc); + deletedDoc._deleted = true; + return { + previous: doc, + document: deletedDoc + }; + }); + _context.next = 6; + return this.internalStore.bulkWrite(writeData); - _proto._spawnPouchDB = function _spawnPouchDB(collectionName, schemaVersion) { - var pouchSettings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - return this.storage.createStorageInstance(this.name, collectionName, schemaVersion, { - pouchSettings: pouchSettings - }); - } + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function dangerousRemoveCollectionInfo() { + return _dangerousRemoveCollectionInfo.apply(this, arguments); + } + + return dangerousRemoveCollectionInfo; + }() /** * This is the main handle-point for all change events * ChangeEvents created by this instance go: @@ -93,8 +108,7 @@ export var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.$emit = function $emit(changeEvent) { - if (!changeEvent) return; // emit into own stream - + // emit into own stream this.subject.next(changeEvent); // write to socket if event was created by this instance if (changeEvent.databaseToken === this.token) { @@ -102,77 +116,113 @@ export var RxDatabaseBase = /*#__PURE__*/function () { } } /** - * removes the collection-doc from this._collectionsPouch + * removes the collection-doc from the internalStore */ ; - _proto.removeCollectionDoc = function removeCollectionDoc(name, schema) { - var _this2 = this; + _proto.removeCollectionDoc = + /*#__PURE__*/ + function () { + var _removeCollectionDoc = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(name, schema) { + var _this = this; - var docId = _collectionNamePrimary(name, schema); + var docId, doc, writeDoc; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + docId = _collectionNamePrimary(name, schema); + _context2.next = 3; + return getSingleDocument(this.internalStore, docId); - return this.internalStore.get(docId).then(function (doc) { - return _this2.lockedRun(function () { - return _this2.internalStore.remove(doc); - }); - }); - } + case 3: + doc = _context2.sent; + + if (doc) { + _context2.next = 6; + break; + } + + throw newRxError('SNH'); + + case 6: + writeDoc = flatClone(doc); + writeDoc._deleted = true; + _context2.next = 10; + return this.lockedRun(function () { + return _this.internalStore.bulkWrite([{ + document: writeDoc, + previous: doc + }]); + }); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function removeCollectionDoc(_x, _x2) { + return _removeCollectionDoc.apply(this, arguments); + } + + return removeCollectionDoc; + }() /** * creates multiple RxCollections at once * to be much faster by saving db txs and doing stuff in bulk-operations * This function is not called often, but mostly in the critical path at the initial page load - * So it must be as fast as possible + * So it must be as fast as possible. */ ; _proto.addCollections = /*#__PURE__*/ function () { - var _addCollections = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(collectionCreators) { - var _this3 = this; + var _addCollections = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(collectionCreators) { + var _this2 = this; - var pouch, result, internalDocByCollectionName, schemaHashByName, collections, bulkPutDocs, ret; - return _regeneratorRuntime.wrap(function _callee$(_context) { + var collectionDocs, internalDocByCollectionName, schemaHashByName, collections, bulkPutDocs, ret; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { - switch (_context.prev = _context.next) { + switch (_context3.prev = _context3.next) { case 0: - pouch = this.internalStore; // get local management docs in bulk request - - _context.next = 3; - return pouch.allDocs({ - include_docs: true, - keys: Object.keys(collectionCreators).map(function (name) { - return _collectionNamePrimary(name, collectionCreators[name].schema); - }) - }); - - case 3: - result = _context.sent; + _context3.next = 2; + return this.internalStore.findDocumentsById(Object.keys(collectionCreators).map(function (name) { + var schema = collectionCreators[name].schema; + return _collectionNamePrimary(name, schema); + }), false); + + case 2: + collectionDocs = _context3.sent; internalDocByCollectionName = {}; - result.rows.forEach(function (row) { - if (!row.error) { - internalDocByCollectionName[row.key] = row.doc; - } + Array.from(collectionDocs.entries()).forEach(function (_ref) { + var key = _ref[0], + doc = _ref[1]; + internalDocByCollectionName[key] = doc; }); schemaHashByName = {}; - _context.next = 9; - return Promise.all(Object.entries(collectionCreators).map(function (_ref) { - var name = _ref[0], - args = _ref[1]; + _context3.next = 8; + return Promise.all(Object.entries(collectionCreators).map(function (_ref2) { + var name = _ref2[0], + args = _ref2[1]; + var useName = name; - var internalDoc = internalDocByCollectionName[_collectionNamePrimary(name, collectionCreators[name].schema)]; + var internalDoc = internalDocByCollectionName[_collectionNamePrimary(name, collectionCreators[useName].schema)]; var useArgs = flatClone(args); - useArgs.name = name; + useArgs.name = useName; var schema = createRxSchema(args.schema); - schemaHashByName[name] = schema.hash; + schemaHashByName[useName] = schema.hash; useArgs.schema = schema; - useArgs.database = _this3; // TODO check if already exists and schema hash has changed + useArgs.database = _this2; // TODO check if already exists and schema hash has changed // collection already exists // TODO check if already exists and schema hash has changed // collection already exists - if (_this3.collections[name]) { + if (_this2.collections[name]) { throw newRxError('DB3', { name: name }); @@ -180,32 +230,32 @@ export var RxDatabaseBase = /*#__PURE__*/function () { // collection already exists but has different schema - if (internalDoc && internalDoc.schemaHash !== schemaHashByName[name]) { + if (internalDoc && internalDoc.schemaHash !== schemaHashByName[useName]) { throw newRxError('DB6', { name: name, previousSchemaHash: internalDoc.schemaHash, - schemaHash: schemaHashByName[name] + schemaHash: schemaHashByName[useName] }); } // run hooks // run hooks var hookData = flatClone(args); - hookData.database = _this3; + hookData.database = _this2; hookData.name = name; runPluginHooks('preCreateRxCollection', hookData); return createRxCollection(useArgs, !!internalDoc); })); - case 9: - collections = _context.sent; + case 8: + collections = _context3.sent; bulkPutDocs = []; ret = {}; collections.forEach(function (collection) { var name = collection.name; ret[name] = collection; - if (collection.schema.crypt && !_this3.password) { + if (collection.schema.crypt && !_this2.password) { throw newRxError('DB7', { name: name }); @@ -214,90 +264,81 @@ export var RxDatabaseBase = /*#__PURE__*/function () { if (!internalDocByCollectionName[name]) { bulkPutDocs.push({ - _id: _collectionNamePrimary(name, collectionCreators[name].schema), - schemaHash: schemaHashByName[name], - schema: collection.schema.normalized, - version: collection.schema.version + document: { + collectionName: _collectionNamePrimary(name, collectionCreators[name].schema), + schemaHash: schemaHashByName[name], + schema: collection.schema.normalized, + version: collection.schema.version, + _attachments: {} + } }); } // set as getter to the database - _this3.collections[name] = collection; + _this2.collections[name] = collection; - if (!_this3[name]) { - Object.defineProperty(_this3, name, { + if (!_this2[name]) { + Object.defineProperty(_this2, name, { get: function get() { - return _this3.collections[name]; + return _this2.collections[name]; } }); } }); // make a single call to the pouchdb instance if (!(bulkPutDocs.length > 0)) { - _context.next = 16; + _context3.next = 15; break; } - _context.next = 16; - return pouch.bulkDocs({ - docs: bulkPutDocs - }); + _context3.next = 15; + return this.internalStore.bulkWrite(bulkPutDocs); - case 16: - return _context.abrupt("return", ret); + case 15: + return _context3.abrupt("return", ret); - case 17: + case 16: case "end": - return _context.stop(); + return _context3.stop(); } } - }, _callee, this); + }, _callee3, this); })); - function addCollections(_x) { + function addCollections(_x3) { return _addCollections.apply(this, arguments); } return addCollections; }() - /** - * create or fetch a collection - * @deprecated use addCollections() instead, it is faster and better typed - */ - ; - - _proto.collection = function collection(args) { - var _this$addCollections; - - if (typeof args === 'string') { - return Promise.resolve(this.collections[args]); - } // collection() is deprecated, call new bulk-creation method - - - return this.addCollections((_this$addCollections = {}, _this$addCollections[args.name] = args, _this$addCollections)).then(function (colObject) { - return colObject[args.name]; - }); - } /** * delete all data of the collection and its previous versions */ ; _proto.removeCollection = function removeCollection(collectionName) { - var _this4 = this; + var _this3 = this; + + if (this.collections[collectionName]) { + this.collections[collectionName].destroy(); + } // remove schemas from internal db - if (this.collections[collectionName]) this.collections[collectionName].destroy(); // remove schemas from internal db return _removeAllOfCollection(this, collectionName) // get all relevant pouchdb-instances .then(function (knownVersions) { - return knownVersions.map(function (v) { - return _this4._spawnPouchDB(collectionName, v); - }); + return Promise.all(knownVersions.map(function (v) { + return _this3.storage.createStorageInstance({ + databaseName: _this3.name, + collectionName: collectionName, + schema: getPseudoSchemaForVersion(v, 'collectionName'), + options: _this3.instanceCreationOptions + }); + })); }) // remove documents - .then(function (pouches) { - return Promise.all(pouches.map(function (pouch) { - return _this4.lockedRun(function () { - return pouch.destroy(); + .then(function (storageInstance) { + return Promise.all(storageInstance.map(function (instance) { + return _this3.lockedRun(function () { + return instance.remove(); }); })); }).then(function () {}); @@ -321,7 +362,7 @@ export var RxDatabaseBase = /*#__PURE__*/function () { */ ; - _proto.dump = function dump() { + _proto.exportJSON = function exportJSON() { var _decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var _collections = arguments.length > 1 ? arguments[1] : undefined; @@ -330,13 +371,13 @@ export var RxDatabaseBase = /*#__PURE__*/function () { } /** * Import the parsed JSON export into the collection. - * @param _exportedJSON The previously exported data from the `.dump()` method. + * @param _exportedJSON The previously exported data from the `.exportJSON()` method. * @note When an interface is loaded in this collection all base properties of the type are typed as `any` * since data could be encrypted. */ ; - _proto.importDump = function importDump(_exportedJSON) { + _proto.importJSON = function importJSON(_exportedJSON) { throw pluginMissing('json-dump'); } /** @@ -377,7 +418,7 @@ export var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.destroy = function destroy() { - var _this5 = this; + var _this4 = this; if (this.destroyed) return Promise.resolve(false); runPluginHooks('preDestroyRxDatabase', this); @@ -391,17 +432,20 @@ export var RxDatabaseBase = /*#__PURE__*/function () { return this.requestIdlePromise() // destroy all collections .then(function () { - return Promise.all(Object.keys(_this5.collections).map(function (key) { - return _this5.collections[key]; + return Promise.all(Object.keys(_this4.collections).map(function (key) { + return _this4.collections[key]; }).map(function (col) { return col.destroy(); })); + }) // destroy internal storage instances + .then(function () { + return _this4.internalStore.close ? _this4.internalStore.close() : null; }) // close broadcastChannel if exists .then(function () { - return _this5.broadcastChannel ? _this5.broadcastChannel.close() : Promise.resolve(); + return _this4.broadcastChannel ? _this4.broadcastChannel.close() : Promise.resolve(); }) // remove combination from USED_COMBINATIONS-map .then(function () { - return _removeUsedCombination(_this5.name, _this5.adapter); + return USED_DATABASE_NAMES["delete"](_this4.name); }).then(function () { return true; }); @@ -412,10 +456,10 @@ export var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.remove = function remove() { - var _this6 = this; + var _this5 = this; return this.destroy().then(function () { - return removeRxDatabase(_this6.name, _this6.adapter); + return removeRxDatabase(_this5.name, _this5.storage); }); }; @@ -433,27 +477,16 @@ export var RxDatabaseBase = /*#__PURE__*/function () { * @throws {RxError} if used */ -function _isNameAdapterUsed(name, adapter) { - if (!USED_COMBINATIONS[name]) return false; - var used = false; - USED_COMBINATIONS[name].forEach(function (ad) { - if (ad === adapter) used = true; - }); - - if (used) { +function throwIfDatabaseNameUsed(name) { + if (!USED_DATABASE_NAMES.has(name)) { + return; + } else { throw newRxError('DB8', { name: name, - adapter: adapter, link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate' }); } } - -function _removeUsedCombination(name, adapter) { - if (!USED_COMBINATIONS[name]) return; - var index = USED_COMBINATIONS[name].indexOf(adapter); - USED_COMBINATIONS[name].splice(index, 1); -} /** * to not confuse multiInstance-messages with other databases that have the same * name and adapter, but do not share state with this one (for example in-memory-instances), @@ -461,29 +494,66 @@ function _removeUsedCombination(name, adapter) { */ -export function _ensureStorageTokenExists(rxDatabase) { - return rxDatabase.internalStore.get(LOCAL_PREFIX + 'storageToken')["catch"](function () { - // no doc exists -> insert - return rxDatabase.internalStore.put({ - _id: LOCAL_PREFIX + 'storageToken', - value: randomToken(10) - })["catch"](function () {}).then(function () { - return promiseWait(0); - }); - }).then(function () { - return rxDatabase.internalStore.get(LOCAL_PREFIX + 'storageToken'); - }).then(function (storageTokenDoc2) { - return storageTokenDoc2.value; - }); +export function _ensureStorageTokenExists(_x4) { + return _ensureStorageTokenExists2.apply(this, arguments); } /** * writes the changeEvent to the broadcastChannel */ +function _ensureStorageTokenExists2() { + _ensureStorageTokenExists2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(rxDatabase) { + var storageTokenDocumentId, storageTokenDoc, storageToken; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + storageTokenDocumentId = 'storageToken'; + _context4.next = 3; + return findLocalDocument(rxDatabase.localDocumentsStore, storageTokenDocumentId); + + case 3: + storageTokenDoc = _context4.sent; + + if (storageTokenDoc) { + _context4.next = 11; + break; + } + + storageToken = randomToken(10); + _context4.next = 8; + return rxDatabase.localDocumentsStore.bulkWrite([{ + document: { + _id: storageTokenDocumentId, + value: storageToken, + _attachments: {} + } + }]); + + case 8: + return _context4.abrupt("return", storageToken); + + case 11: + return _context4.abrupt("return", storageTokenDoc.value); + + case 12: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + return _ensureStorageTokenExists2.apply(this, arguments); +} + export function writeToSocket(rxDatabase, changeEvent) { - if (rxDatabase.multiInstance && !changeEvent.isIntern() && rxDatabase.broadcastChannel) { + if (rxDatabase.destroyed) { + return Promise.resolve(false); + } + + if (rxDatabase.multiInstance && !isRxChangeEventIntern(changeEvent) && rxDatabase.broadcastChannel) { var sendOverChannel = { - cE: changeEvent.toJSON(), + cE: changeEvent, storageToken: rxDatabase.storageToken }; return rxDatabase.broadcastChannel.postMessage(sendOverChannel).then(function () { @@ -504,27 +574,51 @@ export function _collectionNamePrimary(name, schema) { * @return resolves all known collection-versions */ -export function _removeAllOfCollection(rxDatabase, collectionName) { - return rxDatabase.lockedRun(function () { - return getAllDocuments(rxDatabase.internalStore); - }).then(function (data) { - var relevantDocs = data.map(function (row) { - return row.doc; - }).filter(function (doc) { - var name = doc._id.split('-')[0]; +export function _removeAllOfCollection(_x5, _x6) { + return _removeAllOfCollection2.apply(this, arguments); +} - return name === collectionName; - }); - return Promise.all(relevantDocs.map(function (doc) { - return rxDatabase.lockedRun(function () { - return rxDatabase.internalStore.remove(doc); - }); - })).then(function () { - return relevantDocs.map(function (doc) { - return doc.version; - }); - }); - }); +function _removeAllOfCollection2() { + _removeAllOfCollection2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(rxDatabase, collectionName) { + var docs, relevantDocs; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return rxDatabase.lockedRun(function () { + return getAllDocuments(rxDatabase.internalStore); + }); + + case 2: + docs = _context5.sent; + relevantDocs = docs.filter(function (doc) { + var name = doc.collectionName.split('-')[0]; + return name === collectionName; + }); + return _context5.abrupt("return", Promise.all(relevantDocs.map(function (doc) { + var writeDoc = flatClone(doc); + writeDoc._deleted = true; + return rxDatabase.lockedRun(function () { + return writeSingle(rxDatabase.internalStore, { + previous: doc, + document: writeDoc + }); + }); + })).then(function () { + return relevantDocs.map(function (doc) { + return doc.version; + }); + })); + + case 5: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + return _removeAllOfCollection2.apply(this, arguments); } function _prepareBroadcastChannel(rxDatabase) { @@ -537,74 +631,134 @@ function _prepareBroadcastChannel(rxDatabase) { if (msg.cE.databaseToken === rxDatabase.token) return; // same db - var changeEvent = new RxChangeEvent(msg.cE.operation, msg.cE.documentId, msg.cE.documentData, msg.cE.databaseToken, msg.cE.collectionName, msg.cE.isLocal, msg.cE.startTime, msg.cE.endTime, msg.cE.previousData); + var changeEvent = msg.cE; rxDatabase.broadcastChannel$.next(changeEvent); - }; // TODO only subscribe when something is listening to the event-chain - + }; rxDatabase._subs.push(rxDatabase.broadcastChannel$.subscribe(function (cE) { rxDatabase.$emit(cE); })); } +/** + * Creates the storage instances that are used internally in the database + * to store schemas and other configuration stuff. + */ + + +function createRxDatabaseStorageInstances(_x7, _x8, _x9) { + return _createRxDatabaseStorageInstances.apply(this, arguments); +} /** * do the async things for this database */ -function prepare(rxDatabase) { - return rxDatabase.storage.createInternalStorageInstance(rxDatabase.name).then(function (internalStore) { - rxDatabase.internalStore = internalStore; - return _ensureStorageTokenExists(rxDatabase); - }).then(function (storageToken) { - rxDatabase.storageToken = storageToken; +function _createRxDatabaseStorageInstances() { + _createRxDatabaseStorageInstances = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(storage, databaseName, options) { + var internalStore, localDocumentsStore; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return storage.createStorageInstance({ + databaseName: databaseName, + collectionName: INTERNAL_STORAGE_NAME, + schema: getPseudoSchemaForVersion(0, 'collectionName'), + options: options + }); + + case 2: + internalStore = _context6.sent; + _context6.next = 5; + return storage.createKeyObjectStorageInstance(databaseName, // TODO having to set an empty string here is ugly. + // we should change the rx-storage interface to account for non-collection storage instances. + '', options); + + case 5: + localDocumentsStore = _context6.sent; + return _context6.abrupt("return", { + internalStore: internalStore, + localDocumentsStore: localDocumentsStore + }); + + case 7: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + return _createRxDatabaseStorageInstances.apply(this, arguments); +} - if (rxDatabase.multiInstance) { - _prepareBroadcastChannel(rxDatabase); - } - }); +function prepare(_x10) { + return _prepare.apply(this, arguments); +} + +function _prepare() { + _prepare = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(rxDatabase) { + var storageInstances, localDocsSub; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return createRxDatabaseStorageInstances(rxDatabase.storage, rxDatabase.name, rxDatabase.instanceCreationOptions); + + case 2: + storageInstances = _context7.sent; + rxDatabase.internalStore = storageInstances.internalStore; + rxDatabase.localDocumentsStore = storageInstances.localDocumentsStore; + localDocsSub = rxDatabase.localDocumentsStore.changeStream().subscribe(function (rxStorageChangeEvent) { + rxDatabase.$emit(storageChangeEventToRxChangeEvent(true, rxStorageChangeEvent, rxDatabase)); + }); + + rxDatabase._subs.push(localDocsSub); + + _context7.next = 9; + return _ensureStorageTokenExists(rxDatabase); + + case 9: + rxDatabase.storageToken = _context7.sent; + + if (rxDatabase.multiInstance) { + _prepareBroadcastChannel(rxDatabase); + } + + case 11: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + return _prepare.apply(this, arguments); } -export function createRxDatabase(_ref2) { - var name = _ref2.name, - adapter = _ref2.adapter, - password = _ref2.password, - _ref2$multiInstance = _ref2.multiInstance, - multiInstance = _ref2$multiInstance === void 0 ? true : _ref2$multiInstance, - _ref2$eventReduce = _ref2.eventReduce, - eventReduce = _ref2$eventReduce === void 0 ? false : _ref2$eventReduce, - _ref2$ignoreDuplicate = _ref2.ignoreDuplicate, - ignoreDuplicate = _ref2$ignoreDuplicate === void 0 ? false : _ref2$ignoreDuplicate, - _ref2$options = _ref2.options, - options = _ref2$options === void 0 ? {} : _ref2$options, - _ref2$pouchSettings = _ref2.pouchSettings, - pouchSettings = _ref2$pouchSettings === void 0 ? {} : _ref2$pouchSettings; +export function createRxDatabase(_ref3) { + var storage = _ref3.storage, + instanceCreationOptions = _ref3.instanceCreationOptions, + name = _ref3.name, + password = _ref3.password, + _ref3$multiInstance = _ref3.multiInstance, + multiInstance = _ref3$multiInstance === void 0 ? true : _ref3$multiInstance, + _ref3$eventReduce = _ref3.eventReduce, + eventReduce = _ref3$eventReduce === void 0 ? false : _ref3$eventReduce, + _ref3$ignoreDuplicate = _ref3.ignoreDuplicate, + ignoreDuplicate = _ref3$ignoreDuplicate === void 0 ? false : _ref3$ignoreDuplicate, + _ref3$options = _ref3.options, + options = _ref3$options === void 0 ? {} : _ref3$options; runPluginHooks('preCreateRxDatabase', { + storage: storage, + instanceCreationOptions: instanceCreationOptions, name: name, - adapter: adapter, password: password, multiInstance: multiInstance, eventReduce: eventReduce, ignoreDuplicate: ignoreDuplicate, - options: options, - pouchSettings: pouchSettings - }); // check if pouchdb-adapter - - if (typeof adapter === 'string') { - // TODO make a function hasAdapter() - if (!PouchDB.adapters || !PouchDB.adapters[adapter]) { - throw newRxError('DB9', { - adapter: adapter - }); - } - } else { - isLevelDown(adapter); - - if (!PouchDB.adapters || !PouchDB.adapters.leveldb) { - throw newRxError('DB10', { - adapter: adapter - }); - } - } + options: options + }); if (password) { overwritable.validatePassword(password); @@ -612,16 +766,11 @@ export function createRxDatabase(_ref2) { if (!ignoreDuplicate) { - _isNameAdapterUsed(name, adapter); - } // add to used_map - - - if (!USED_COMBINATIONS[name]) { - USED_COMBINATIONS[name] = []; + throwIfDatabaseNameUsed(name); } - USED_COMBINATIONS[name].push(adapter); - var rxDatabase = new RxDatabaseBase(name, adapter, password, multiInstance, eventReduce, options, pouchSettings); + USED_DATABASE_NAMES.add(name); + var rxDatabase = new RxDatabaseBase(name, storage, instanceCreationOptions, password, multiInstance, eventReduce, options); return prepare(rxDatabase).then(function () { return runAsyncPluginHooks('createRxDatabase', rxDatabase); }).then(function () { @@ -632,45 +781,82 @@ export function createRxDatabase(_ref2) { * removes the database and all its known data */ -export function removeRxDatabase(databaseName, adapter) { - var storage = getRxStoragePouchDb(adapter); - return storage.createInternalStorageInstance(databaseName).then(function (internalStore) { - return getAllDocuments(internalStore).then(function (docs) { - // remove collections storages - return Promise.all(docs.map(function (colDoc) { - return colDoc.id; - }).map(function (id) { - var split = id.split('-'); - var name = split[0]; - var version = parseInt(split[1], 10); - var instance = storage.createStorageInstance(databaseName, name, version); - return instance.destroy(); - })); - }) // remove internals - .then(function () { - return deleteStorageInstance(internalStore); - }); - }); +export function removeRxDatabase(_x11, _x12) { + return _removeRxDatabase.apply(this, arguments); } -/** - * check if the given adapter can be used - */ -export function checkAdapter(adapter) { - return overwritable.checkAdapter(adapter); +function _removeRxDatabase() { + _removeRxDatabase = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(databaseName, storage) { + var storageInstance, docs; + return _regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return createRxDatabaseStorageInstances(storage, databaseName, {}); + + case 2: + storageInstance = _context9.sent; + _context9.next = 5; + return getAllDocuments(storageInstance.internalStore); + + case 5: + docs = _context9.sent; + _context9.next = 8; + return Promise.all(docs.map(function (colDoc) { + return colDoc.collectionName; + }).map( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(id) { + var split, name, version, instance; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + split = id.split('-'); + name = split[0]; + version = parseInt(split[1], 10); + _context8.next = 5; + return storage.createStorageInstance({ + databaseName: databaseName, + collectionName: name, + schema: getPseudoSchemaForVersion(version, 'collectionName'), + options: {} + }); + + case 5: + instance = _context8.sent; + return _context8.abrupt("return", instance.remove()); + + case 7: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + + return function (_x13) { + return _ref4.apply(this, arguments); + }; + }())); + + case 8: + return _context9.abrupt("return", Promise.all([storageInstance.internalStore.remove(), storageInstance.localDocumentsStore.remove()])); + + case 9: + case "end": + return _context9.stop(); + } + } + }, _callee9); + })); + return _removeRxDatabase.apply(this, arguments); } -export function isInstanceOf(obj) { + +export function isRxDatabase(obj) { return obj instanceof RxDatabaseBase; } export function dbCount() { return DB_COUNT; } -export default { - createRxDatabase: createRxDatabase, - removeRxDatabase: removeRxDatabase, - checkAdapter: checkAdapter, - isInstanceOf: isInstanceOf, - RxDatabaseBase: RxDatabaseBase, - dbCount: dbCount -}; //# sourceMappingURL=rx-database.js.map \ No newline at end of file diff --git a/dist/es/rx-document-prototype-merge.js b/dist/es/rx-document-prototype-merge.js index 155afc23adb..8744957b66d 100644 --- a/dist/es/rx-document-prototype-merge.js +++ b/dist/es/rx-document-prototype-merge.js @@ -65,15 +65,17 @@ export function getRxDocumentConstructor(rxCollection) { */ export function createRxDocument(rxCollection, docData) { - // return from cache if exsists - var id = docData[rxCollection.schema.primaryPath]; + var primary = docData[rxCollection.schema.primaryPath]; // return from cache if exsists - var cacheDoc = rxCollection._docCache.get(id); + var cacheDoc = rxCollection._docCache.get(primary); + + if (cacheDoc) { + return cacheDoc; + } - if (cacheDoc) return cacheDoc; var doc = createRxDocumentWithConstructor(getRxDocumentConstructor(rxCollection), rxCollection, docData); - rxCollection._docCache.set(id, doc); + rxCollection._docCache.set(primary, doc); rxCollection._runHooksSync('post', 'create', docData, doc); diff --git a/dist/es/rx-document.js b/dist/es/rx-document.js index 08aed51f0ca..a51834a6797 100644 --- a/dist/es/rx-document.js +++ b/dist/es/rx-document.js @@ -3,10 +3,13 @@ import _regeneratorRuntime from "@babel/runtime/regenerator"; import objectPath from 'object-path'; import { BehaviorSubject } from 'rxjs'; import { distinctUntilChanged, map } from 'rxjs/operators'; -import { clone, trimDots, getHeightOfRevision, pluginMissing, now, nextTick } from './util'; -import { createUpdateEvent, createDeleteEvent } from './rx-change-event'; +import { clone, trimDots, getHeightOfRevision, pluginMissing, now, nextTick, flatClone } from './util'; import { newRxError, newRxTypeError, isPouchdbConflictError } from './rx-error'; import { runPluginHooks } from './hooks'; +import { getDocumentDataOfRxChangeEvent } from './rx-change-event'; +import { writeToStorageInstance } from './rx-collection-helper'; +import { overwritable } from './overwritable'; +import { getSchemaByObjectPath } from './rx-schema-helper'; export var basePrototype = { /** * TODO @@ -65,7 +68,7 @@ export var basePrototype = { return undefined; } - return _this._deleted$.asObservable(); + return _this._isDeleted$.asObservable(); }, get deleted() { @@ -75,7 +78,7 @@ export var basePrototype = { return undefined; } - return _this._deleted$.getValue(); + return _this._isDeleted$.getValue(); }, /** @@ -88,9 +91,13 @@ export var basePrototype = { }, _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) return; // ensure that new _rev is higher then current + if (changeEvent.documentId !== this.primary) { + return; + } // ensure that new _rev is higher then current - var newRevNr = getHeightOfRevision(changeEvent.documentData._rev); + + var docData = getDocumentDataOfRxChangeEvent(changeEvent); + var newRevNr = getHeightOfRevision(docData._rev); var currentRevNr = getHeightOfRevision(this._data._rev); if (currentRevNr > newRevNr) return; @@ -109,7 +116,7 @@ export var basePrototype = { // remove from docCache to assure new upserted RxDocuments will be a new instance this.collection._docCache["delete"](this.primary); - this._deleted$.next(true); + this._isDeleted$.next(true); break; } @@ -140,7 +147,7 @@ export var basePrototype = { }); } - var schemaObj = this.collection.schema.getSchemaByObjectPath(path); + var schemaObj = getSchemaByObjectPath(this.collection.schema.jsonSchema, path); if (!schemaObj) { throw newRxError('DOC4', { @@ -157,7 +164,7 @@ export var basePrototype = { * populate the given path */ populate: function populate(path) { - var schemaObj = this.collection.schema.getSchemaByObjectPath(path); + var schemaObj = getSchemaByObjectPath(this.collection.schema.jsonSchema, path); var value = this.get(path); if (!value) { @@ -202,23 +209,32 @@ export var basePrototype = { */ get: function get(objPath) { if (!this._data) return undefined; - var valueObj = objectPath.get(this._data, objPath); - valueObj = clone(valueObj); // direct return if array or non-object + var valueObj = objectPath.get(this._data, objPath); // direct return if array or non-object + + if (typeof valueObj !== 'object' || Array.isArray(valueObj)) { + return overwritable.deepFreezeWhenDevMode(valueObj); + } + /** + * TODO find a way to deep-freeze together with defineGetterSetter + * so we do not have to do a deep clone here. + */ + - if (typeof valueObj !== 'object' || Array.isArray(valueObj)) return valueObj; + valueObj = clone(valueObj); defineGetterSetter(this.collection.schema, valueObj, objPath, this); return valueObj; }, toJSON: function toJSON() { var withRevAndAttachments = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var data = clone(this._data); if (!withRevAndAttachments) { + var data = flatClone(this._data); delete data._rev; delete data._attachments; + return overwritable.deepFreezeWhenDevMode(data); + } else { + return overwritable.deepFreezeWhenDevMode(this._data); } - - return data; }, /** @@ -375,59 +391,59 @@ export var basePrototype = { }); }, - /** - * @deprecated use atomicPatch instead because it is better typed - * and does not allow any keys and values - */ - atomicSet: function atomicSet(key, value) { - return this.atomicUpdate(function (docData) { - objectPath.set(docData, key, value); - return docData; - }); - }, - /** * saves the new document-data * and handles the events */ - _saveData: function _saveData(newData, oldData) { - var _this3 = this; - - newData = newData; // deleted documents cannot be changed - - if (this._deleted$.getValue()) { - throw newRxError('DOC11', { - id: this.primary, - document: this - }); - } // ensure modifications are ok - - - this.collection.schema.validateChange(oldData, newData); - var startTime; - return this.collection._runHooks('pre', 'save', newData, this).then(function () { - _this3.collection.schema.validate(newData); - - startTime = now(); - return _this3.collection._pouchPut(newData); - }).then(function (ret) { - var endTime = now(); - - if (!ret.ok) { - throw newRxError('DOC12', { - data: ret - }); - } - - newData._rev = ret.rev; // emit event - - var changeEvent = createUpdateEvent(_this3.collection, newData, oldData, startTime, endTime, _this3); + _saveData: function () { + var _saveData2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(newData, oldData) { + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + newData = newData; // deleted documents cannot be changed + + if (!this._isDeleted$.getValue()) { + _context2.next = 3; + break; + } + + throw newRxError('DOC11', { + id: this.primary, + document: this + }); + + case 3: + // ensure modifications are ok + this.collection.schema.validateChange(oldData, newData); + _context2.next = 6; + return this.collection._runHooks('pre', 'save', newData, this); + + case 6: + this.collection.schema.validate(newData); + _context2.next = 9; + return writeToStorageInstance(this.collection, { + previous: oldData, + document: newData + }); + + case 9: + return _context2.abrupt("return", this.collection._runHooks('post', 'save', newData, this)); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); - _this3.$emit(changeEvent); + function _saveData(_x, _x2) { + return _saveData2.apply(this, arguments); + } - return _this3.collection._runHooks('post', 'save', newData, _this3); - }); - }, + return _saveData; + }(), /** * saves the temporary document and makes a non-temporary out of it @@ -435,7 +451,7 @@ export var basePrototype = { * @return false if nothing to save */ save: function save() { - var _this4 = this; + var _this3 = this; // .save() cannot be called on non-temporary-documents if (!this._isTemporary) { @@ -446,12 +462,12 @@ export var basePrototype = { } return this.collection.insert(this).then(function () { - _this4._isTemporary = false; + _this3._isTemporary = false; - _this4.collection._docCache.set(_this4.primary, _this4); // internal events + _this3.collection._docCache.set(_this3.primary, _this3); // internal events - _this4._dataSync$.next(_this4._data); + _this3._dataSync$.next(_this3._data); return true; }); @@ -463,7 +479,7 @@ export var basePrototype = { * instead we keep the values and only set _deleted: true */ remove: function remove() { - var _this5 = this; + var _this4 = this; if (this.deleted) { return Promise.reject(newRxError('DOC13', { @@ -472,25 +488,19 @@ export var basePrototype = { })); } - var deletedData = clone(this._data); + var deletedData = flatClone(this._data); var startTime; return this.collection._runHooks('pre', 'remove', deletedData, this).then(function () { deletedData._deleted = true; startTime = now(); - /** - * because pouch.remove will also empty the object, - * we set _deleted: true and use pouch.put - */ - - return _this5.collection._pouchPut(deletedData); + return writeToStorageInstance(_this4.collection, { + previous: _this4._data, + document: deletedData + }); }).then(function () { - var endTime = now(); - - _this5.$emit(createDeleteEvent(_this5.collection, deletedData, _this5._data, startTime, endTime, _this5)); - - return _this5.collection._runHooks('post', 'remove', deletedData, _this5); + return _this4.collection._runHooks('post', 'remove', deletedData, _this4); }).then(function () { - return _this5; + return _this4; }); }, destroy: function destroy() { @@ -506,7 +516,7 @@ export function createRxDocumentConstructor() { this._isTemporary = false; // assume that this is always equal to the doc-data in the database this._dataSync$ = new BehaviorSubject(jsonData); - this._deleted$ = new BehaviorSubject(false); + this._isDeleted$ = new BehaviorSubject(false); this._atomicQueue = Promise.resolve(); /** * because of the prototype-merge, @@ -523,7 +533,7 @@ export function defineGetterSetter(schema, valueObj) { var objPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var thisObj = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (valueObj === null) return; - var pathProperties = schema.getSchemaByObjectPath(objPath); + var pathProperties = getSchemaByObjectPath(schema.jsonSchema, objPath); if (typeof pathProperties === 'undefined') return; if (pathProperties.properties) pathProperties = pathProperties.properties; Object.keys(pathProperties).forEach(function (key) { @@ -580,7 +590,7 @@ export function createWithConstructor(constructor, collection, jsonData) { runPluginHooks('createRxDocument', doc); return doc; } -export function isInstanceOf(obj) { +export function isRxDocument(obj) { if (typeof obj === 'undefined') return false; return !!obj.isInstanceOfRxDocument; } diff --git a/dist/es/rx-query.js b/dist/es/rx-query.js index ada5457edec..2373966e0ef 100644 --- a/dist/es/rx-query.js +++ b/dist/es/rx-query.js @@ -2,13 +2,13 @@ import _createClass from "@babel/runtime/helpers/createClass"; import deepEqual from 'deep-equal'; import { merge, BehaviorSubject, firstValueFrom } from 'rxjs'; import { mergeMap, filter, map, tap } from 'rxjs/operators'; -import { massageSelector, filterInMemoryFields } from 'pouchdb-selector-core'; -import { sortObject, stringifyFilter, pluginMissing, clone, overwriteGetterForCaching, now } from './util'; +import { sortObject, stringifyFilter, pluginMissing, clone, overwriteGetterForCaching, now, promiseWait } from './util'; import { newRxError, newRxTypeError } from './rx-error'; import { runPluginHooks } from './hooks'; import { createRxDocuments } from './rx-document-prototype-merge'; import { calculateNewResults } from './event-reduce'; import { triggerCacheReplacement } from './query-cache'; +import { _handleToStorageInstance } from './rx-collection-helper'; var _queryCount = 0; var newQueryID = function newQueryID() { @@ -74,11 +74,11 @@ export var RxQueryBase = /*#__PURE__*/function () { switch (this.op) { case 'find': - docsPromise = this.collection._pouchFind(this); + docsPromise = this.collection._queryStorageInstance(this); break; case 'findOne': - docsPromise = this.collection._pouchFind(this, 1); + docsPromise = this.collection._queryStorageInstance(this, 1); break; default: @@ -140,7 +140,7 @@ export var RxQueryBase = /*#__PURE__*/function () { }); } /** - * cached call to get the massageSelector + * cached call to get the queryMatcher * @overwrites itself with the actual value */ ; @@ -165,35 +165,23 @@ export var RxQueryBase = /*#__PURE__*/function () { } /** * returns the prepared query + * which can be send to the storage instance to query for documents. * @overwrites itself with the actual value + * TODO rename this function, toJSON is missleading + * because we do not return the plain mango query object. */ ; _proto.toJSON = function toJSON() { - var value = this.collection.database.storage.prepareQuery(this.asRxQuery, clone(this.mangoQuery)); - - this.toJSON = function () { - return value; + var hookInput = { + rxQuery: this, + // can be mutated by the hooks so we have to deep clone first. + mangoQuery: clone(this.mangoQuery) }; + runPluginHooks('prePrepareQuery', hookInput); + var value = this.collection.storageInstance.prepareQuery(hookInput.mangoQuery); - return value; - } - /** - * returns the key-compressed version of the query - * @overwrites itself with the actual value - */ - ; - - _proto.keyCompress = function keyCompress() { - var value; - - if (!this.collection.schema.doKeyCompression()) { - value = this.toJSON(); - } else { - value = this.collection._keyCompressor.compressQuery(this.toJSON()); - } - - this.keyCompress = function () { + this.toJSON = function () { return value; }; @@ -208,24 +196,11 @@ export var RxQueryBase = /*#__PURE__*/function () { _proto.doesDocumentDataMatch = function doesDocumentDataMatch(docData) { // if doc is deleted, it cannot match - if (docData._deleted) return false; - docData = this.collection.schema.swapPrimaryToId(docData); // return matchesSelector(docData, selector); - - /** - * the following is equal to the implementation of pouchdb - * we do not use matchesSelector() directly so we can cache the - * result of massageSelector - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ + if (docData._deleted) { + return false; + } - var selector = this.massageSelector; - var row = { - doc: docData - }; - var rowsMatched = filterInMemoryFields([row], { - selector: selector - }, Object.keys(selector)); - return rowsMatched && rowsMatched.length === 1; + return this.queryMatcher(_handleToStorageInstance(this.collection, docData)); } /** * deletes all found documents @@ -237,9 +212,14 @@ export var RxQueryBase = /*#__PURE__*/function () { var ret; return this.exec().then(function (docs) { ret = docs; - if (Array.isArray(docs)) return Promise.all(docs.map(function (doc) { - return doc.remove(); - }));else return docs.remove(); + + if (Array.isArray(docs)) { + return Promise.all(docs.map(function (doc) { + return doc.remove(); + })); + } else { + return docs.remove(); + } }).then(function () { return ret; }); @@ -287,19 +267,25 @@ export var RxQueryBase = /*#__PURE__*/function () { */ var results$ = this._resultsDocs$.pipe(mergeMap(function (docs) { return _ensureEqual(_this3).then(function (hasChanged) { - if (hasChanged) return false; // wait for next emit - else return docs; + if (hasChanged) { + // wait for next emit + return false; + } else { + return docs; + } }); }), filter(function (docs) { return !!docs; }), // not if previous returned false map(function (docs) { - // findOne()-queries emit document or null if (_this3.op === 'findOne') { + // findOne()-queries emit document or null var doc = docs.length === 0 ? null : docs[0]; return doc; - } else return docs; // find()-queries emit RxDocument[] - + } else { + // find()-queries emit RxDocument[] + return docs; + } }), map(function (docs) { // copy the array so it wont matter if the user modifies it var ret = Array.isArray(docs) ? docs.slice() : docs; @@ -325,9 +311,9 @@ export var RxQueryBase = /*#__PURE__*/function () { } // stores the changeEvent-Number of the last handled change-event }, { - key: "massageSelector", + key: "queryMatcher", get: function get() { - return overwriteGetterForCaching(this, 'massageSelector', massageSelector(this.mangoQuery.selector)); + return overwriteGetterForCaching(this, 'queryMatcher', this.collection.storageInstance.getQueryMatcher(this.toJSON())); } }, { key: "asRxQuery", @@ -397,15 +383,11 @@ function _isResultsInSync(rxQuery) { function _ensureEqual(rxQuery) { rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue.then(function () { - return new Promise(function (res) { - return setTimeout(res, 0); - }); + return promiseWait(0); }).then(function () { return __ensureEqual(rxQuery); }).then(function (ret) { - return new Promise(function (res) { - return setTimeout(res, 0); - }).then(function () { + return promiseWait(0).then(function () { return ret; }); }); diff --git a/dist/es/rx-schema-helper.js b/dist/es/rx-schema-helper.js new file mode 100644 index 00000000000..342148fa17a --- /dev/null +++ b/dist/es/rx-schema-helper.js @@ -0,0 +1,33 @@ +import objectPath from 'object-path'; +import { trimDots } from './util'; +/** + * Helper function to create a valid RxJsonSchema + * with a given version. + */ + +export function getPseudoSchemaForVersion(version, primaryKey) { + var _properties; + + var pseudoSchema = { + version: version, + type: 'object', + primaryKey: primaryKey, + properties: (_properties = {}, _properties[primaryKey] = { + type: 'string' + }, _properties) + }; + return pseudoSchema; +} +/** + * Returns the sub-schema for a given path + */ + +export function getSchemaByObjectPath(rxJsonSchema, path) { + var usePath = path; + usePath = usePath.replace(/\./g, '.properties.'); + usePath = 'properties.' + usePath; + usePath = trimDots(usePath); + var ret = objectPath.get(rxJsonSchema, usePath); + return ret; +} +//# sourceMappingURL=rx-schema-helper.js.map \ No newline at end of file diff --git a/dist/es/rx-schema.js b/dist/es/rx-schema.js index 9580c22d30a..58cb481604e 100644 --- a/dist/es/rx-schema.js +++ b/dist/es/rx-schema.js @@ -1,7 +1,6 @@ import _createClass from "@babel/runtime/helpers/createClass"; -import objectPath from 'object-path'; import deepEqual from 'deep-equal'; -import { clone, hash, sortObject, trimDots, pluginMissing, overwriteGetterForCaching } from './util'; +import { clone, hash, sortObject, pluginMissing, overwriteGetterForCaching } from './util'; import { newRxError } from './rx-error'; import { runPluginHooks } from './hooks'; import { defineGetterSetter } from './rx-document'; @@ -10,7 +9,7 @@ export var RxSchema = /*#__PURE__*/function () { this.jsonSchema = jsonSchema; this.indexes = getIndexes(this.jsonSchema); // primary is always required - this.primaryPath = getPrimary(this.jsonSchema); + this.primaryPath = this.jsonSchema.primaryKey; if (this.primaryPath) { this.jsonSchema.required.push(this.primaryPath); @@ -21,26 +20,10 @@ export var RxSchema = /*#__PURE__*/function () { this.jsonSchema.required = this.jsonSchema.required.concat(this.finalFields).filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos; }); // unique; - // add primary to schema if not there (if _id) - - if (!this.jsonSchema.properties[this.primaryPath]) { - this.jsonSchema.properties[this.primaryPath] = { - type: 'string', - minLength: 1 - }; - } } var _proto = RxSchema.prototype; - _proto.getSchemaByObjectPath = function getSchemaByObjectPath(path) { - var usePath = path; - usePath = usePath.replace(/\./g, '.properties.'); - usePath = 'properties.' + usePath; - usePath = trimDots(usePath); - var ret = objectPath.get(this.jsonSchema, usePath); - return ret; - } /** * checks if a given change on a document is allowed * Ensures that: @@ -48,8 +31,6 @@ export var RxSchema = /*#__PURE__*/function () { * - final fields are not modified * @throws {Error} if not valid */ - ; - _proto.validateChange = function validateChange(dataBefore, dataAfter) { this.finalFields.forEach(function (fieldName) { if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) { @@ -89,39 +70,6 @@ export var RxSchema = /*#__PURE__*/function () { return obj[k] = v; }); return obj; - }; - - _proto.swapIdToPrimary = function swapIdToPrimary(obj) { - if (this.primaryPath === '_id' || obj[this.primaryPath]) { - return obj; - } - - obj[this.primaryPath] = obj._id; - delete obj._id; - return obj; - }; - - _proto.swapPrimaryToId = function swapPrimaryToId(obj) { - var _this = this; - - if (this.primaryPath === '_id') { - return obj; - } - - var ret = {}; - Object.entries(obj).forEach(function (entry) { - var newKey = entry[0] === _this.primaryPath ? '_id' : entry[0]; - ret[newKey] = entry[1]; - }); - return ret; - } - /** - * returns true if key-compression should be done - */ - ; - - _proto.doKeyCompression = function doKeyCompression() { - return this.jsonSchema.keyCompression; } /** * creates the schema-based document-prototype, @@ -207,17 +155,6 @@ export function getIndexes(jsonSchema) { return Array.isArray(index) ? index : [index]; }); } -/** - * returns the primary path of a jsonschema - * @return primaryPath which is _id if none defined - */ - -export function getPrimary(jsonSchema) { - var ret = Object.keys(jsonSchema.properties).filter(function (key) { - return jsonSchema.properties[key].primary; - }).shift(); - if (!ret) return '_id';else return ret; -} /** * array with previous version-numbers */ @@ -239,7 +176,7 @@ export function getFinalFields(jsonSchema) { return jsonSchema.properties[key]["final"]; }); // primary is also final - ret.push(getPrimary(jsonSchema)); + ret.push(jsonSchema.primaryKey); return ret; } /** @@ -254,6 +191,12 @@ export function normalize(jsonSchema) { normalizedSchema.indexes = Array.from(jsonSchema.indexes); // indexes should remain unsorted } + if (!jsonSchema.required) { + jsonSchema.required = [jsonSchema.primaryKey]; + } else if (!jsonSchema.required.includes(jsonSchema.primaryKey)) { + jsonSchema.required.push(jsonSchema.primaryKey); + } + return normalizedSchema; } /** @@ -261,18 +204,26 @@ export function normalize(jsonSchema) { * @return cloned schemaObj */ -export var fillWithDefaultSettings = function fillWithDefaultSettings(schemaObj) { +export function fillWithDefaultSettings(schemaObj) { schemaObj = clone(schemaObj); // additionalProperties is always false schemaObj.additionalProperties = false; // fill with key-compression-state () - if (!schemaObj.hasOwnProperty('keyCompression')) schemaObj.keyCompression = false; // indexes must be array + if (!schemaObj.hasOwnProperty('keyCompression')) { + schemaObj.keyCompression = false; + } // indexes must be array + schemaObj.indexes = schemaObj.indexes || []; // required must be array schemaObj.required = schemaObj.required || []; // encrypted must be array - schemaObj.encrypted = schemaObj.encrypted || []; // add _rev + schemaObj.encrypted = schemaObj.encrypted || []; + /** + * TODO we should not need to added the internal fields to the schema. + * Better remove the before validation. + */ + // add _rev schemaObj.properties._rev = { type: 'string', @@ -281,11 +232,15 @@ export var fillWithDefaultSettings = function fillWithDefaultSettings(schemaObj) schemaObj.properties._attachments = { type: 'object' + }; // add deleted flag + + schemaObj.properties._deleted = { + type: 'boolean' }; // version is 0 by default schemaObj.version = schemaObj.version || 0; return schemaObj; -}; +} export function createRxSchema(jsonSchema) { var runPreCreateHooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; diff --git a/dist/es/rx-storage-helper.js b/dist/es/rx-storage-helper.js new file mode 100644 index 00000000000..d6891ec0bf6 --- /dev/null +++ b/dist/es/rx-storage-helper.js @@ -0,0 +1,365 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; + +/** + * Helper functions for accessing the RxStorage instances. + */ +import { runPluginHooks } from './hooks'; +import { overwritable } from './overwritable'; +import { newRxError } from './rx-error'; +export var INTERNAL_STORAGE_NAME = '_rxdb_internal'; +/** + * returns all NON-LOCAL documents + * TODO this is pouchdb specific should not be needed + */ + +export function getAllDocuments(_x) { + return _getAllDocuments.apply(this, arguments); +} + +function _getAllDocuments() { + _getAllDocuments = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(storageInstance) { + var getAllQueryPrepared, queryResult, allDocs; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + getAllQueryPrepared = storageInstance.prepareQuery({ + selector: {} + }); + _context.next = 3; + return storageInstance.query(getAllQueryPrepared); + + case 3: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _getAllDocuments.apply(this, arguments); +} + +export function getSingleDocument(_x2, _x3) { + return _getSingleDocument.apply(this, arguments); +} +/** + * get the number of all undeleted documents + */ + +function _getSingleDocument() { + _getSingleDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(storageInstance, documentId) { + var results, doc; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return storageInstance.findDocumentsById([documentId], false); + + case 2: + results = _context2.sent; + doc = results.get(documentId); + + if (!doc) { + _context2.next = 8; + break; + } + + return _context2.abrupt("return", doc); + + case 8: + return _context2.abrupt("return", null); + + case 9: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _getSingleDocument.apply(this, arguments); +} + +export function countAllUndeleted(_x4) { + return _countAllUndeleted.apply(this, arguments); +} +/** + * get a batch of documents from the storage-instance + */ + +function _countAllUndeleted() { + _countAllUndeleted = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(storageInstance) { + var docs; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getAllDocuments(storageInstance); + + case 2: + docs = _context3.sent; + return _context3.abrupt("return", docs.length); + + case 4: + case "end": + return _context3.stop(); + } + } + }, _callee3); + })); + return _countAllUndeleted.apply(this, arguments); +} + +export function getBatch(_x5, _x6) { + return _getBatch.apply(this, arguments); +} +/** + * Writes a single document, + * throws RxStorageBulkWriteError on failure + */ + +function _getBatch() { + _getBatch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(storageInstance, limit) { + var preparedQuery, result; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (!(limit <= 1)) { + _context4.next = 2; + break; + } + + throw newRxError('P1', { + limit: limit + }); + + case 2: + preparedQuery = storageInstance.prepareQuery({ + selector: {}, + limit: limit + }); + _context4.next = 5; + return storageInstance.query(preparedQuery); + + case 5: + result = _context4.sent; + return _context4.abrupt("return", result.documents); + + case 7: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + return _getBatch.apply(this, arguments); +} + +export function writeSingle(_x7, _x8) { + return _writeSingle.apply(this, arguments); +} +/** + * Writes a single local document, + * throws RxStorageBulkWriteError on failure + */ + +function _writeSingle() { + _writeSingle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(instance, writeRow) { + var writeResult, error, ret; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return instance.bulkWrite([writeRow]); + + case 2: + writeResult = _context5.sent; + + if (!(writeResult.error.size > 0)) { + _context5.next = 8; + break; + } + + error = writeResult.error.values().next().value; + throw error; + + case 8: + ret = writeResult.success.values().next().value; + return _context5.abrupt("return", ret); + + case 10: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + return _writeSingle.apply(this, arguments); +} + +export function writeSingleLocal(_x9, _x10) { + return _writeSingleLocal.apply(this, arguments); +} + +function _writeSingleLocal() { + _writeSingleLocal = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(instance, writeRow) { + var writeResult, error, ret; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return instance.bulkWrite([writeRow]); + + case 2: + writeResult = _context6.sent; + + if (!(writeResult.error.size > 0)) { + _context6.next = 8; + break; + } + + error = writeResult.error.values().next().value; + throw error; + + case 8: + ret = writeResult.success.values().next().value; + return _context6.abrupt("return", ret); + + case 10: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + return _writeSingleLocal.apply(this, arguments); +} + +export function findLocalDocument(_x11, _x12) { + return _findLocalDocument.apply(this, arguments); +} + +function _findLocalDocument() { + _findLocalDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(instance, id) { + var docList, doc; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return instance.findLocalDocumentsById([id]); + + case 2: + docList = _context7.sent; + doc = docList.get(id); + + if (doc) { + _context7.next = 8; + break; + } + + return _context7.abrupt("return", null); + + case 8: + return _context7.abrupt("return", doc); + + case 9: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + return _findLocalDocument.apply(this, arguments); +} + +export function getNewestSequence(_x13) { + return _getNewestSequence.apply(this, arguments); +} + +function _getNewestSequence() { + _getNewestSequence = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(storageInstance) { + var changesResult; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return storageInstance.getChangedDocuments({ + order: 'desc', + limit: 1, + startSequence: 0 + }); + + case 2: + changesResult = _context8.sent; + return _context8.abrupt("return", changesResult.lastSequence); + + case 4: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + return _getNewestSequence.apply(this, arguments); +} + +export function storageChangeEventToRxChangeEvent(isLocal, rxStorageChangeEvent, rxDatabase, rxCollection) { + var documentData; + + if (rxStorageChangeEvent.change.operation !== 'DELETE') { + if (!rxCollection) { + documentData = rxStorageChangeEvent.change.doc; + } else { + var hookParams = { + collection: rxCollection, + doc: rxStorageChangeEvent.change.doc + }; + runPluginHooks('postReadFromInstance', hookParams); + documentData = hookParams.doc; + documentData = rxCollection._crypter.decrypt(documentData); + } + } + + var previousDocumentData; + + if (rxStorageChangeEvent.change.operation !== 'INSERT') { + if (!rxCollection) { + previousDocumentData = rxStorageChangeEvent.change.previous; + } else { + var _hookParams = { + collection: rxCollection, + doc: rxStorageChangeEvent.change.previous + }; + runPluginHooks('postReadFromInstance', _hookParams); + previousDocumentData = _hookParams.doc; + previousDocumentData = rxCollection._crypter.decrypt(previousDocumentData); + } + } + + var ret = { + eventId: rxStorageChangeEvent.eventId, + documentId: rxStorageChangeEvent.documentId, + databaseToken: rxDatabase.token, + collectionName: rxCollection ? rxCollection.name : undefined, + startTime: rxStorageChangeEvent.startTime, + endTime: rxStorageChangeEvent.endTime, + isLocal: isLocal, + operation: rxStorageChangeEvent.change.operation, + documentData: overwritable.deepFreezeWhenDevMode(documentData), + previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData) + }; + return ret; +} +//# sourceMappingURL=rx-storage-helper.js.map \ No newline at end of file diff --git a/dist/es/rx-storage-pouchdb.js b/dist/es/rx-storage-pouchdb.js deleted file mode 100644 index b0278a27b47..00000000000 --- a/dist/es/rx-storage-pouchdb.js +++ /dev/null @@ -1,268 +0,0 @@ -import { filterInMemoryFields, massageSelector } from 'pouchdb-selector-core'; -import { flatClone, adapterObject } from './util'; -import { runPluginHooks } from './hooks'; -import { PouchDB } from './pouch-db'; -import { newRxError } from './rx-error'; -export var RxStoragePouchDbClass = /*#__PURE__*/function () { - function RxStoragePouchDbClass(adapter) { - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.name = 'pouchdb'; - this.adapter = adapter; - this.pouchSettings = pouchSettings; - } - - var _proto = RxStoragePouchDbClass.prototype; - - _proto.getSortComparator = function getSortComparator(primaryKey, query) { - var _ref; - - var sortOptions = query.sort ? query.sort : [(_ref = {}, _ref[primaryKey] = 'asc', _ref)]; - var massagedSelector = massageSelector(query.selector); - var inMemoryFields = Object.keys(query.selector); - - var fun = function fun(a, b) { - // TODO use createFieldSorter - // TODO make a performance test - var rows = [a, b].map(function (doc) { - // swap primary to _id - var cloned = flatClone(doc); - var primaryValue = cloned[primaryKey]; - delete cloned[primaryKey]; - cloned._id = primaryValue; - return { - doc: cloned - }; - }); - var sortedRows = filterInMemoryFields(rows, { - selector: massagedSelector, - sort: sortOptions - }, inMemoryFields); - - if (sortedRows[0].doc._id === rows[0].doc._id) { - return -1; - } else { - return 1; - } - }; - - return fun; - } - /** - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ - ; - - _proto.getQueryMatcher = function getQueryMatcher(primaryKey, query) { - var massagedSelector = massageSelector(query.selector); - - var fun = function fun(doc) { - // swap primary to _id - var cloned = flatClone(doc); - var primaryValue = cloned[primaryKey]; - delete cloned[primaryKey]; - cloned._id = primaryValue; - var row = { - doc: cloned - }; - var rowsMatched = filterInMemoryFields([row], { - selector: massagedSelector - }, Object.keys(query.selector)); - return rowsMatched && rowsMatched.length === 1; - }; - - return fun; - }; - - _proto.createStorageInstance = function createStorageInstance(databaseName, collectionName, schemaVersion) { - var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - - if (!options.pouchSettings) { - options.pouchSettings = {}; - } - - var pouchLocation = getPouchLocation(databaseName, collectionName, schemaVersion); - var pouchDbParameters = { - location: pouchLocation, - adapter: adapterObject(this.adapter), - settings: options.pouchSettings - }; - var pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); - runPluginHooks('preCreatePouchDb', pouchDbParameters); - return new PouchDB(pouchDbParameters.location, pouchDBOptions); - }; - - _proto.createInternalStorageInstance = function createInternalStorageInstance(databaseName, _options) { - var storageInstance = this.createStorageInstance(databaseName, '_rxdb_internal', 0, { - pouchSettings: { - // no compaction because this only stores local documents - auto_compaction: false, - revs_limit: 1 - } - }); - return Promise.resolve(storageInstance); - } - /** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ - ; - - _proto.prepareQuery = function prepareQuery(rxQuery, mutateableQuery) { - var primPath = rxQuery.collection.schema.primaryPath; - var query = mutateableQuery; - /** - * because sort wont work on unused keys we have to workaround - * so we add the key to the selector if necessary - * @link https://github.com/nolanlawson/pouchdb-find/issues/204 - */ - - if (query.sort) { - query.sort.forEach(function (sortPart) { - var key = Object.keys(sortPart)[0]; - var comparisonOperators = ['$gt', '$gte', '$lt', '$lte']; - var keyUsed = query.selector[key] && Object.keys(query.selector[key]).some(function (op) { - return comparisonOperators.includes(op); - }) || false; - - if (!keyUsed) { - var schemaObj = rxQuery.collection.schema.getSchemaByObjectPath(key); - - if (!schemaObj) { - throw newRxError('QU5', { - key: key - }); - } - - if (!query.selector[key]) { - query.selector[key] = {}; - } - - switch (schemaObj.type) { - case 'number': - case 'integer': - // TODO change back to -Infinity when issue resolved - // @link https://github.com/pouchdb/pouchdb/issues/6454 - // -Infinity does not work since pouchdb 6.2.0 - query.selector[key].$gt = -9999999999999999999999999999; - break; - - case 'string': - /** - * strings need an empty string, see - * @link https://github.com/pubkey/rxdb/issues/585 - */ - if (typeof query.selector[key] !== 'string') { - query.selector[key].$gt = ''; - } - - break; - - default: - query.selector[key].$gt = null; - break; - } - } - }); - } // regex does not work over the primary key - // TODO move this to dev mode - - - if (query.selector[primPath] && query.selector[primPath].$regex) { - throw newRxError('QU4', { - path: primPath, - query: rxQuery.mangoQuery - }); - } // primary-swap sorting - - - if (query.sort) { - var sortArray = query.sort.map(function (part) { - var _newPart; - - var key = Object.keys(part)[0]; - var direction = Object.values(part)[0]; - var useKey = key === primPath ? '_id' : key; - var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); - return newPart; - }); - query.sort = sortArray; - } // strip empty selectors - - - Object.entries(query.selector).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - - if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { - delete query.selector[k]; - } - }); - - if (primPath !== '_id') { - query.selector = primarySwapPouchDbQuerySelector(query.selector, primPath); - } - - return query; - }; - - return RxStoragePouchDbClass; -}(); -/** - * Runs a primary swap with transform all custom primaryKey occurences - * into '_id' - * @recursive - */ - -export function primarySwapPouchDbQuerySelector(selector, primaryKey) { - if (Array.isArray(selector)) { - return selector.map(function (item) { - return primarySwapPouchDbQuerySelector(item, primaryKey); - }); - } else if (typeof selector === 'object') { - var ret = {}; - Object.entries(selector).forEach(function (_ref3) { - var k = _ref3[0], - v = _ref3[1]; - - if (k === primaryKey) { - ret._id = v; - } else { - if (k.startsWith('$')) { - ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); - } else { - ret[k] = v; - } - } - }); - return ret; - } else { - return selector; - } -} -/** - * returns the pouchdb-database-name - */ - -export function getPouchLocation(dbName, collectionName, schemaVersion) { - var prefix = dbName + '-rxdb-' + schemaVersion + '-'; - - if (!collectionName.includes('/')) { - return prefix + collectionName; - } else { - // if collectionName is a path, we have to prefix the last part only - var split = collectionName.split('/'); - var last = split.pop(); - var ret = split.join('/'); - ret += '/' + prefix + last; - return ret; - } -} -export function getRxStoragePouchDb(adapter, pouchSettings) { - if (!adapter) { - throw new Error('adapter missing'); - } - - return new RxStoragePouchDbClass(adapter, pouchSettings); -} -//# sourceMappingURL=rx-storage-pouchdb.js.map \ No newline at end of file diff --git a/dist/es/rx-storate.interface.js b/dist/es/rx-storate.interface.js deleted file mode 100644 index 2558b40ed07..00000000000 --- a/dist/es/rx-storate.interface.js +++ /dev/null @@ -1,2 +0,0 @@ - -//# sourceMappingURL=rx-storate.interface.js.map \ No newline at end of file diff --git a/dist/es/types/index.d.js b/dist/es/types/index.d.js index 187bb2b3cb1..05bae456d3a 100644 --- a/dist/es/types/index.d.js +++ b/dist/es/types/index.d.js @@ -6,7 +6,11 @@ export * from './rx-document'; export * from './rx-error'; export * from './rx-plugin'; export * from './rx-query'; -export * from './rx-schema'; // plugins +export * from './rx-schema'; +export * from './rx-storage'; +export * from './rx-storage.interface'; +export * from './rx-change-event'; +export * from './util'; // plugins export * from './plugins/replication'; export * from './plugins/replication-graphql'; diff --git a/dist/es/types/plugins/backup.d.js b/dist/es/types/plugins/backup.d.js index e17cc549db1..6e072730062 100644 --- a/dist/es/types/plugins/backup.d.js +++ b/dist/es/types/plugins/backup.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=backup.d.js.map \ No newline at end of file diff --git a/dist/es/types/plugins/migration.d.js b/dist/es/types/plugins/migration.d.js index fbe92e969d1..6f04103ef00 100644 --- a/dist/es/types/plugins/migration.d.js +++ b/dist/es/types/plugins/migration.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=migration.d.js.map \ No newline at end of file diff --git a/dist/es/types/plugins/replication-graphql.d.js b/dist/es/types/plugins/replication-graphql.d.js index a95579eed97..63bd570ab32 100644 --- a/dist/es/types/plugins/replication-graphql.d.js +++ b/dist/es/types/plugins/replication-graphql.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=replication-graphql.d.js.map \ No newline at end of file diff --git a/dist/es/types/plugins/replication.d.js b/dist/es/types/plugins/replication.d.js index 8ce27ae526c..8fd290b116f 100644 --- a/dist/es/types/plugins/replication.d.js +++ b/dist/es/types/plugins/replication.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=replication.d.js.map \ No newline at end of file diff --git a/dist/es/types/plugins/server.d.js b/dist/es/types/plugins/server.d.js index 5f9dfc19b71..bc1db0795d4 100644 --- a/dist/es/types/plugins/server.d.js +++ b/dist/es/types/plugins/server.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=server.d.js.map \ No newline at end of file diff --git a/dist/es/types/pouch.d.js b/dist/es/types/pouch.d.js index cd2523b6c5e..80e3a45f6d3 100644 --- a/dist/es/types/pouch.d.js +++ b/dist/es/types/pouch.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=pouch.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-attachment.d.js b/dist/es/types/rx-attachment.d.js index 228e0fbea46..3e8ce690c72 100644 --- a/dist/es/types/rx-attachment.d.js +++ b/dist/es/types/rx-attachment.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=rx-attachment.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-change-event.d.js b/dist/es/types/rx-change-event.d.js new file mode 100644 index 00000000000..ecfe821a68c --- /dev/null +++ b/dist/es/types/rx-change-event.d.js @@ -0,0 +1,3 @@ +export {}; +export {}; +//# sourceMappingURL=rx-change-event.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-collection.d.js b/dist/es/types/rx-collection.d.js index 61b1a91e457..d5b4bf986dd 100644 --- a/dist/es/types/rx-collection.d.js +++ b/dist/es/types/rx-collection.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=rx-collection.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-database.d.js b/dist/es/types/rx-database.d.js index a6835a50f29..a66189b52df 100644 --- a/dist/es/types/rx-database.d.js +++ b/dist/es/types/rx-database.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=rx-database.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-document.d.js b/dist/es/types/rx-document.d.js index 3d3153a39b6..614c0e3902c 100644 --- a/dist/es/types/rx-document.d.js +++ b/dist/es/types/rx-document.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=rx-document.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-error.d.js b/dist/es/types/rx-error.d.js index 486e8fb7ff7..d8398b6148a 100644 --- a/dist/es/types/rx-error.d.js +++ b/dist/es/types/rx-error.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=rx-error.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-plugin.d.js b/dist/es/types/rx-plugin.d.js index b52779828b5..8ab98e85fa8 100644 --- a/dist/es/types/rx-plugin.d.js +++ b/dist/es/types/rx-plugin.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=rx-plugin.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-schema.d.js b/dist/es/types/rx-schema.d.js index ac45ddf0efa..4e9357b22af 100644 --- a/dist/es/types/rx-schema.d.js +++ b/dist/es/types/rx-schema.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=rx-schema.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-storage.d.js b/dist/es/types/rx-storage.d.js new file mode 100644 index 00000000000..7b893f6b18e --- /dev/null +++ b/dist/es/types/rx-storage.d.js @@ -0,0 +1,3 @@ +export {}; +export {}; +//# sourceMappingURL=rx-storage.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-storage.interface.d.js b/dist/es/types/rx-storage.interface.d.js new file mode 100644 index 00000000000..5f06942fc41 --- /dev/null +++ b/dist/es/types/rx-storage.interface.d.js @@ -0,0 +1,3 @@ +export {}; +export {}; +//# sourceMappingURL=rx-storage.interface.d.js.map \ No newline at end of file diff --git a/dist/es/types/util.d.js b/dist/es/types/util.d.js index 05c2ecfb953..4e14938a97f 100644 --- a/dist/es/types/util.d.js +++ b/dist/es/types/util.d.js @@ -1,2 +1,3 @@ - +export {}; +export {}; //# sourceMappingURL=util.d.js.map \ No newline at end of file diff --git a/dist/es/util.js b/dist/es/util.js index 2b8ea353674..ae178b0259c 100644 --- a/dist/es/util.js +++ b/dist/es/util.js @@ -1,8 +1,3 @@ -/** - * this contains a mapping to basic dependencies - * which should be easy to change - */ -import randomToken from 'random-token'; import { default as deepClone } from 'clone'; /** * Returns an error that indicates that a plugin is missing @@ -63,13 +58,6 @@ export function hash(msg) { return Md5.hash(RXDB_HASH_SALT + msg); } -/** - * generate a new _id as db-primary-key - */ - -export function generateId() { - return randomToken(10) + ':' + now(); -} /** * Returns the current unix time in milliseconds * Because the accuracy of getTime() in javascript is bad, @@ -220,7 +208,10 @@ export function sortObject(obj) { */ export function stringifyFilter(key, value) { - if (value instanceof RegExp) return value.toString(); + if (value instanceof RegExp) { + return value.toString(); + } + return value; } /** @@ -239,6 +230,9 @@ export function randomCouchString() { return text; } +export function lastOfArray(ar) { + return ar[ar.length - 1]; +} /** * shuffle the given array */ @@ -349,11 +343,6 @@ export function createRevision(docData, deterministic_revs) { }); return stringMd5(JSON.stringify(docWithoutRev)); } -/** - * prefix of local pouchdb documents - */ - -export var LOCAL_PREFIX = '_local/'; /** * overwrites the getter with the actual value * Mostly used for caching stuff on the first run @@ -381,6 +370,15 @@ export function isFolderPath(name) { return false; } } +export function getFromMapOrThrow(map, key) { + var val = map.get(key); + + if (!val) { + throw new Error('missing value from map ' + key); + } + + return val; +} export var blobBufferUtil = { /** * depending if we are on node or browser, @@ -410,6 +408,13 @@ export var blobBufferUtil = { return blobBuffer; }, + isBlobBuffer: function isBlobBuffer(data) { + if (data instanceof Blob || Buffer.isBuffer(data)) { + return true; + } else { + return false; + } + }, toString: function toString(blobBuffer) { if (blobBuffer instanceof Buffer) { // node diff --git a/dist/lib/browserify.index.js b/dist/lib/browserify.index.js index 2afe4711dfd..e3ae96292bf 100644 --- a/dist/lib/browserify.index.js +++ b/dist/lib/browserify.index.js @@ -4,6 +4,8 @@ require("@babel/polyfill"); var RxDB = _interopRequireWildcard(require("./index.js")); +var RxDbPouchPlugin = _interopRequireWildcard(require("./plugins/pouchdb/index.js")); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } @@ -13,8 +15,8 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && * which produces a single file that can be embeded into the html * and used via window.RxDB */ -RxDB.addRxPlugin(require('pouchdb-adapter-idb')); -RxDB.addRxPlugin(require('pouchdb-adapter-http')); +RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb')); +RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http')); window['RxDB'] = RxDB; //# sourceMappingURL=browserify.index.js.map \ No newline at end of file diff --git a/dist/lib/change-event-buffer.js b/dist/lib/change-event-buffer.js index 8d1f52fd416..f8ee1f8049f 100644 --- a/dist/lib/change-event-buffer.js +++ b/dist/lib/change-event-buffer.js @@ -6,6 +6,8 @@ Object.defineProperty(exports, "__esModule", { exports.createChangeEventBuffer = createChangeEventBuffer; exports.ChangeEventBuffer = void 0; +var _operators = require("rxjs/operators"); + /** * a buffer-cache which holds the last X changeEvents of the collection */ @@ -23,7 +25,9 @@ var ChangeEventBuffer = /*#__PURE__*/function () { this.eventCounterMap = new WeakMap(); this.buffer = []; this.collection = collection; - this.subs.push(this.collection.$.subscribe(function (cE) { + this.subs.push(this.collection.$.pipe((0, _operators.filter)(function (cE) { + return !cE.isLocal; + })).subscribe(function (cE) { return _this._handleChangeEvent(cE); })); } @@ -31,7 +35,6 @@ var ChangeEventBuffer = /*#__PURE__*/function () { var _proto = ChangeEventBuffer.prototype; _proto._handleChangeEvent = function _handleChangeEvent(changeEvent) { - // console.log('changeEventBuffer()._handleChangeEvent()'); this.counter++; this.buffer.push(changeEvent); this.eventCounterMap.set(changeEvent, this.counter); @@ -110,6 +113,7 @@ var ChangeEventBuffer = /*#__PURE__*/function () { /** * use this to check if a change has already been handled * @returns true if change with revision exists + * TODO only used in the in-memory plugin, we should move it there. * */ ; @@ -121,7 +125,10 @@ var ChangeEventBuffer = /*#__PURE__*/function () { while (t > 0) { t--; var cE = this.buffer[t]; - if (cE.documentData && cE.documentData._rev === revision) return true; + + if (cE.documentData && cE.documentData._rev === revision) { + return true; + } } return false; diff --git a/dist/lib/core.js b/dist/lib/core.js index 9581c308c2a..93f69196802 100644 --- a/dist/lib/core.js +++ b/dist/lib/core.js @@ -5,19 +5,17 @@ Object.defineProperty(exports, "__esModule", { }); var _exportNames = { addRxPlugin: true, - PouchDB: true, - validateCouchDBString: true, - getBatch: true, - countAllUndeleted: true, - getNewestSequence: true, createRxDatabase: true, removeRxDatabase: true, - checkAdapter: true, isRxDatabase: true, dbCount: true, _collectionNamePrimary: true, isRxCollection: true, - _createRxCollection: true, + RxCollectionBase: true, + createRxCollection: true, + _handleFromStorageInstance: true, + _handleToStorageInstance: true, + fillObjectDataBeforeInsert: true, isRxDocument: true, getDocumentOrmPrototype: true, getDocumentPrototype: true, @@ -29,9 +27,16 @@ var _exportNames = { normalize: true, getFinalFields: true, getPreviousVersions: true, - RxChangeEvent: true, - getRxStoragePouchDb: true, - getPouchLocation: true, + getPseudoSchemaForVersion: true, + getSchemaByObjectPath: true, + findLocalDocument: true, + getSingleDocument: true, + getNewestSequence: true, + getAllDocuments: true, + writeSingleLocal: true, + writeSingle: true, + countAllUndeleted: true, + getBatch: true, _clearHook: true, createCrypter: true }; @@ -41,88 +46,76 @@ Object.defineProperty(exports, "addRxPlugin", { return _plugin.addRxPlugin; } }); -Object.defineProperty(exports, "PouchDB", { - enumerable: true, - get: function get() { - return _pouchDb.PouchDB; - } -}); -Object.defineProperty(exports, "validateCouchDBString", { +Object.defineProperty(exports, "createRxDatabase", { enumerable: true, get: function get() { - return _pouchDb.validateCouchDBString; + return _rxDatabase.createRxDatabase; } }); -Object.defineProperty(exports, "getBatch", { +Object.defineProperty(exports, "removeRxDatabase", { enumerable: true, get: function get() { - return _pouchDb.getBatch; + return _rxDatabase.removeRxDatabase; } }); -Object.defineProperty(exports, "countAllUndeleted", { +Object.defineProperty(exports, "isRxDatabase", { enumerable: true, get: function get() { - return _pouchDb.countAllUndeleted; + return _rxDatabase.isRxDatabase; } }); -Object.defineProperty(exports, "getNewestSequence", { +Object.defineProperty(exports, "dbCount", { enumerable: true, get: function get() { - return _pouchDb.getNewestSequence; + return _rxDatabase.dbCount; } }); -Object.defineProperty(exports, "createRxDatabase", { +Object.defineProperty(exports, "_collectionNamePrimary", { enumerable: true, get: function get() { - return _rxDatabase.createRxDatabase; + return _rxDatabase._collectionNamePrimary; } }); -Object.defineProperty(exports, "removeRxDatabase", { +Object.defineProperty(exports, "isRxCollection", { enumerable: true, get: function get() { - return _rxDatabase.removeRxDatabase; + return _rxCollection.isRxCollection; } }); -Object.defineProperty(exports, "checkAdapter", { +Object.defineProperty(exports, "RxCollectionBase", { enumerable: true, get: function get() { - return _rxDatabase.checkAdapter; + return _rxCollection.RxCollectionBase; } }); -Object.defineProperty(exports, "isRxDatabase", { +Object.defineProperty(exports, "createRxCollection", { enumerable: true, get: function get() { - return _rxDatabase.isInstanceOf; + return _rxCollection.createRxCollection; } }); -Object.defineProperty(exports, "dbCount", { +Object.defineProperty(exports, "_handleFromStorageInstance", { enumerable: true, get: function get() { - return _rxDatabase.dbCount; + return _rxCollectionHelper._handleFromStorageInstance; } }); -Object.defineProperty(exports, "_collectionNamePrimary", { +Object.defineProperty(exports, "_handleToStorageInstance", { enumerable: true, get: function get() { - return _rxDatabase._collectionNamePrimary; + return _rxCollectionHelper._handleToStorageInstance; } }); -Object.defineProperty(exports, "isRxCollection", { +Object.defineProperty(exports, "fillObjectDataBeforeInsert", { enumerable: true, get: function get() { - return _rxCollection.isInstanceOf; - } -}); -Object.defineProperty(exports, "_createRxCollection", { - enumerable: true, - get: function get() { - return _rxCollection.create; + return _rxCollectionHelper.fillObjectDataBeforeInsert; } }); Object.defineProperty(exports, "isRxDocument", { enumerable: true, get: function get() { - return _rxDocument.isInstanceOf; + return _rxDocument.isRxDocument; } }); Object.defineProperty(exports, "getDocumentOrmPrototype", { @@ -185,22 +178,64 @@ Object.defineProperty(exports, "getPreviousVersions", { return _rxSchema.getPreviousVersions; } }); -Object.defineProperty(exports, "RxChangeEvent", { +Object.defineProperty(exports, "getPseudoSchemaForVersion", { + enumerable: true, + get: function get() { + return _rxSchemaHelper.getPseudoSchemaForVersion; + } +}); +Object.defineProperty(exports, "getSchemaByObjectPath", { + enumerable: true, + get: function get() { + return _rxSchemaHelper.getSchemaByObjectPath; + } +}); +Object.defineProperty(exports, "findLocalDocument", { + enumerable: true, + get: function get() { + return _rxStorageHelper.findLocalDocument; + } +}); +Object.defineProperty(exports, "getSingleDocument", { + enumerable: true, + get: function get() { + return _rxStorageHelper.getSingleDocument; + } +}); +Object.defineProperty(exports, "getNewestSequence", { enumerable: true, get: function get() { - return _rxChangeEvent.RxChangeEvent; + return _rxStorageHelper.getNewestSequence; } }); -Object.defineProperty(exports, "getRxStoragePouchDb", { +Object.defineProperty(exports, "getAllDocuments", { enumerable: true, get: function get() { - return _rxStoragePouchdb.getRxStoragePouchDb; + return _rxStorageHelper.getAllDocuments; } }); -Object.defineProperty(exports, "getPouchLocation", { +Object.defineProperty(exports, "writeSingleLocal", { enumerable: true, get: function get() { - return _rxStoragePouchdb.getPouchLocation; + return _rxStorageHelper.writeSingleLocal; + } +}); +Object.defineProperty(exports, "writeSingle", { + enumerable: true, + get: function get() { + return _rxStorageHelper.writeSingle; + } +}); +Object.defineProperty(exports, "countAllUndeleted", { + enumerable: true, + get: function get() { + return _rxStorageHelper.countAllUndeleted; + } +}); +Object.defineProperty(exports, "getBatch", { + enumerable: true, + get: function get() { + return _rxStorageHelper.getBatch; } }); Object.defineProperty(exports, "_clearHook", { @@ -224,18 +259,16 @@ require("./types/modules/mocha.parallel.d"); require("./types/modules/modifiyjs.d"); -require("./types/modules/pouchdb-selector-core.d"); - require("./types/modules/random-token.d"); var _plugin = require("./plugin"); -var _pouchDb = require("./pouch-db"); - var _rxDatabase = require("./rx-database"); var _rxCollection = require("./rx-collection"); +var _rxCollectionHelper = require("./rx-collection-helper"); + var _rxDocument = require("./rx-document"); var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); @@ -244,9 +277,9 @@ var _rxQuery = require("./rx-query"); var _rxSchema = require("./rx-schema"); -var _rxChangeEvent = require("./rx-change-event"); +var _rxSchemaHelper = require("./rx-schema-helper"); -var _rxStoragePouchdb = require("./rx-storage-pouchdb"); +var _rxStorageHelper = require("./rx-storage-helper"); var _hooks = require("./hooks"); diff --git a/dist/lib/crypter.js b/dist/lib/crypter.js index 6a6af49c26d..2e7a1e324a4 100644 --- a/dist/lib/crypter.js +++ b/dist/lib/crypter.js @@ -14,6 +14,9 @@ var _util = require("./util"); /** * handle the en/decryption of documents-data + * TODO atm we have the crypter inside of rxdb core. + * Instead all should be moved to the encryption plugin + * and work via plugin hooks. */ var Crypter = /*#__PURE__*/function () { function Crypter(password, schema) { @@ -21,37 +24,44 @@ var Crypter = /*#__PURE__*/function () { this.schema = schema; } /** - * encrypt and stringify data + * encrypt a given string. * @overwritten by plugin (optional) */ var _proto = Crypter.prototype; - _proto._encryptValue = function _encryptValue(_value) { + _proto._encryptString = function _encryptString(_value) { throw (0, _util.pluginMissing)('encryption'); } /** - * decrypt and json-parse an encrypted value + * decrypt a given string. * @overwritten by plugin (optional) */ ; - _proto._decryptValue = function _decryptValue(_value) { + _proto._decryptString = function _decryptString(_value) { throw (0, _util.pluginMissing)('encryption'); }; _proto.encrypt = function encrypt(obj) { var _this = this; - if (!this.password) return obj; + if (!this.password) { + return obj; + } + obj = (0, _util.clone)(obj); this.schema.encryptedPaths.forEach(function (path) { var value = _objectPath["default"].get(obj, path); - if (typeof value === 'undefined') return; + if (typeof value === 'undefined') { + return; + } - var encrypted = _this._encryptValue(value); + var stringValue = JSON.stringify(value); + + var encrypted = _this._encryptString(stringValue); _objectPath["default"].set(obj, path, encrypted); }); @@ -66,11 +76,15 @@ var Crypter = /*#__PURE__*/function () { this.schema.encryptedPaths.forEach(function (path) { var value = _objectPath["default"].get(obj, path); - if (typeof value === 'undefined') return; + if (typeof value === 'undefined') { + return; + } + + var decrypted = _this2._decryptString(value); - var decrypted = _this2._decryptValue(value); + var decryptedParsed = JSON.parse(decrypted); - _objectPath["default"].set(obj, path, decrypted); + _objectPath["default"].set(obj, path, decryptedParsed); }); return obj; }; diff --git a/dist/lib/event-reduce.js b/dist/lib/event-reduce.js index 19a6c913dbe..1a6c4941e4c 100644 --- a/dist/lib/event-reduce.js +++ b/dist/lib/event-reduce.js @@ -10,6 +10,10 @@ exports.RXQUERY_QUERY_PARAMS_CACHE = void 0; var _eventReduceJs = require("event-reduce-js"); +var _hooks = require("./hooks"); + +var _rxChangeEvent = require("./rx-change-event"); + function getSortFieldsOfQuery(primaryKey, query) { if (!query.sort || query.sort.length === 0) { return [primaryKey]; @@ -25,16 +29,51 @@ exports.RXQUERY_QUERY_PARAMS_CACHE = RXQUERY_QUERY_PARAMS_CACHE; function getQueryParams(rxQuery) { if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) { - var storage = rxQuery.collection.database.storage; + var collection = rxQuery.collection; var queryJson = rxQuery.toJSON(); - var primaryKey = rxQuery.collection.schema.primaryPath; + var primaryKey = collection.schema.primaryPath; + /** + * Create a custom sort comparator + * that uses the hooks to ensure + * we send for example compressed documents to be sorted by compressed queries. + */ + + var sortComparator = collection.storageInstance.getSortComparator(queryJson); + + var useSortComparator = function useSortComparator(docA, docB) { + var sortComparatorData = { + docA: docA, + docB: docB, + rxQuery: rxQuery + }; + (0, _hooks.runPluginHooks)('preSortComparator', sortComparatorData); + return sortComparator(sortComparatorData.docA, sortComparatorData.docB); + }; + /** + * Create a custom query matcher + * that uses the hooks to ensure + * we send for example compressed documents to match compressed queries. + */ + + + var queryMatcher = collection.storageInstance.getQueryMatcher(queryJson); + + var useQueryMatcher = function useQueryMatcher(doc) { + var queryMatcherData = { + doc: doc, + rxQuery: rxQuery + }; + (0, _hooks.runPluginHooks)('preQueryMatcher', queryMatcherData); + return queryMatcher(queryMatcherData.doc); + }; + var ret = { primaryKey: rxQuery.collection.schema.primaryPath, skip: queryJson.skip, limit: queryJson.limit, sortFields: getSortFieldsOfQuery(primaryKey, queryJson), - sortComparator: storage.getSortComparator(primaryKey, queryJson), - queryMatcher: storage.getQueryMatcher(primaryKey, queryJson) + sortComparator: useSortComparator, + queryMatcher: useQueryMatcher }; RXQUERY_QUERY_PARAMS_CACHE.set(rxQuery, ret); return ret; @@ -57,7 +96,7 @@ function calculateNewResults(rxQuery, rxChangeEvents) { var previousResultsMap = rxQuery._resultsDataMap; var changed = false; var foundNonOptimizeable = rxChangeEvents.find(function (cE) { - var eventReduceEvent = cE.toEventReduceChangeEvent(); + var eventReduceEvent = (0, _rxChangeEvent.rxChangeEventToEventReduceChangeEvent)(cE); var actionName = (0, _eventReduceJs.calculateActionName)({ queryParams: queryParams, changeEvent: eventReduceEvent, diff --git a/dist/lib/hooks.js b/dist/lib/hooks.js index 0314636f736..da3e9228bfc 100644 --- a/dist/lib/hooks.js +++ b/dist/lib/hooks.js @@ -55,6 +55,34 @@ var HOOKS = { createRxSchema: [], preCreateRxQuery: [], createRxQuery: [], + + /** + * Runs before a document is send to the query matcher. + */ + preQueryMatcher: [], + + /** + * Runs before a document is send to the sortComparator. + */ + preSortComparator: [], + + /** + * Runs before a query is send to the + * prepareQuery function of the storage engine. + */ + prePrepareQuery: [], + + /** + * Runs before the document data is send to the + * bulkWrite of the storage instance + */ + preWriteToStorageInstance: [], + + /** + * Runs after the document data is ready from + * the storage instance. + */ + postReadFromInstance: [], createRxDocument: [], /** @@ -64,15 +92,12 @@ var HOOKS = { postCreateRxDocument: [], /** - * runs before a pouchdb-instance is created - * gets pouchParameters as attribute so you can manipulate them - * { - * location: string, - * adapter: any, - * settings: object - * } + * Runs before a RxStorageInstance is created + * gets the params of createStorageInstance() + * as attribute so you can manipulate them. + * Notice that you have to clone stuff before mutating the inputs. */ - preCreatePouchDb: [], + preCreateRxStorageInstance: [], /** * runs on the document-data before the document is migrated diff --git a/dist/lib/index.js b/dist/lib/index.js index 0ad99b10d5f..b90264450b1 100644 --- a/dist/lib/index.js +++ b/dist/lib/index.js @@ -31,11 +31,7 @@ var _encryption = require("./plugins/encryption"); var _update = require("./plugins/update"); -var _watchForChanges = require("./plugins/watch-for-changes"); - -var _replication = require("./plugins/replication"); - -var _adapterCheck = require("./plugins/adapter-check"); +var _replicationCouchdb = require("./plugins/replication-couchdb"); var _jsonDump = require("./plugins/json-dump"); @@ -47,6 +43,19 @@ var _localDocuments = require("./plugins/local-documents"); var _queryBuilder = require("./plugins/query-builder"); +var _pouchdb = require("./plugins/pouchdb"); + +Object.keys(_pouchdb).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _pouchdb[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _pouchdb[key]; + } + }); +}); + /** * this is the default rxdb-export * It has a batteries-included guarantee. @@ -60,9 +69,7 @@ var _queryBuilder = require("./plugins/query-builder"); (0, _core.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); (0, _core.addRxPlugin)(_encryption.RxDBEncryptionPlugin); (0, _core.addRxPlugin)(_update.RxDBUpdatePlugin); -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); -(0, _core.addRxPlugin)(_replication.RxDBReplicationPlugin); -(0, _core.addRxPlugin)(_adapterCheck.RxDBAdapterCheckPlugin); +(0, _core.addRxPlugin)(_replicationCouchdb.RxDBReplicationCouchDBPlugin); (0, _core.addRxPlugin)(_jsonDump.RxDBJsonDumpPlugin); (0, _core.addRxPlugin)(_inMemory.RxDBInMemoryPlugin); (0, _core.addRxPlugin)(_attachments.RxDBAttachmentsPlugin); diff --git a/dist/lib/overwritable.js b/dist/lib/overwritable.js index dda73ad1bcd..6712fc1e12a 100644 --- a/dist/lib/overwritable.js +++ b/dist/lib/overwritable.js @@ -20,6 +20,16 @@ var overwritable = { return false; }, + /** + * Deep freezes and object when in dev-mode. + * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode. + * Also we can ensure the readonly state via typescript + * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ + deepFreezeWhenDevMode: function deepFreezeWhenDevMode(obj) { + return obj; + }, + /** * validates if a password can be used * @overwritten by plugin (optional) @@ -29,20 +39,6 @@ var overwritable = { throw (0, _util.pluginMissing)('encryption'); }, - /** - * creates a key-compressor for the given schema - */ - createKeyCompressor: function createKeyCompressor(_rxSchema) { - throw (0, _util.pluginMissing)('key-compression'); - }, - - /** - * checks if the given adapter can be used - */ - checkAdapter: function checkAdapter(_adapter) { - throw (0, _util.pluginMissing)('adapter-check'); - }, - /** * overwritte to map error-codes to text-messages */ diff --git a/dist/lib/plugin.js b/dist/lib/plugin.js index fefabff2398..4b15e38cb36 100644 --- a/dist/lib/plugin.js +++ b/dist/lib/plugin.js @@ -17,12 +17,12 @@ var _rxCollection = require("./rx-collection"); var _rxDatabase = require("./rx-database"); -var _pouchDb = require("./pouch-db"); - var _overwritable = require("./overwritable"); var _hooks = require("./hooks"); +var _rxError = require("./rx-error"); + /** * this handles how plugins are added to rxdb * basically it changes the internal prototypes @@ -41,6 +41,10 @@ var PROTOTYPES = { RxDatabase: _rxDatabase.RxDatabaseBase.prototype }; var ADDED_PLUGINS = new Set(); +/** + * Add a plugin to the RxDB library. + * Plugins are added globally and cannot be removed. + */ function addRxPlugin(plugin) { (0, _hooks.runPluginHooks)('preAddRxPlugin', { @@ -53,19 +57,21 @@ function addRxPlugin(plugin) { } else { ADDED_PLUGINS.add(plugin); } + /** + * Since version 10.0.0 we decoupled pouchdb from + * the rxdb core. Therefore pouchdb plugins must be added + * with the addPouchPlugin() method of the pouchdb plugin. + */ - if (!plugin.rxdb) { - // pouchdb-plugin - if (typeof plugin === 'object' && plugin["default"]) plugin = plugin["default"]; - - _pouchDb.PouchDB.plugin(plugin); - return; - } + if (!plugin.rxdb) { + throw (0, _rxError.newRxTypeError)('PL1', { + plugin: plugin + }); + } // prototype-overwrites - var rxPlugin = plugin; // prototype-overwrites - if (rxPlugin.prototypes) { + if (plugin.prototypes) { Object.entries(plugin.prototypes).forEach(function (_ref) { var name = _ref[0], fun = _ref[1]; @@ -74,12 +80,12 @@ function addRxPlugin(plugin) { } // overwritable-overwrites - if (rxPlugin.overwritable) { + if (plugin.overwritable) { Object.assign(_overwritable.overwritable, plugin.overwritable); } // extend-hooks - if (rxPlugin.hooks) { + if (plugin.hooks) { Object.entries(plugin.hooks).forEach(function (_ref2) { var name = _ref2[0], fun = _ref2[1]; diff --git a/dist/lib/plugins/attachments.js b/dist/lib/plugins/attachments.js index f1668e8baf4..c5f9b7896b2 100644 --- a/dist/lib/plugins/attachments.js +++ b/dist/lib/plugins/attachments.js @@ -5,7 +5,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromPouchDocument = fromPouchDocument; +exports.fromStorageInstanceResult = fromStorageInstanceResult; exports.putAttachment = putAttachment; exports.getAttachment = getAttachment; exports.allAttachments = allAttachments; @@ -19,13 +19,11 @@ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/ var _operators = require("rxjs/operators"); -var _rxChangeEvent = require("./../rx-change-event"); - var _util = require("./../util"); var _rxError = require("../rx-error"); -var _pouchDb = require("../pouch-db"); +var _rxStorageHelper = require("../rx-storage-helper"); function ensureSchemaSupportsAttachments(doc) { var schemaJson = doc.collection.schema.jsonSchema; @@ -37,17 +35,6 @@ function ensureSchemaSupportsAttachments(doc) { } } -function resyncRxDocument(doc) { - var startTime = (0, _util.now)(); - return doc.collection.pouch.get(doc.primary).then(function (docDataFromPouch) { - var data = doc.collection._handleFromPouch(docDataFromPouch); - - var endTime = (0, _util.now)(); - var changeEvent = (0, _rxChangeEvent.createUpdateEvent)(doc.collection, data, null, startTime, endTime, doc); - doc.$emit(changeEvent); - }); -} - var _assignMethodsToAttachment = function _assignMethodsToAttachment(attachment) { Object.entries(attachment.doc.collection.attachments).forEach(function (_ref) { var funName = _ref[0], @@ -71,43 +58,122 @@ var RxAttachment = /*#__PURE__*/function () { id = _ref2.id, type = _ref2.type, length = _ref2.length, - digest = _ref2.digest, - rev = _ref2.rev; + digest = _ref2.digest; this.doc = doc; this.id = id; this.type = type; this.length = length; this.digest = digest; - this.rev = rev; _assignMethodsToAttachment(this); } var _proto = RxAttachment.prototype; - _proto.remove = function remove() { - var _this = this; + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var _this = this; + + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + this.doc._atomicQueue = this.doc._atomicQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var docWriteData, writeResult, newData; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + docWriteData = (0, _util.flatClone)(_this.doc._data); + docWriteData._attachments = (0, _util.flatClone)(docWriteData._attachments); + delete docWriteData._attachments[_this.id]; + _context.next = 5; + return (0, _rxStorageHelper.writeSingle)(_this.doc.collection.storageInstance, { + previous: _this.doc._data, + document: docWriteData + }); - return this.doc.collection.pouch.removeAttachment(this.doc.primary, this.id, this.doc._data._rev).then(function () { - return resyncRxDocument(_this.doc); - }); - } + case 5: + writeResult = _context.sent; + newData = (0, _util.flatClone)(_this.doc._data); + newData._rev = writeResult._rev; + newData._attachments = writeResult._attachments; + + _this.doc._dataSync$.next(newData); + + case 10: + case "end": + return _context.stop(); + } + } + }, _callee); + }))); + return _context2.abrupt("return", this.doc._atomicQueue); + + case 2: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function remove() { + return _remove.apply(this, arguments); + } + + return remove; + }() /** * returns the data for the attachment */ ; - _proto.getData = function getData() { - var _this2 = this; + _proto.getData = + /*#__PURE__*/ + function () { + var _getData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var plainData, dataString, ret; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.doc.collection.storageInstance.getAttachmentData(this.doc.primary, this.id); + + case 2: + plainData = _context3.sent; + + if (!shouldEncrypt(this.doc.collection.schema)) { + _context3.next = 11; + break; + } + + _context3.next = 6; + return _util.blobBufferUtil.toString(plainData); + + case 6: + dataString = _context3.sent; + ret = _util.blobBufferUtil.createBlobBuffer(this.doc.collection._crypter._decryptString(dataString), this.type); + return _context3.abrupt("return", ret); + + case 11: + return _context3.abrupt("return", plainData); + + case 12: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function getData() { + return _getData.apply(this, arguments); + } - return this.doc.collection.pouch.getAttachment(this.doc.primary, this.id).then(function (data) { - if (shouldEncrypt(_this2.doc.collection.schema)) { - return _util.blobBufferUtil.toString(data).then(function (dataString) { - return _util.blobBufferUtil.createBlobBuffer(_this2.doc.collection._crypter._decryptValue(dataString), _this2.type); - }); - } else return data; - }); - }; + return getData; + }(); _proto.getStringData = function getStringData() { return this.getData().then(function (bufferBlob) { @@ -120,14 +186,13 @@ var RxAttachment = /*#__PURE__*/function () { exports.RxAttachment = RxAttachment; -function fromPouchDocument(id, pouchDocAttachment, rxDocument) { +function fromStorageInstanceResult(id, attachmentData, rxDocument) { return new RxAttachment({ doc: rxDocument, id: id, - type: pouchDocAttachment.content_type, - length: pouchDocAttachment.length, - digest: pouchDocAttachment.digest, - rev: pouchDocAttachment.revpos + type: attachmentData.type, + length: attachmentData.length, + digest: attachmentData.digest }); } @@ -144,83 +209,110 @@ function putAttachment(_x) { function _putAttachment() { - _putAttachment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(_ref3) { - var _this5 = this; + _putAttachment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(_ref4) { + var _this4 = this; var id, data, - _ref3$type, + _ref4$type, type, skipIfSame, - blobBuffer, - _args2 = arguments; + dataString, + encrypted, + _args5 = arguments; - return _regenerator["default"].wrap(function _callee2$(_context2) { + return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context5.prev = _context5.next) { case 0: - id = _ref3.id, data = _ref3.data, _ref3$type = _ref3.type, type = _ref3$type === void 0 ? 'text/plain' : _ref3$type; - skipIfSame = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : false; + id = _ref4.id, data = _ref4.data, _ref4$type = _ref4.type, type = _ref4$type === void 0 ? 'text/plain' : _ref4$type; + skipIfSame = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : true; ensureSchemaSupportsAttachments(this); + /** + * Then encryption plugin is only able to encrypt strings, + * so unpack as string first. + */ - if (shouldEncrypt(this.collection.schema)) { - data = this.collection._crypter._encryptValue(data); + if (!shouldEncrypt(this.collection.schema)) { + _context5.next = 9; + break; } - blobBuffer = _util.blobBufferUtil.createBlobBuffer(data, type); - this._atomicQueue = this._atomicQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { - var currentMeta, newHash; - return _regenerator["default"].wrap(function _callee$(_context) { + _context5.next = 6; + return _util.blobBufferUtil.toString(data); + + case 6: + dataString = _context5.sent; + encrypted = this.collection._crypter._encryptString(dataString); + data = _util.blobBufferUtil.createBlobBuffer(encrypted, 'text/plain'); + + case 9: + this._atomicQueue = this._atomicQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var currentMeta, newHash, docWriteData, useData, writeResult, attachmentData, attachment, newData; + return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { - switch (_context.prev = _context.next) { + switch (_context4.prev = _context4.next) { case 0: - if (!(skipIfSame && _this5._data._attachments && _this5._data._attachments[id])) { - _context.next = 7; + if (!(skipIfSame && _this4._data._attachments && _this4._data._attachments[id])) { + _context4.next = 7; break; } - currentMeta = _this5._data._attachments[id]; - _context.next = 4; - return (0, _pouchDb.pouchAttachmentBinaryHash)(data); + currentMeta = _this4._data._attachments[id]; + _context4.next = 4; + return _this4.collection.database.storage.hash(data); case 4: - newHash = _context.sent; + newHash = _context4.sent; - if (!(currentMeta.content_type === type && currentMeta.digest === newHash)) { - _context.next = 7; + if (!(currentMeta.type === type && currentMeta.digest === newHash)) { + _context4.next = 7; break; } - return _context.abrupt("return", _this5.getAttachment(id)); + return _context4.abrupt("return", _this4.getAttachment(id)); case 7: - return _context.abrupt("return", _this5.collection.pouch.putAttachment(_this5.primary, id, _this5._data._rev, blobBuffer, type).then(function () { - return _this5.collection.pouch.get(_this5.primary); - }).then(function (docData) { - var attachmentData = docData._attachments[id]; - var attachment = fromPouchDocument(id, attachmentData, _this5); - _this5._data._rev = docData._rev; - _this5._data._attachments = docData._attachments; - return resyncRxDocument(_this5).then(function () { - return attachment; - }); - })); - - case 8: + docWriteData = (0, _util.flatClone)(_this4._data); + docWriteData._attachments = (0, _util.flatClone)(docWriteData._attachments); + useData = typeof data === 'string' ? Buffer.from(data) : data; + docWriteData._attachments[id] = { + type: type, + data: useData + }; + _context4.next = 13; + return (0, _rxStorageHelper.writeSingle)(_this4.collection.storageInstance, { + previous: _this4._data, + document: docWriteData + }); + + case 13: + writeResult = _context4.sent; + attachmentData = writeResult._attachments[id]; + attachment = fromStorageInstanceResult(id, attachmentData, _this4); + newData = (0, _util.flatClone)(_this4._data); + newData._rev = writeResult._rev; + newData._attachments = writeResult._attachments; + + _this4._dataSync$.next(newData); + + return _context4.abrupt("return", attachment); + + case 21: case "end": - return _context.stop(); + return _context4.stop(); } } - }, _callee); + }, _callee4); }))); - return _context2.abrupt("return", this._atomicQueue); + return _context5.abrupt("return", this._atomicQueue); - case 7: + case 11: case "end": - return _context2.stop(); + return _context5.stop(); } } - }, _callee2, this); + }, _callee5, this); })); return _putAttachment.apply(this, arguments); } @@ -232,7 +324,7 @@ function getAttachment(id) { if (!docData._attachments || !docData._attachments[id]) return null; var attachmentData = docData._attachments[id]; - var attachment = fromPouchDocument(id, attachmentData, this); + var attachment = fromStorageInstanceResult(id, attachmentData, this); return attachment; } /** @@ -241,16 +333,19 @@ function getAttachment(id) { function allAttachments() { - var _this3 = this; + var _this2 = this; ensureSchemaSupportsAttachments(this); var docData = this._dataSync$.getValue(); // if there are no attachments, the field is missing - if (!docData._attachments) return []; + if (!docData._attachments) { + return []; + } + return Object.keys(docData._attachments).map(function (id) { - return fromPouchDocument(id, docData._attachments[id], _this3); + return fromStorageInstanceResult(id, docData._attachments[id], _this2); }); } @@ -259,71 +354,66 @@ function preMigrateDocument(_x2) { } function _preMigrateDocument() { - _preMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(data) { + _preMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(data) { var attachments, mustDecrypt, newAttachments; - return _regenerator["default"].wrap(function _callee4$(_context4) { + return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context7.prev = _context7.next) { case 0: attachments = data.docData._attachments; if (!attachments) { - _context4.next = 7; + _context7.next = 7; break; } mustDecrypt = !!shouldEncrypt(data.oldCollection.schema); newAttachments = {}; - _context4.next = 6; + _context7.next = 6; return Promise.all(Object.keys(attachments).map( /*#__PURE__*/function () { - var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(attachmentId) { + var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(attachmentId) { var attachment, docPrimary, rawAttachmentData; - return _regenerator["default"].wrap(function _callee3$(_context3) { + return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context6.prev = _context6.next) { case 0: attachment = attachments[attachmentId]; docPrimary = data.docData[data.oldCollection.schema.primaryPath]; - _context3.next = 4; - return data.oldCollection.pouchdb.getAttachment(docPrimary, attachmentId); + _context6.next = 4; + return data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId); case 4: - rawAttachmentData = _context3.sent; + rawAttachmentData = _context6.sent; if (!mustDecrypt) { - _context3.next = 9; + _context6.next = 9; break; } - _context3.next = 8; + _context6.next = 8; return _util.blobBufferUtil.toString(rawAttachmentData).then(function (dataString) { - return _util.blobBufferUtil.createBlobBuffer(data.oldCollection._crypter._decryptValue(dataString), attachment.content_type); + return _util.blobBufferUtil.createBlobBuffer(data.oldCollection._crypter._decryptString(dataString), attachment.type); }); case 8: - rawAttachmentData = _context3.sent; + rawAttachmentData = _context6.sent; case 9: newAttachments[attachmentId] = { - digest: attachment.digest, - length: attachment.length, - revpos: attachment.revpos, - content_type: attachment.content_type, - stub: false, - // set this to false because now we have the full data + type: attachment.type, data: rawAttachmentData }; case 10: case "end": - return _context3.stop(); + return _context6.stop(); } } - }, _callee3); + }, _callee6); })); return function (_x4) { - return _ref6.apply(this, arguments); + return _ref7.apply(this, arguments); }; }())); @@ -336,10 +426,10 @@ function _preMigrateDocument() { case 7: case "end": - return _context4.stop(); + return _context7.stop(); } } - }, _callee4); + }, _callee7); })); return _preMigrateDocument.apply(this, arguments); } @@ -349,19 +439,19 @@ function postMigrateDocument(_x3) { } function _postMigrateDocument() { - _postMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(action) { - return _regenerator["default"].wrap(function _callee5$(_context5) { + _postMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(_action) { + return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { - switch (_context5.prev = _context5.next) { + switch (_context8.prev = _context8.next) { case 0: - return _context5.abrupt("return"); + return _context8.abrupt("return"); case 1: case "end": - return _context5.stop(); + return _context8.stop(); } } - }, _callee5); + }, _callee8); })); return _postMigrateDocument.apply(this, arguments); } @@ -375,18 +465,21 @@ var prototypes = { proto.allAttachments = allAttachments; Object.defineProperty(proto, 'allAttachments$', { get: function allAttachments$() { - var _this4 = this; + var _this3 = this; return this._dataSync$.pipe((0, _operators.map)(function (data) { - if (!data['_attachments']) return {}; + if (!data['_attachments']) { + return {}; + } + return data['_attachments']; }), (0, _operators.map)(function (attachmentsData) { return Object.entries(attachmentsData); }), (0, _operators.map)(function (entries) { - return entries.map(function (_ref4) { - var id = _ref4[0], - attachmentData = _ref4[1]; - return fromPouchDocument(id, attachmentData, _this4); + return entries.map(function (_ref5) { + var id = _ref5[0], + attachmentData = _ref5[1]; + return fromStorageInstanceResult(id, attachmentData, _this3); }); })); } diff --git a/dist/lib/plugins/backup/index.js b/dist/lib/plugins/backup/index.js index 54e15caac27..5f5ff219102 100644 --- a/dist/lib/plugins/backup/index.js +++ b/dist/lib/plugins/backup/index.js @@ -25,7 +25,11 @@ var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _pouchDb = require("../../pouch-db"); +var _rxError = require("../../rx-error"); + +var _rxStorageHelper = require("../../rx-storage-helper"); + +var _util = require("../../util"); var _fileUtil = require("./file-util"); @@ -135,10 +139,10 @@ function addToBackupStates(db, state) { BACKUP_STATES_BY_DB.set(db, []); } - var ar = BACKUP_STATES_BY_DB.get(db); + var ar = (0, _util.getFromMapOrThrow)(BACKUP_STATES_BY_DB, db); if (!ar) { - throw new Error('this should never happen'); + throw (0, _rxError.newRxError)('SNH'); } ar.push(state); @@ -232,7 +236,7 @@ var RxBackupState = /*#__PURE__*/function () { case 4: _context5.next = 6; - return (0, _pouchDb.getNewestSequence)(collection.pouch); + return (0, _rxStorageHelper.getNewestSequence)(collection.storageInstance); case 6: newestSeq = _context5.sent; @@ -247,7 +251,7 @@ var RxBackupState = /*#__PURE__*/function () { lastSequence = meta.collectionStates[collectionName].lastSequence; hasMore = true; _loop = /*#__PURE__*/_regenerator["default"].mark(function _loop() { - var pouchChanges, docIds, docs; + var changesResult, docIds, docs; return _regenerator["default"].wrap(function _loop$(_context4) { while (1) { switch (_context4.prev = _context4.next) { @@ -257,28 +261,25 @@ var RxBackupState = /*#__PURE__*/function () { case 2: _context4.next = 4; - return collection.pouch.changes({ - live: false, - since: lastSequence, + return collection.storageInstance.getChangedDocuments({ + startSequence: lastSequence, limit: _this2.options.batchSize, - include_docs: false + order: 'asc' }); case 4: - pouchChanges = _context4.sent; - lastSequence = pouchChanges.last_seq; + changesResult = _context4.sent; + lastSequence = changesResult.lastSequence; meta.collectionStates[collectionName].lastSequence = lastSequence; - docIds = pouchChanges.results.filter(function (doc) { - if (processedDocuments.has(doc.id) && doc.seq < newestSeq) { + docIds = changesResult.changedDocuments.filter(function (changedDocument) { + if (processedDocuments.has(changedDocument.id) && changedDocument.sequence < newestSeq) { return false; } else { - processedDocuments.add(doc.id); + processedDocuments.add(changedDocument.id); return true; } }).map(function (r) { return r.id; - }).filter(function (id) { - return !id.startsWith('_design/'); }) // unique . // unique filter(function (elem, pos, arr) { @@ -444,11 +445,7 @@ var RxBackupState = /*#__PURE__*/function () { var collections = Object.values(this.database.collections); collections.forEach(function (collection) { - var changes$ = (0, _rxjs.fromEvent)(collection.pouch.changes({ - since: 'now', - live: true, - include_docs: false - }), 'change'); + var changes$ = collection.storageInstance.changeStream(); var sub = changes$.subscribe(function () { _this3.persistOnce(); }); diff --git a/dist/lib/plugins/dev-mode/check-names.js b/dist/lib/plugins/dev-mode/check-names.js new file mode 100644 index 00000000000..3db10a80817 --- /dev/null +++ b/dist/lib/plugins/dev-mode/check-names.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validateDatabaseName = validateDatabaseName; + +var _rxError = require("../../rx-error"); + +var _util = require("../../util"); + +var validCouchDBStringRegexStr = '^[a-z][_$a-z0-9]*$'; +var validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr); +/** + * Validates that a given string is ok to be used with couchdb-collection-names. + * We only allow these strings as database- or collectionnames because it ensures + * that you later do not get in troubble when you want to use the database together witch couchdb. + * + * @link https://wiki.apache.org/couchdb/HTTP_database_API + * @throws {Error} + */ + +function validateDatabaseName(name) { + if (typeof name !== 'string' || name.length === 0) { + throw (0, _rxError.newRxTypeError)('UT1', { + name: name + }); + } // do not check, if foldername is given + + + if ((0, _util.isFolderPath)(name)) { + return true; + } + + if (!name.match(validCouchDBStringRegex)) { + throw (0, _rxError.newRxError)('UT2', { + regex: validCouchDBStringRegexStr, + givenName: name + }); + } + + return true; +} + +//# sourceMappingURL=check-names.js.map \ No newline at end of file diff --git a/dist/lib/plugins/dev-mode/check-schema.js b/dist/lib/plugins/dev-mode/check-schema.js index cedbac48f21..53a4cff0146 100644 --- a/dist/lib/plugins/dev-mode/check-schema.js +++ b/dist/lib/plugins/dev-mode/check-schema.js @@ -29,8 +29,9 @@ var _entityProperties = require("./entity-properties"); * @throws {Error} */ function checkFieldNameRegex(fieldName) { - if (fieldName === '') return; - if (fieldName === '_id') return; + if (fieldName === '') return; // TODO why is the fieldname allowed to be empty string? + + if (fieldName === '_deleted') return; if (['properties', 'language'].includes(fieldName)) { throw (0, _rxError.newRxError)('SC23', { @@ -125,7 +126,7 @@ function validateFieldsDeep(jsonSchema) { if (!isNested) { // check underscore fields if (fieldName.charAt(0) === '_') { - if (fieldName === '_id' && schemaObj.primary) { + if (fieldName === '_deleted') { return; } @@ -178,6 +179,12 @@ function getSchemaPropertyRealPath(shortPath) { function checkSchema(jsonSchema) { + if (!jsonSchema.primaryKey) { + throw (0, _rxError.newRxError)('SC30', { + schema: jsonSchema + }); + } + if (!jsonSchema.hasOwnProperty('properties')) { throw (0, _rxError.newRxError)('SC29', { schema: jsonSchema @@ -199,20 +206,11 @@ function checkSchema(jsonSchema) { } validateFieldsDeep(jsonSchema); - var primaryPath; Object.keys(jsonSchema.properties).forEach(function (key) { var value = jsonSchema.properties[key]; // check primary - if (value.primary) { - if (primaryPath) { - throw (0, _rxError.newRxError)('SC12', { - value: value - }); - } - - primaryPath = key; - - if (value.index) { + if (key === jsonSchema.primaryKey) { + if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) { throw (0, _rxError.newRxError)('SC13', { value: value }); @@ -224,7 +222,7 @@ function checkSchema(jsonSchema) { }); } - if (value.encrypted) { + if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) { throw (0, _rxError.newRxError)('SC15', { value: value }); diff --git a/dist/lib/plugins/dev-mode/error-messages.js b/dist/lib/plugins/dev-mode/error-messages.js index e2e98ae9e13..e286dd7c69b 100644 --- a/dist/lib/plugins/dev-mode/error-messages.js +++ b/dist/lib/plugins/dev-mode/error-messages.js @@ -16,6 +16,9 @@ var ERROR_MESSAGES = { UT2: "collection- and database-names must match the regex\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\'", UT3: 'replication-direction must either be push or pull or both. But not none', UT4: 'given leveldown is no valid adapter', + // plugins + PL1: 'Given plugin is not RxDB plugin. Pouchdb plugins must be added via addPouchPlugin()', + PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.', // pouch-db.js P1: 'PouchDB.getBatch: limit must be > 2', // rx-query @@ -41,19 +44,19 @@ var ERROR_MESSAGES = { MQ8: 'Can\'t mix sort syntaxes. Use either array or object', // rx-database DB1: 'RxDocument.prepare(): another instance on this adapter has a different password', - DB2: 'RxDatabase.collection(): collection-names cannot start with underscore _', - DB3: 'RxDatabase.collection(): collection already exists. use myDatabase.[collectionName] to get it', - DB4: 'RxDatabase.collection(): schema is missing', - DB5: 'RxDatabase.collection(): collection-name not allowed', - DB6: 'RxDatabase.collection(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', - DB7: 'RxDatabase.collection(): schema encrypted but no password given', + DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _', + DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it', + DB4: 'RxDatabase.addCollections(): schema is missing', + DB5: 'RxDatabase.addCollections(): collection-name not allowed', + DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', + DB7: 'RxDatabase.addCollections(): schema encrypted but no password given', DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\n' + 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional', DB9: 'RxDatabase.create(): Adapter not added. Use RxDB.plugin(require(\'pouchdb-adapter-[adaptername]\');', DB10: 'RxDatabase.create(): To use leveldown-adapters, you have to add the leveldb-plugin. Use RxDB.plugin(require(\'pouchdb-adapter-leveldb\'));', DB11: 'RxDatabase.create(): Invalid db-name, folder-paths must not have an ending slash', // rx-collection COL1: 'RxDocument.insert() You cannot insert an existing document', - COL2: 'RxCollection.insert() do not provide ._id when it is not the primary key', + // removed in 10.0.0 - COL2: 'RxCollection.insert() do not provide ._id when it is not the primary key', COL3: 'RxCollection.upsert() does not work without primary', COL4: 'RxCollection.atomicUpsert() does not work without primary', COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)', @@ -83,7 +86,7 @@ var ERROR_MESSAGES = { DOC9: 'final fields cannot be modified', DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected', DOC11: 'RxDocument.save(): cant save deleted document', - DOC12: 'RxDocument.save(): error', + // removed in 10.0.0 DOC12: 'RxDocument.save(): error', DOC13: 'RxDocument.remove(): Document is already deleted', DOC14: 'RxDocument.destroy() does not exist', DOC15: 'query cannot be an array', @@ -100,8 +103,8 @@ var ERROR_MESSAGES = { EN2: 'validatePassword: min-length of password not complied', // plugins/json-dump.js JD1: 'You must create the collections before you can import their data', - JD2: 'RxCollection.importDump(): the imported json relies on a different schema', - JD3: 'RxCollection.importDump(): json.passwordHash does not match the own', + JD2: 'RxCollection.importJSON(): the imported json relies on a different schema', + JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own', // plugins/leader-election.js // plugins/local-documents.js LD1: 'RxDocument.allAttachments$ cant use attachments on local documents', @@ -113,10 +116,10 @@ var ERROR_MESSAGES = { LD7: 'Local document already exists', // plugins/replication.js RC1: 'Replication: already added', - RC2: 'RxCollection.sync() query must be from the same RxCollection', - RC3: 'RxCollection.sync() Do not use a collection\'s pouchdb as remote, use the collection instead', - RC4: 'RxReplicationState.awaitInitialReplication() cannot await inital replication when live: true', - RC5: 'RxReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance', + RC2: 'RxCollection.syncCouchDB() query must be from the same RxCollection', + RC3: 'RxCollection.syncCouchDB() Do not use a collection\'s pouchdb as remote, use the collection instead', + RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication when live: true', + RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance', // plugins/dev-mode/check-schema.js SC1: 'fieldnames do not match the regex', SC2: 'SchemaCheck: name \'item\' reserved for array-fields', @@ -127,7 +130,7 @@ var ERROR_MESSAGES = { SC8: 'SchemaCheck: first level-fields cannot start with underscore _', SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically', SC11: 'SchemaCheck: schema needs a number >=0 as version', - SC12: 'SchemaCheck: primary can only be defined once', + // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once', SC13: 'SchemaCheck: primary is always index, do not declare it as index', SC14: 'SchemaCheck: primary is always unique, do not declare it as index', SC15: 'SchemaCheck: primary cannot be encrypted', @@ -145,17 +148,25 @@ var ERROR_MESSAGES = { SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level', SC28: 'SchemaCheck: encrypted fields is not defined in the schema', SC29: 'SchemaCheck: missing object key \'properties\'', + SC30: 'SchemaCheck: primaryKey is required', // plugins/dev-mode DEV1: 'dev-mode added multiple times, ' + 'this is likely because you have mixed up the import from the the plugins/core and the full RxDB', // plugins/validate.js VD1: 'Sub-schema not found, does the schemaPath exists in your schema?', VD2: 'object does not match schema', // plugins/in-memory.js - IM1: 'InMemory: Memory-Adapter must be added. Use RxDB.plugin(require(\'pouchdb-adapter-memory\'));', + IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\'pouchdb-adapter-memory\'));', IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead', // plugins/server.js - S1: 'You cannot create collections after calling RxDatabase.server()' // plugins/replication-graphql.js + S1: 'You cannot create collections after calling RxDatabase.server()', + // plugins/replication-graphql.js + /** + * Should never be thrown, use this for + * null checks etc. so you do not have to increase the + * build size with error message strings. + */ + SNH: 'This should never happen' }; exports.ERROR_MESSAGES = ERROR_MESSAGES; diff --git a/dist/lib/plugins/dev-mode/index.js b/dist/lib/plugins/dev-mode/index.js index d76da2a24f2..e9f48cf19f5 100644 --- a/dist/lib/plugins/dev-mode/index.js +++ b/dist/lib/plugins/dev-mode/index.js @@ -4,8 +4,10 @@ Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { + deepFreezeWhenDevMode: true, RxDBDevModePlugin: true }; +exports.deepFreezeWhenDevMode = deepFreezeWhenDevMode; exports.RxDBDevModePlugin = void 0; var _errorMessages = require("./error-messages"); @@ -34,6 +36,38 @@ var _checkQuery = require("./check-query"); var _rxError = require("../../rx-error"); +var _checkNames = require("./check-names"); + +Object.keys(_checkNames).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _checkNames[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _checkNames[key]; + } + }); +}); + +var deepFreeze = require('deep-freeze'); +/** + * Deep freezes and object when in dev-mode. + * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode. + * Also we can ensure the readonly state via typescript + * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ + + +function deepFreezeWhenDevMode(obj) { + // direct return if falsy + if (!obj) { + return obj; + } + + return deepFreeze(obj); +} + var DEV_MODE_PLUGIN_NAME = 'dev-mode'; var RxDBDevModePlugin = { name: DEV_MODE_PLUGIN_NAME, @@ -42,6 +76,7 @@ var RxDBDevModePlugin = { isDevMode: function isDevMode() { return true; }, + deepFreezeWhenDevMode: deepFreezeWhenDevMode, tunnelErrorMessage: function tunnelErrorMessage(code) { if (!_errorMessages.ERROR_MESSAGES[code]) { console.error('RxDB: Error-Code not known: ' + code); diff --git a/dist/lib/plugins/dev-mode/unallowed-properties.js b/dist/lib/plugins/dev-mode/unallowed-properties.js index f0602eaf155..5e3a2027812 100644 --- a/dist/lib/plugins/dev-mode/unallowed-properties.js +++ b/dist/lib/plugins/dev-mode/unallowed-properties.js @@ -10,10 +10,10 @@ var _rxError = require("../../rx-error"); var _entityProperties = require("./entity-properties"); -var _pouchDb = require("../../pouch-db"); - var _util = require("../../util"); +var _checkNames = require("./check-names"); + /** * if the name of a collection * clashes with a property of RxDatabase, @@ -28,12 +28,7 @@ function ensureCollectionNameValid(args) { } function ensureDatabaseNameIsValid(args) { - /** - * Not all strings can be used as couchdb collection name - * So we only allow couchdb-valid string as databse name - * which solves some strange bugs. - */ - (0, _pouchDb.validateCouchDBString)(args.name); + (0, _checkNames.validateDatabaseName)(args.name); /** * The server-plugin has problems when a path with and ending slash is given * So we do not allow this. diff --git a/dist/lib/plugins/encryption.js b/dist/lib/plugins/encryption.js index 93bc3be3739..2e912b7612e 100644 --- a/dist/lib/plugins/encryption.js +++ b/dist/lib/plugins/encryption.js @@ -10,6 +10,10 @@ exports.decrypt = decrypt; exports.storePasswordHashIntoDatabase = storePasswordHashIntoDatabase; exports.RxDBEncryptionPlugin = exports.overwritable = exports.prototypes = exports.rxdb = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + var _aes = _interopRequireDefault(require("crypto-js/aes")); var cryptoEnc = _interopRequireWildcard(require("crypto-js/enc-utf8")); @@ -18,6 +22,8 @@ var _rxError = require("../rx-error"); var _util = require("../util"); +var _rxStorageHelper = require("../rx-storage-helper"); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } @@ -41,13 +47,13 @@ function decrypt(cipherText, password) { return decrypted.toString(cryptoEnc); } -var _encryptValue = function _encryptValue(value) { - return encrypt(JSON.stringify(value), this.password); +var _encryptString = function _encryptString(value) { + return encrypt(value, this.password); }; -var _decryptValue = function _decryptValue(encryptedValue) { +var _decryptString = function _decryptString(encryptedValue) { var decrypted = decrypt(encryptedValue, this.password); - return JSON.parse(decrypted); + return decrypted; }; /** @@ -55,40 +61,77 @@ var _decryptValue = function _decryptValue(encryptedValue) { * to ensure there is/was no other instance with a different password * which would cause strange side effects when both instances save into the same db */ -function storePasswordHashIntoDatabase(rxDatabase) { - if (!rxDatabase.password) { - return Promise.resolve(false); - } - - var pwHash = (0, _util.hash)(rxDatabase.password); - return rxDatabase.internalStore.get(_util.LOCAL_PREFIX + 'pwHash')["catch"](function () { - return null; - }).then(function (pwHashDoc) { - /** - * if pwHash was not saved, we save it, - * this operation might throw because another instance runs save at the same time, - */ - if (!pwHashDoc) { - return rxDatabase.internalStore.put({ - _id: _util.LOCAL_PREFIX + 'pwHash', - value: pwHash - })["catch"](function () { - return null; - }).then(function () { - return true; - }); - } else if (pwHash !== pwHashDoc.value) { - // different hash was already set by other instance - return rxDatabase.destroy().then(function () { - throw (0, _rxError.newRxError)('DB1', { - passwordHash: (0, _util.hash)(rxDatabase.password), - existingPasswordHash: pwHashDoc.value - }); - }); - } +function storePasswordHashIntoDatabase(_x) { + return _storePasswordHashIntoDatabase.apply(this, arguments); +} - return true; - }); +function _storePasswordHashIntoDatabase() { + _storePasswordHashIntoDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(rxDatabase) { + var pwHash, pwHashDocumentId, pwHashDoc, docData; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (rxDatabase.password) { + _context.next = 2; + break; + } + + return _context.abrupt("return", Promise.resolve(false)); + + case 2: + pwHash = (0, _util.hash)(rxDatabase.password); + pwHashDocumentId = 'pwHash'; + _context.next = 6; + return (0, _rxStorageHelper.findLocalDocument)(rxDatabase.localDocumentsStore, pwHashDocumentId); + + case 6: + pwHashDoc = _context.sent; + + if (pwHashDoc) { + _context.next = 14; + break; + } + + docData = { + _id: pwHashDocumentId, + value: pwHash, + _attachments: {} + }; + _context.next = 11; + return rxDatabase.localDocumentsStore.bulkWrite([{ + document: docData + }]); + + case 11: + return _context.abrupt("return", true); + + case 14: + if (!(pwHash !== pwHashDoc.value)) { + _context.next = 20; + break; + } + + _context.next = 17; + return rxDatabase.destroy(); + + case 17: + throw (0, _rxError.newRxError)('DB1', { + passwordHash: (0, _util.hash)(rxDatabase.password), + existingPasswordHash: pwHashDoc.value + }); + + case 20: + return _context.abrupt("return", true); + + case 21: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _storePasswordHashIntoDatabase.apply(this, arguments); } var rxdb = true; @@ -98,8 +141,8 @@ var prototypes = { * set crypto-functions for the Crypter.prototype */ Crypter: function Crypter(proto) { - proto._encryptValue = _encryptValue; - proto._decryptValue = _decryptValue; + proto._encryptString = _encryptString; + proto._decryptString = _decryptString; } }; exports.prototypes = prototypes; diff --git a/dist/lib/plugins/in-memory.js b/dist/lib/plugins/in-memory.js index fc3faef6dd8..b6d330f854a 100644 --- a/dist/lib/plugins/in-memory.js +++ b/dist/lib/plugins/in-memory.js @@ -9,9 +9,14 @@ exports.replicateExistingDocuments = replicateExistingDocuments; exports.setIndexes = setIndexes; exports.streamChangedDocuments = streamChangedDocuments; exports.applyChangedDocumentToPouch = applyChangedDocumentToPouch; -exports.spawnInMemory = spawnInMemory; +exports.inMemory = inMemory; +exports.prepareInMemoryRxCollection = prepareInMemoryRxCollection; exports.RxDBInMemoryPlugin = exports.prototypes = exports.rxdb = exports.InMemoryRxCollection = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); @@ -24,7 +29,7 @@ var _rxCollection = require("../rx-collection"); var _util = require("../util"); -var _core = require("../core"); +var _pouchdb = require("../plugins/pouchdb"); var _crypter = require("../crypter"); @@ -32,13 +37,11 @@ var _changeEventBuffer = require("../change-event-buffer"); var _rxSchema = require("../rx-schema"); -var _pouchDb = require("../pouch-db"); - var _rxError = require("../rx-error"); -var _rxStoragePouchdb = require("../rx-storage-pouchdb"); +var _rxChangeEvent = require("../rx-change-event"); -var _watchForChanges = require("../plugins/watch-for-changes"); +var _rxCollectionHelper = require("../rx-collection-helper"); /** * This plugin adds RxCollection.inMemory() @@ -46,8 +49,6 @@ var _watchForChanges = require("../plugins/watch-for-changes"); * So you can do faster queries and also query over encrypted fields. * Writes will still run on the original collection */ -// add the watch-for-changes-plugin -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); var collectionCacheMap = new WeakMap(); var collectionPromiseCacheMap = new WeakMap(); var BULK_DOC_OPTIONS = { @@ -60,20 +61,18 @@ var BULK_DOC_OPTIONS_FALSE = { var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { (0, _inheritsLoose2["default"])(InMemoryRxCollection, _RxCollectionBase); - function InMemoryRxCollection(parentCollection) { + function InMemoryRxCollection(parentCollection, pouchSettings) { var _this; - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _this = _RxCollectionBase.call(this, parentCollection.database, parentCollection.name, toCleanSchema(parentCollection.schema), pouchSettings, // pouchSettings {}, parentCollection._methods) || this; _this._eventCounter = 0; + _this.parentCollection = parentCollection; + _this.pouchSettings = pouchSettings; _this._isInMemory = true; - _this._parentCollection = parentCollection; - - _this._parentCollection.onDestroy.then(function () { + parentCollection.onDestroy.then(function () { return _this.destroy(); }); - _this._crypter = (0, _crypter.createCrypter)(_this.database.password, _this.schema); _this._changeStreams = []; /** @@ -84,9 +83,10 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _this.onDestroy.then(function () { _this._changeStreams.forEach(function (stream) { return stream.cancel(); - }); + }); // delete all data + - _this.pouch.destroy(); + _this.storageInstance.internals.pouch.destroy(); }); // add orm functions and options from parent @@ -100,8 +100,6 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { } }); }); - var storage = (0, _rxStoragePouchdb.getRxStoragePouchDb)('memory'); - _this.pouch = storage.createStorageInstance('rxdb-in-memory', (0, _util.randomCouchString)(10), 0); _this._observable$ = new _rxjs.Subject(); _this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)((0, _assertThisInitialized2["default"])(_this)); var parentProto = Object.getPrototypeOf(parentCollection); @@ -117,7 +115,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _proto.prepareChild = function prepareChild() { var _this2 = this; - return setIndexes(this.schema, this.pouch).then(function () { + return setIndexes(this.schema, this.storageInstance.internals.pouch).then(function () { _this2._subs.push(_this2._observable$.subscribe(function (cE) { // when data changes, send it to RxDocument in docCache var doc = _this2._docCache.get(cE.documentId); @@ -126,23 +124,13 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { })); }) // initial sync parent's docs to own .then(function () { - return replicateExistingDocuments(_this2._parentCollection, _this2); + return replicateExistingDocuments(_this2.parentCollection, _this2); }).then(function () { - /** - * call watchForChanges() on both sides, - * to ensure none-rxdb-changes like replication - * will fire into the change-event-stream - */ - _this2._parentCollection.watchForChanges(); - - _this2.watchForChanges(); /** * create an ongoing replications between both sides */ - - var thisToParentSub = streamChangedDocuments(_this2).pipe((0, _operators.mergeMap)(function (doc) { - return applyChangedDocumentToPouch(_this2._parentCollection, doc).then(function () { + return applyChangedDocumentToPouch(_this2.parentCollection, doc).then(function () { return doc['_rev']; }); })).subscribe(function (changeRev) { @@ -153,7 +141,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _this2._subs.push(thisToParentSub); - var parentToThisSub = streamChangedDocuments(_this2._parentCollection).subscribe(function (doc) { + var parentToThisSub = streamChangedDocuments(_this2.parentCollection).subscribe(function (doc) { return applyChangedDocumentToPouch(_this2, doc); }); @@ -169,7 +157,10 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _proto.awaitPersistence = function awaitPersistence() { var _this3 = this; - if (this._nonPersistentRevisions.size === 0) return Promise.resolve(); + if (this._nonPersistentRevisions.size === 0) { + return Promise.resolve(); + } + return (0, _rxjs.firstValueFrom)(this._nonPersistentRevisionsSubject.pipe((0, _operators.filter)(function () { return _this3._nonPersistentRevisions.size === 0; }))); @@ -192,7 +183,9 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { }; _proto.$emit = function $emit(changeEvent) { - if (this._changeEventBuffer.hasChangeWithRevision(changeEvent.documentData && changeEvent.documentData._rev)) { + var doc = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + + if (this._changeEventBuffer.hasChangeWithRevision(doc && doc._rev)) { return; } @@ -203,7 +196,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { if (this._eventCounter === 10) { this._eventCounter = 0; - this.pouch.compact(); + this.storageInstance.internals.pouch.compact(); } } /** @@ -213,7 +206,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { */ ; - _proto.sync = function sync() { + _proto.syncCouchDB = function syncCouchDB() { throw (0, _rxError.newRxError)('IM2'); }; @@ -232,7 +225,6 @@ exports.InMemoryRxCollection = InMemoryRxCollection; function toCleanSchema(rxSchema) { var newSchemaJson = (0, _util.clone)(rxSchema.jsonSchema); newSchemaJson.keyCompression = false; - delete newSchemaJson.properties._id; delete newSchemaJson.properties._rev; delete newSchemaJson.properties._attachments; @@ -255,7 +247,8 @@ function toCleanSchema(rxSchema) { function replicateExistingDocuments(fromCollection, toCollection) { - return fromCollection.pouch.allDocs({ + var pouch = fromCollection.storageInstance.internals.pouch; + return pouch.allDocs({ attachments: false, include_docs: true }).then(function (allRows) { @@ -265,14 +258,15 @@ function replicateExistingDocuments(fromCollection, toCollection) { return !doc.language; }) // do not replicate design-docs .map(function (doc) { - return fromCollection._handleFromPouch(doc); + return (0, _rxCollectionHelper._handleFromStorageInstance)(fromCollection, doc); }) // swap back primary because keyCompression:false .map(function (doc) { - return fromCollection.schema.swapPrimaryToId(doc); + var primaryKey = fromCollection.schema.primaryPath; + return (0, _pouchdb.pouchSwapPrimaryToId)(primaryKey, doc); }); if (docs.length === 0) return Promise.resolve([]); // nothing to replicate else { - return toCollection.pouch.bulkDocs({ + return toCollection.storageInstance.internals.pouch.bulkDocs({ docs: docs }, BULK_DOC_OPTIONS_FALSE).then(function () { return docs; @@ -310,8 +304,12 @@ function streamChangedDocuments(rxCollection) { var prevFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (_i) { return true; }; - if (!rxCollection._doNotEmitSet) rxCollection._doNotEmitSet = new Set(); - var observable = (0, _rxjs.fromEvent)(rxCollection.pouch.changes({ + + if (!rxCollection._doNotEmitSet) { + rxCollection._doNotEmitSet = new Set(); + } + + var observable = (0, _rxjs.fromEvent)(rxCollection.storageInstance.internals.pouch.changes({ since: 'now', live: true, include_docs: true @@ -328,11 +326,19 @@ function streamChangedDocuments(rxCollection) { (0, _operators.filter)(function (change) { // changes on the doNotEmit-list shell not be fired var emitFlag = change.id + ':' + change.doc._rev; - if (rxCollection._doNotEmitSet.has(emitFlag)) return false;else return true; + + if (rxCollection._doNotEmitSet.has(emitFlag)) { + return false; + } else { + return true; + } }), (0, _operators.filter)(function (change) { return prevFilter(change); }), (0, _operators.map)(function (change) { - return rxCollection._handleFromPouch(change.doc); + return (0, _rxCollectionHelper._handleFromStorageInstance)(rxCollection, change.doc); + }), (0, _operators.map)(function (d) { + var primaryKey = rxCollection.schema.primaryPath; + return (0, _pouchdb.pouchSwapIdToPrimary)(primaryKey, d); })); return observable; } @@ -343,17 +349,20 @@ function streamChangedDocuments(rxCollection) { function applyChangedDocumentToPouch(rxCollection, docData) { - if (!rxCollection._doNotEmitSet) rxCollection._doNotEmitSet = new Set(); - - var transformedDoc = rxCollection._handleToPouch(docData); + if (!rxCollection._doNotEmitSet) { + rxCollection._doNotEmitSet = new Set(); + } - return rxCollection.pouch.get(transformedDoc._id).then(function (oldDoc) { + var primaryKey = rxCollection.schema.primaryPath; + var transformedDoc = (0, _rxCollectionHelper._handleToStorageInstance)(rxCollection, docData); + transformedDoc = (0, _pouchdb.pouchSwapPrimaryToId)(primaryKey, transformedDoc); + return rxCollection.storageInstance.internals.pouch.get(transformedDoc._id).then(function (oldDoc) { return transformedDoc._rev = oldDoc._rev; })["catch"](function () { // doc not found, do not use a revision delete transformedDoc._rev; }).then(function () { - return rxCollection.pouch.bulkDocs({ + return rxCollection.storageInstance.internals.pouch.bulkDocs({ docs: [transformedDoc] }, BULK_DOC_OPTIONS); }).then(function (bulkRet) { @@ -379,36 +388,105 @@ var INIT_DONE = false; * called in the proto of RxCollection */ -function spawnInMemory() { - var _this5 = this; - - if (!INIT_DONE) { - INIT_DONE = true; // ensure memory-adapter is added +function inMemory() { + return _inMemory.apply(this, arguments); +} - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.memory) throw (0, _rxError.newRxError)('IM1'); - } +function _inMemory() { + _inMemory = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var _this5 = this; + + var col, preparePromise; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (INIT_DONE) { + _context.next = 4; + break; + } + + INIT_DONE = true; // ensure memory-adapter is added + + if (!(!_pouchdb.PouchDB.adapters || !_pouchdb.PouchDB.adapters.memory)) { + _context.next = 4; + break; + } + + throw (0, _rxError.newRxError)('IM1'); + + case 4: + if (!collectionCacheMap.has(this)) { + _context.next = 6; + break; + } + + return _context.abrupt("return", collectionPromiseCacheMap.get(this).then(function () { + return collectionCacheMap.get(_this5); + })); + + case 6: + col = new InMemoryRxCollection(this); + _context.next = 9; + return prepareInMemoryRxCollection(col); + + case 9: + preparePromise = col.prepareChild(); + collectionCacheMap.set(this, col); + collectionPromiseCacheMap.set(this, preparePromise); + return _context.abrupt("return", preparePromise.then(function () { + return col; + })); + + case 13: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + return _inMemory.apply(this, arguments); +} - if (collectionCacheMap.has(this)) { - // already exists for this collection -> wait until synced - return collectionPromiseCacheMap.get(this).then(function () { - return collectionCacheMap.get(_this5); - }); - } +function prepareInMemoryRxCollection(_x) { + return _prepareInMemoryRxCollection.apply(this, arguments); +} - var col = new InMemoryRxCollection(this); - var preparePromise = col.prepareChild(); - collectionCacheMap.set(this, col); - collectionPromiseCacheMap.set(this, preparePromise); - return preparePromise.then(function () { - return col; - }); +function _prepareInMemoryRxCollection() { + _prepareInMemoryRxCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(instance) { + var memoryStorage; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + memoryStorage = (0, _pouchdb.getRxStoragePouch)('memory', {}); + _context2.next = 3; + return memoryStorage.createStorageInstance({ + databaseName: 'rxdb-in-memory', + collectionName: (0, _util.randomCouchString)(10), + schema: instance.schema.jsonSchema, + options: instance.pouchSettings + }); + + case 3: + instance.storageInstance = _context2.sent; + instance.pouch = instance.storageInstance.internals.pouch; + + case 5: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _prepareInMemoryRxCollection.apply(this, arguments); } var rxdb = true; exports.rxdb = rxdb; var prototypes = { RxCollection: function RxCollection(proto) { - proto.inMemory = spawnInMemory; + proto.inMemory = inMemory; } }; exports.prototypes = prototypes; diff --git a/dist/lib/plugins/json-dump.js b/dist/lib/plugins/json-dump.js index a0258b12e09..952dbe49c3b 100644 --- a/dist/lib/plugins/json-dump.js +++ b/dist/lib/plugins/json-dump.js @@ -11,7 +11,7 @@ var _rxQuery = require("../rx-query"); var _rxError = require("../rx-error"); -var _rxChangeEvent = require("../rx-change-event"); +var _rxCollectionHelper = require("../rx-collection-helper"); /** * this plugin adds the json export/import capabilities to RxDB @@ -42,7 +42,7 @@ function dumpRxDatabase() { return _this.collections[colName]; }); return Promise.all(useCollections.map(function (col) { - return col.dump(decrypted); + return col.exportJSON(decrypted); })).then(function (cols) { json.collections = cols; return json; @@ -69,7 +69,7 @@ var importDumpRxDatabase = function importDumpRxDatabase(dump) { } return Promise.all(dump.collections.map(function (colDump) { - return _this2.collections[colDump.name].importDump(colDump); + return _this2.collections[colDump.name].importJSON(colDump); })); }; @@ -90,7 +90,7 @@ var dumpRxCollection = function dumpRxCollection() { } var query = (0, _rxQuery.createRxQuery)('find', (0, _rxQuery._getDefaultQuery)(this), this); - return this._pouchFind(query, undefined, encrypted).then(function (docs) { + return this._queryStorageInstance(query, undefined, encrypted).then(function (docs) { json.docs = docs.map(function (docData) { delete docData._rev; delete docData._attachments; @@ -125,23 +125,17 @@ function importDumpRxCollection(exportedJSON) { }) // validate schema .map(function (doc) { return _this3.schema.validate(doc); - }) // transform - .map(function (doc) { - return _this3._handleToPouch(doc); }); var startTime; return this.database.lockedRun( // write to disc function () { startTime = (0, _util.now)(); - return _this3.pouch.bulkDocs(docs); - }).then(function () { - var endTime = (0, _util.now)(); - docs.forEach(function (doc) { - // emit change events - var emitEvent = (0, _rxChangeEvent.createInsertEvent)(_this3, doc, startTime, endTime); - - _this3.$emit(emitEvent); + var writeMe = docs.map(function (doc) { + return { + document: (0, _rxCollectionHelper._handleToStorageInstance)(_this3, doc) + }; }); + return _this3.storageInstance.bulkWrite(writeMe); }); } @@ -149,12 +143,12 @@ var rxdb = true; exports.rxdb = rxdb; var prototypes = { RxDatabase: function RxDatabase(proto) { - proto.dump = dumpRxDatabase; - proto.importDump = importDumpRxDatabase; + proto.exportJSON = dumpRxDatabase; + proto.importJSON = importDumpRxDatabase; }, RxCollection: function RxCollection(proto) { - proto.dump = dumpRxCollection; - proto.importDump = importDumpRxCollection; + proto.exportJSON = dumpRxCollection; + proto.importJSON = importDumpRxCollection; } }; exports.prototypes = prototypes; diff --git a/dist/lib/plugins/key-compression.js b/dist/lib/plugins/key-compression.js index b2a10bd9aa4..a422b64d0ec 100644 --- a/dist/lib/plugins/key-compression.js +++ b/dist/lib/plugins/key-compression.js @@ -1,104 +1,142 @@ "use strict"; -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); - Object.defineProperty(exports, "__esModule", { value: true }); -exports.create = create; -exports.RxDBKeyCompressionPlugin = exports.overwritable = exports.prototypes = exports.rxdb = exports.KeyCompressor = void 0; - -var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); +exports.createCompressionState = createCompressionState; +exports.getCompressionStateByStorageInstance = getCompressionStateByStorageInstance; +exports.RxDBKeyCompressionPlugin = exports.overwritable = exports.prototypes = exports.rxdb = void 0; var _jsonschemaKeyCompression = require("jsonschema-key-compression"); -var _util = require("../util"); - /** * this plugin adds the keycompression-capabilities to rxdb * if you dont use this, ensure that you set disableKeyComression to false in your schema */ -var KeyCompressor = /*#__PURE__*/function () { - function KeyCompressor(schema) { - this.schema = schema; - } - /** - * @overwrites itself on the first call - */ +/** + * Cache the compression table and the compressed schema + * by the storage instance for better performance. + */ +var COMPRESSION_STATE_BY_COLLECTION = new WeakMap(); - var _proto = KeyCompressor.prototype; - +function createCompressionState(schema) { + var primaryPath = schema.primaryKey; + var table = (0, _jsonschemaKeyCompression.createCompressionTable)(schema, _jsonschemaKeyCompression.DEFAULT_COMPRESSION_FLAG, [ /** - * compress the keys of an object via the compression-table + * Do not compress the primary path + * to make it easier to debug errors. */ - _proto.compress = function compress(obj) { - if (!this.schema.doKeyCompression()) { - return obj; - } else { - return (0, _jsonschemaKeyCompression.compressObject)(this.table, obj); - } - }; - - _proto.decompress = function decompress(compressedObject) { - if (!this.schema.doKeyCompression()) { - return compressedObject; - } else { - return (0, _jsonschemaKeyCompression.decompressObject)(this.table, compressedObject); - } - } + primaryPath, '_rev', '_attachments', '_deleted']); + var compressedSchema = (0, _jsonschemaKeyCompression.createCompressedJsonSchema)(table, schema); /** - * get the full compressed-key-path of a object-path + * the key compression module does not know about indexes + * in the schema, so we have to also compress them here. */ - ; - _proto.transformKey = function transformKey(objectPath) { - return (0, _jsonschemaKeyCompression.compressedPath)(this.table, objectPath); // > '|a.|b' + if (schema.indexes) { + var newIndexes = schema.indexes.map(function (idx) { + if (Array.isArray(idx)) { + return idx.map(function (subIdx) { + return (0, _jsonschemaKeyCompression.compressedPath)(table, subIdx); + }); + } else { + return (0, _jsonschemaKeyCompression.compressedPath)(table, idx); + } + }); + compressedSchema.indexes = newIndexes; } - /** - * replace the keys of a query-obj with the compressed keys - * @return compressed queryJSON - */ - ; - _proto.compressQuery = function compressQuery(queryJSON) { - if (!this.schema.doKeyCompression()) { - return queryJSON; - } else { - return (0, _jsonschemaKeyCompression.compressQuery)(this.table, queryJSON); - } + return { + table: table, + schema: compressedSchema }; +} - (0, _createClass2["default"])(KeyCompressor, [{ - key: "table", - get: function get() { - var jsonSchema = this.schema.normalized; - var table = (0, _jsonschemaKeyCompression.createCompressionTable)(jsonSchema, _jsonschemaKeyCompression.DEFAULT_COMPRESSION_FLAG, [this.schema.primaryPath, '_rev', '_attachments']); - return (0, _util.overwriteGetterForCaching)(this, 'table', table); - } - }]); - return KeyCompressor; -}(); +function getCompressionStateByStorageInstance(collection) { + var state = COMPRESSION_STATE_BY_COLLECTION.get(collection); -exports.KeyCompressor = KeyCompressor; + if (!state) { + state = createCompressionState(collection.schema.jsonSchema); + COMPRESSION_STATE_BY_COLLECTION.set(collection, state); + } -function create(schema) { - return new KeyCompressor(schema); + return state; } var rxdb = true; exports.rxdb = rxdb; var prototypes = {}; exports.prototypes = prototypes; -var overwritable = { - createKeyCompressor: create -}; +var overwritable = {}; exports.overwritable = overwritable; var RxDBKeyCompressionPlugin = { name: 'key-compression', rxdb: rxdb, prototypes: prototypes, - overwritable: overwritable + overwritable: overwritable, + hooks: { + /** + * replace the keys of a query-obj with the compressed keys + * because the storage instance only know the compressed schema + * @return compressed queryJSON + */ + prePrepareQuery: function prePrepareQuery(input) { + var rxQuery = input.rxQuery; + var mangoQuery = input.mangoQuery; + + if (!rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var compressionState = getCompressionStateByStorageInstance(rxQuery.collection); + var compressedQuery = (0, _jsonschemaKeyCompression.compressQuery)(compressionState.table, mangoQuery); + input.mangoQuery = compressedQuery; + }, + preCreateRxStorageInstance: function preCreateRxStorageInstance(params) { + /** + * When key compression is used, + * the storage instance only knows about the compressed schema + */ + if (params.schema.keyCompression) { + var compressionState = createCompressionState(params.schema); + params.schema = compressionState.schema; + } + }, + preQueryMatcher: function preQueryMatcher(params) { + if (!params.rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.rxQuery.collection); + params.doc = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.doc); + }, + preSortComparator: function preSortComparator(params) { + if (!params.rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.rxQuery.collection); + params.docA = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.docA); + params.docB = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.docB); + }, + preWriteToStorageInstance: function preWriteToStorageInstance(params) { + if (!params.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.collection); + params.doc = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.doc); + }, + postReadFromInstance: function postReadFromInstance(params) { + if (!params.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.collection); + params.doc = (0, _jsonschemaKeyCompression.decompressObject)(state.table, params.doc); + } + } }; exports.RxDBKeyCompressionPlugin = RxDBKeyCompressionPlugin; diff --git a/dist/lib/plugins/local-documents.js b/dist/lib/plugins/local-documents.js index bc8ba7687e5..881b37fb447 100644 --- a/dist/lib/plugins/local-documents.js +++ b/dist/lib/plugins/local-documents.js @@ -5,7 +5,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.RxDBLocalDocumentsPlugin = exports.overwritable = exports.prototypes = exports.rxdb = exports.RxLocalDocument = void 0; +exports.RxDBLocalDocumentsPlugin = exports.RxLocalDocument = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -17,8 +17,6 @@ var _objectPath = _interopRequireDefault(require("object-path")); var _rxDocument = require("../rx-document"); -var _rxChangeEvent = require("../rx-change-event"); - var _docCache = require("../doc-cache"); var _rxError = require("../rx-error"); @@ -31,11 +29,10 @@ var _rxCollection = require("../rx-collection"); var _operators = require("rxjs/operators"); -/** - * This plugin adds the local-documents-support - * Local documents behave equal then with pouchdb - * @link https://pouchdb.com/guides/local-documents.html - */ +var _rxStorageHelper = require("../rx-storage-helper"); + +var _overwritable = require("../overwritable"); + var DOC_CACHE_BY_PARENT = new WeakMap(); var _getDocCache = function _getDocCache(parent) { @@ -56,7 +53,10 @@ var _getChangeSub = function _getChangeSub(parent) { var docCache = _getDocCache(parent); var doc = docCache.get(cE.documentId); - if (doc) doc._handleChangeEvent(cE); + + if (doc) { + doc._handleChangeEvent(cE); + } }); parent._subs.push(sub); @@ -86,25 +86,19 @@ var RxLocalDocument = /*#__PURE__*/function (_RxDocumentParent) { exports.RxLocalDocument = RxLocalDocument; -var _getPouchByParent = function _getPouchByParent(parent) { - if ((0, _rxDatabase.isInstanceOf)(parent)) return parent.internalStore; // database - else return parent.pouch; // collection -}; +function _getKeyObjectStorageInstanceByParent(parent) { + if ((0, _rxDatabase.isRxDatabase)(parent)) { + return parent.localDocumentsStore; // database + } else { + return parent.localDocumentsStore; // collection + } +} var RxLocalDocumentPrototype = { - toPouchJson: function toPouchJson() { - var data = (0, _util.clone)(this._data); - data._id = _util.LOCAL_PREFIX + this.id; - }, - get isLocal() { return true; }, - get parentPouch() { - return _getPouchByParent(this.parent); - }, - // // overwrites // @@ -115,9 +109,9 @@ var RxLocalDocumentPrototype = { switch (changeEvent.operation) { case 'UPDATE': - var newData = (0, _util.clone)(changeEvent.documentData); + var newData = changeEvent.documentData; - this._dataSync$.next((0, _util.clone)(newData)); + this._dataSync$.next(newData); break; @@ -127,7 +121,7 @@ var RxLocalDocumentPrototype = { docCache["delete"](this.primary); - this._deleted$.next(true); + this._isDeleted$.next(true); break; } @@ -156,7 +150,9 @@ var RxLocalDocumentPrototype = { return this.parent.$emit(changeEvent); }, get: function get(objPath) { - if (!this._data) return undefined; + if (!this._data) { + return undefined; + } if (typeof objPath !== 'string') { throw (0, _rxError.newRxTypeError)('LD2', { @@ -166,7 +162,7 @@ var RxLocalDocumentPrototype = { var valueObj = _objectPath["default"].get(this._data, objPath); - valueObj = (0, _util.clone)(valueObj); + valueObj = _overwritable.overwritable.deepFreezeWhenDevMode(valueObj); return valueObj; }, get$: function get$(path) { @@ -184,7 +180,7 @@ var RxLocalDocumentPrototype = { set: function set(objPath, value) { if (!value) { // object path not set, overwrite whole data - var data = (0, _util.clone)(objPath); + var data = (0, _util.flatClone)(objPath); data._rev = this._data._rev; this._data = data; return this; @@ -197,40 +193,48 @@ var RxLocalDocumentPrototype = { }); } - if (Object.is(this.get(objPath), value)) return; + if (Object.is(this.get(objPath), value)) { + return; + } _objectPath["default"].set(this._data, objPath, value); return this; }, _saveData: function _saveData(newData) { - var _this2 = this; - var oldData = this._dataSync$.getValue(); - newData = (0, _util.clone)(newData); - newData._id = _util.LOCAL_PREFIX + this.id; - var startTime = (0, _util.now)(); - return this.parentPouch.put(newData).then(function (res) { - var endTime = (0, _util.now)(); - newData._rev = res.rev; - var changeEvent = new _rxChangeEvent.RxChangeEvent('UPDATE', _this2.id, (0, _util.clone)(newData), (0, _rxDatabase.isInstanceOf)(_this2.parent) ? _this2.parent.token : _this2.parent.database.token, (0, _rxCollection.isInstanceOf)(_this2.parent) ? _this2.parent.name : null, true, startTime, endTime, oldData, _this2); + var storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); + + newData._id = this.id; + return storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }]).then(function (res) { + var docResult = res.success.get(newData._id); - _this2.$emit(changeEvent); + if (!docResult) { + throw (0, _util.getFromMapOrThrow)(res.error, newData._id); + } + + newData._rev = docResult._rev; }); }, remove: function remove() { - var _this3 = this; - - var removeId = _util.LOCAL_PREFIX + this.id; - var startTime = (0, _util.now)(); - return this.parentPouch.remove(removeId, this._data._rev).then(function () { - _getDocCache(_this3.parent)["delete"](_this3.id); + var _this2 = this; - var endTime = (0, _util.now)(); - var changeEvent = new _rxChangeEvent.RxChangeEvent('DELETE', _this3.id, (0, _util.clone)(_this3._data), (0, _rxDatabase.isInstanceOf)(_this3.parent) ? _this3.parent.token : _this3.parent.database.token, (0, _rxCollection.isInstanceOf)(_this3.parent) ? _this3.parent.name : null, true, startTime, endTime, null, _this3); + var storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); - _this3.$emit(changeEvent); + var writeData = { + _id: this.id, + _deleted: true, + _attachments: {} + }; + return (0, _rxStorageHelper.writeSingleLocal)(storageInstance, { + previous: this._data, + document: writeData + }).then(function () { + _getDocCache(_this2.parent)["delete"](_this2.id); }); } }; @@ -283,36 +287,29 @@ RxLocalDocument.create = function (id, data, parent) { */ -function insertLocal(id, data) { - var _this4 = this; +function insertLocal(id, docData) { + var _this3 = this; - if ((0, _rxCollection.isInstanceOf)(this) && this._isInMemory) { - return this._parentCollection.insertLocal(id, data); + if ((0, _rxCollection.isRxCollection)(this) && this._isInMemory) { + return this.parentCollection.insertLocal(id, docData); } - data = (0, _util.clone)(data); return this.getLocal(id).then(function (existing) { if (existing) { throw (0, _rxError.newRxError)('LD7', { id: id, - data: data + data: docData }); } // create new one - var pouch = _getPouchByParent(_this4); - - var saveData = (0, _util.clone)(data); - saveData._id = _util.LOCAL_PREFIX + id; - var startTime = (0, _util.now)(); - return pouch.put(saveData).then(function (res) { - data._rev = res.rev; - var newDoc = RxLocalDocument.create(id, data, _this4); - var endTime = (0, _util.now)(); - var changeEvent = new _rxChangeEvent.RxChangeEvent('INSERT', id, (0, _util.clone)(data), (0, _rxDatabase.isInstanceOf)(_this4) ? _this4.token : _this4.database.token, (0, _rxCollection.isInstanceOf)(_this4) ? _this4.name : '', true, startTime, endTime, undefined, newDoc); - - _this4.$emit(changeEvent); - + docData = (0, _util.flatClone)(docData); + docData._id = id; + return (0, _rxStorageHelper.writeSingleLocal)(_getKeyObjectStorageInstanceByParent(_this3), { + document: docData + }).then(function (res) { + docData._rev = res._rev; + var newDoc = RxLocalDocument.create(id, docData, _this3); return newDoc; }); }); @@ -324,16 +321,16 @@ function insertLocal(id, data) { function upsertLocal(id, data) { - var _this5 = this; + var _this4 = this; - if ((0, _rxCollection.isInstanceOf)(this) && this._isInMemory) { + if ((0, _rxCollection.isRxCollection)(this) && this._isInMemory) { return this._parentCollection.upsertLocal(id, data); } return this.getLocal(id).then(function (existing) { if (!existing) { // create new one - var docPromise = _this5.insertLocal(id, data); + var docPromise = _this4.insertLocal(id, data); return docPromise; } else { @@ -349,21 +346,30 @@ function upsertLocal(id, data) { } function getLocal(id) { - var _this6 = this; + var _this5 = this; - if ((0, _rxCollection.isInstanceOf)(this) && this._isInMemory) return this._parentCollection.getLocal(id); + if ((0, _rxCollection.isRxCollection)(this) && this._isInMemory) { + return this.parentCollection.getLocal(id); + } - var pouch = _getPouchByParent(this); + var storageInstance = _getKeyObjectStorageInstanceByParent(this); var docCache = _getDocCache(this); // check in doc-cache var found = docCache.get(id); - if (found) return Promise.resolve(found); // if not found, check in pouch - return pouch.get(_util.LOCAL_PREFIX + id).then(function (docData) { - if (!docData) return null; - var doc = RxLocalDocument.create(id, docData, _this6); + if (found) { + return Promise.resolve(found); + } // if not found, check in storage instance + + + return (0, _rxStorageHelper.findLocalDocument)(storageInstance, id).then(function (docData) { + if (!docData) { + return null; + } + + var doc = RxLocalDocument.create(id, docData, _this5); return doc; })["catch"](function () { return null; @@ -371,7 +377,7 @@ function getLocal(id) { } function getLocal$(id) { - var _this7 = this; + var _this6 = this; return this.$.pipe((0, _operators.startWith)(null), (0, _operators.mergeMap)( /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(cE) { @@ -391,7 +397,7 @@ function getLocal$(id) { case 4: _context.next = 6; - return _this7.getLocal(id); + return _this6.getLocal(id); case 6: doc = _context.sent; @@ -418,7 +424,7 @@ function getLocal$(id) { switch (_context2.prev = _context2.next) { case 0: if (!changeEventOrDoc.changeEvent) { - _context2.next = 17; + _context2.next = 12; break; } @@ -434,40 +440,27 @@ function getLocal$(id) { }); case 6: - if (!cE.rxDocument) { - _context2.next = 10; - break; - } - - _context2.t0 = cE.rxDocument; - _context2.next = 13; - break; - - case 10: - _context2.next = 12; - return _this7.getLocal(id); - - case 12: - _context2.t0 = _context2.sent; + _context2.next = 8; + return _this6.getLocal(id); - case 13: - doc = _context2.t0; + case 8: + doc = _context2.sent; return _context2.abrupt("return", { use: true, doc: doc }); - case 15: - _context2.next = 18; + case 10: + _context2.next = 13; break; - case 17: + case 12: return _context2.abrupt("return", { use: true, doc: changeEventOrDoc.doc }); - case 18: + case 13: case "end": return _context2.stop(); } @@ -485,30 +478,24 @@ function getLocal$(id) { })); } -var rxdb = true; -exports.rxdb = rxdb; -var prototypes = { - RxCollection: function RxCollection(proto) { - proto.insertLocal = insertLocal; - proto.upsertLocal = upsertLocal; - proto.getLocal = getLocal; - proto.getLocal$ = getLocal$; - }, - RxDatabase: function RxDatabase(proto) { - proto.insertLocal = insertLocal; - proto.upsertLocal = upsertLocal; - proto.getLocal = getLocal; - proto.getLocal$ = getLocal$; - } -}; -exports.prototypes = prototypes; -var overwritable = {}; -exports.overwritable = overwritable; var RxDBLocalDocumentsPlugin = { name: 'local-documents', - rxdb: rxdb, - prototypes: prototypes, - overwritable: overwritable + rxdb: true, + prototypes: { + RxCollection: function RxCollection(proto) { + proto.insertLocal = insertLocal; + proto.upsertLocal = upsertLocal; + proto.getLocal = getLocal; + proto.getLocal$ = getLocal$; + }, + RxDatabase: function RxDatabase(proto) { + proto.insertLocal = insertLocal; + proto.upsertLocal = upsertLocal; + proto.getLocal = getLocal; + proto.getLocal$ = getLocal$; + } + }, + overwritable: {} }; exports.RxDBLocalDocumentsPlugin = RxDBLocalDocumentsPlugin; diff --git a/dist/lib/plugins/migration/data-migrator.js b/dist/lib/plugins/migration/data-migrator.js index 76402d9f880..4002d1ccdd2 100644 --- a/dist/lib/plugins/migration/data-migrator.js +++ b/dist/lib/plugins/migration/data-migrator.js @@ -19,30 +19,32 @@ exports.migrateOldCollection = migrateOldCollection; exports.migratePromise = migratePromise; exports.DataMigrator = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + var _rxjs = require("rxjs"); var _deepEqual = _interopRequireDefault(require("deep-equal")); -var _pouchDb = require("../../pouch-db"); - var _util = require("../../util"); var _rxSchema = require("../../rx-schema"); var _rxError = require("../../rx-error"); -var _overwritable = require("../../overwritable"); - var _hooks = require("../../hooks"); var _crypter = require("../../crypter"); -var _rxCollectionHelper = require("../../rx-collection-helper"); - var _migrationState = require("./migration-state"); var _operators = require("rxjs/operators"); +var _rxStorageHelper = require("../../rx-storage-helper"); + +var _rxCollectionHelper = require("../../rx-collection-helper"); + /** * The DataMigrator handles the documents from collections with older schemas * and transforms/saves them into the newest collection @@ -50,7 +52,7 @@ var _operators = require("rxjs/operators"); /** * TODO this should be completely rewritten because: - * - The current implemetation does not use pouchdb'S bulkDocs which is much faster + * - The current implemetation does not use bulkDocs which is much faster * - This could have been done in much less code which would be easier to uderstand * */ @@ -103,6 +105,8 @@ var DataMigrator = /*#__PURE__*/function () { * TODO this is a side-effect which might throw * We did this because it is not possible to create new Observer(async(...)) * @link https://github.com/ReactiveX/rxjs/issues/4074 + * In the future the whole migration plugin should be rewritten without rxjs + * so we do not have this problem. */ (function () { @@ -110,7 +114,7 @@ var DataMigrator = /*#__PURE__*/function () { return _getOldCollections(_this).then(function (ret) { oldCols = ret; var countAll = Promise.all(oldCols.map(function (oldCol) { - return (0, _pouchDb.countAllUndeleted)(oldCol.pouchdb); + return (0, _rxStorageHelper.countAllUndeleted)(oldCol.storageInstance); })); return countAll; }).then(function (countAll) { @@ -191,51 +195,102 @@ var DataMigrator = /*#__PURE__*/function () { exports.DataMigrator = DataMigrator; -function createOldCollection(version, schemaObj, dataMigrator) { - var database = dataMigrator.newestCollection.database; - var schema = (0, _rxSchema.createRxSchema)(schemaObj, false); - var ret = { - version: version, - dataMigrator: dataMigrator, - newestCollection: dataMigrator.newestCollection, - database: database, - schema: (0, _rxSchema.createRxSchema)(schemaObj, false), - pouchdb: database._spawnPouchDB(dataMigrator.newestCollection.name, version, dataMigrator.newestCollection.pouchSettings), - _crypter: (0, _crypter.createCrypter)(database.password, schema) - }; - - if (schema.doKeyCompression()) { - ret._keyCompressor = _overwritable.overwritable.createKeyCompressor(schema); - } - - return ret; +function createOldCollection(_x, _x2, _x3) { + return _createOldCollection.apply(this, arguments); } /** - * get an array with OldCollection-instances from all existing old pouchdb-instance + * get an array with OldCollection-instances from all existing old storage-instances */ -function _getOldCollections(dataMigrator) { - return Promise.all((0, _rxSchema.getPreviousVersions)(dataMigrator.currentSchema.jsonSchema).map(function (v) { - return dataMigrator.database.internalStore.get(dataMigrator.name + '-' + v); - }).map(function (fun) { - return fun["catch"](function () { - return null; - }); - }) // auto-catch so Promise.all continues - ).then(function (oldColDocs) { - return oldColDocs.filter(function (colDoc) { - return colDoc !== null; - }).map(function (colDoc) { - return createOldCollection(colDoc.schema.version, colDoc.schema, dataMigrator); - }); - }); +function _createOldCollection() { + _createOldCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(version, schemaObj, dataMigrator) { + var database, schema, storageInstanceCreationParams, storageInstance, ret; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + database = dataMigrator.newestCollection.database; + schema = (0, _rxSchema.createRxSchema)(schemaObj, false); + storageInstanceCreationParams = { + databaseName: database.name, + collectionName: dataMigrator.newestCollection.name, + schema: schemaObj, + options: dataMigrator.newestCollection.instanceCreationOptions + }; + _context.next = 5; + return database.storage.createStorageInstance(storageInstanceCreationParams); + + case 5: + storageInstance = _context.sent; + ret = { + version: version, + dataMigrator: dataMigrator, + newestCollection: dataMigrator.newestCollection, + database: database, + schema: (0, _rxSchema.createRxSchema)(schemaObj, false), + storageInstance: storageInstance, + _crypter: (0, _crypter.createCrypter)(database.password, schema) + }; + return _context.abrupt("return", ret); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _createOldCollection.apply(this, arguments); +} + +function _getOldCollections(_x4) { + return _getOldCollections2.apply(this, arguments); } /** * returns true if a migration is needed */ +function _getOldCollections2() { + _getOldCollections2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(dataMigrator) { + var oldColDocs; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all((0, _rxSchema.getPreviousVersions)(dataMigrator.currentSchema.jsonSchema).map(function (v) { + return (0, _rxStorageHelper.getSingleDocument)(dataMigrator.database.internalStore, dataMigrator.name + '-' + v); + }).map(function (fun) { + return fun["catch"](function () { + return null; + }); + }) // auto-catch so Promise.all continues + ); + + case 2: + oldColDocs = _context2.sent; + return _context2.abrupt("return", Promise.all(oldColDocs.map(function (colDoc) { + if (!colDoc) { + return null; + } + + return createOldCollection(colDoc.schema.version, colDoc.schema, dataMigrator); + }).filter(function (colDoc) { + return colDoc !== null; + }))); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _getOldCollections2.apply(this, arguments); +} + function mustMigrate(dataMigrator) { if (dataMigrator.currentSchema.version === 0) { return Promise.resolve(false); @@ -261,9 +316,11 @@ function runStrategyIfNotNull(oldCollection, version, docOrNull) { } function getBatchOfOldCollection(oldCollection, batchSize) { - return (0, _pouchDb.getBatch)(oldCollection.pouchdb, batchSize).then(function (docs) { + return (0, _rxStorageHelper.getBatch)(oldCollection.storageInstance, batchSize).then(function (docs) { return docs.map(function (doc) { - return (0, _rxCollectionHelper._handleFromPouch)(oldCollection, doc); + doc = (0, _util.flatClone)(doc); + doc = (0, _rxCollectionHelper._handleFromStorageInstance)(oldCollection, doc); + return doc; }); }); } @@ -301,7 +358,10 @@ function migrateDocumentData(oldCollection, docData) { } return currentPromise.then(function (doc) { - if (doc === null) return Promise.resolve(null); // check final schema + if (doc === null) { + return Promise.resolve(null); + } // check final schema + try { oldCollection.newestCollection.schema.validate(doc); @@ -388,17 +448,16 @@ function _migrateDocument(oldCollection, docData) { * notice that this data also contains the attachments data */ var attachmentsBefore = migrated._attachments; - - var saveData = oldCollection.newestCollection._handleToPouch(migrated); - + var saveData = (0, _rxCollectionHelper._handleToStorageInstance)(oldCollection.newestCollection, migrated); saveData._attachments = attachmentsBefore; - return oldCollection.newestCollection.pouch.bulkDocs([saveData], { - /** - * We need new_edits: false - * because we provide the _rev by our own - */ - new_edits: false - }).then(function () { + /** + * We need to add as revision + * because we provide the _rev by our own + * to have deterministic revisions in case the migration + * runs on multiple nodes which must lead to the equal storage state. + */ + + return oldCollection.newestCollection.storageInstance.bulkAddRevisions([saveData]).then(function () { action.res = saveData; action.type = 'success'; return (0, _hooks.runAsyncPluginHooks)('postMigrateDocument', action); @@ -411,25 +470,30 @@ function _migrateDocument(oldCollection, docData) { */ action.type = 'deleted'; } - }).then(function () { - // remove from old collection - return oldCollection.pouchdb.remove((0, _rxCollectionHelper._handleToPouch)(oldCollection, docData))["catch"](function () {}); + }) // remove the migrated document from the old collection + .then(function () { + var writeDeleted = (0, _util.flatClone)(docData); + writeDeleted._deleted = true; + return oldCollection.storageInstance.bulkWrite([{ + previous: (0, _rxCollectionHelper._handleToStorageInstance)(oldCollection, docData), + document: (0, _rxCollectionHelper._handleToStorageInstance)(oldCollection, writeDeleted) + }]); }).then(function () { return action; }); } /** - * deletes this.pouchdb and removes it from the database.collectionsCollection + * deletes this.storageInstance and removes it from the database.collectionsCollection */ function deleteOldCollection(oldCollection) { - return oldCollection.pouchdb.destroy().then(function () { + return oldCollection.storageInstance.remove().then(function () { return oldCollection.database.removeCollectionDoc(oldCollection.dataMigrator.name, oldCollection.schema); }); } /** - * runs the migration on all documents and deletes the pouchdb afterwards + * runs the migration on all documents and deletes the storage instance afterwards */ diff --git a/dist/lib/plugins/adapter-check.js b/dist/lib/plugins/pouchdb/adapter-check.js similarity index 75% rename from dist/lib/plugins/adapter-check.js rename to dist/lib/plugins/pouchdb/adapter-check.js index 38013cf7ff0..df32dd52c82 100644 --- a/dist/lib/plugins/adapter-check.js +++ b/dist/lib/plugins/pouchdb/adapter-check.js @@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.checkAdapter = checkAdapter; -exports.RxDBAdapterCheckPlugin = exports.overwritable = exports.prototypes = exports.rxdb = exports.POUCHDB_LOCATION = void 0; +exports.POUCHDB_LOCATION = void 0; -var _pouchDb = require("../pouch-db"); +var _pouchDb = require("./pouch-db"); -var _util = require("../util"); +var _util = require("../../util"); /** * this plugin adds the checkAdapter-function to rxdb @@ -25,7 +25,7 @@ exports.POUCHDB_LOCATION = POUCHDB_LOCATION; function checkAdapter(adapter) { // id of the document which is stored and removed to ensure everything works - var _id = POUCHDB_LOCATION + '-' + (0, _util.generateId)(); + var _id = POUCHDB_LOCATION + '-' + (0, _util.randomCouchString)(12); var pouch; @@ -74,20 +74,4 @@ function checkAdapter(adapter) { */ } -var rxdb = true; -exports.rxdb = rxdb; -var prototypes = {}; -exports.prototypes = prototypes; -var overwritable = { - checkAdapter: checkAdapter -}; -exports.overwritable = overwritable; -var RxDBAdapterCheckPlugin = { - name: 'adapter-check', - rxdb: rxdb, - prototypes: prototypes, - overwritable: overwritable -}; -exports.RxDBAdapterCheckPlugin = RxDBAdapterCheckPlugin; - //# sourceMappingURL=adapter-check.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/custom-events-plugin.js b/dist/lib/plugins/pouchdb/custom-events-plugin.js new file mode 100644 index 00000000000..c57fb2dca38 --- /dev/null +++ b/dist/lib/plugins/pouchdb/custom-events-plugin.js @@ -0,0 +1,260 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getCustomEventEmitterByPouch = getCustomEventEmitterByPouch; +exports.addCustomEventsPluginToPouch = addCustomEventsPluginToPouch; +exports.EVENT_EMITTER_BY_POUCH_INSTANCE = void 0; + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); + +var _rxjs = require("rxjs"); + +var _util = require("../../util"); + +var _rxError = require("../../rx-error"); + +var _obliviousSet = require("oblivious-set"); + +/* + * Instead of listening to pouch.changes, + * we overwrite pouchdbs bulkDocs() + * and create our own event stream, this will work more reliable + * and has less strange behaviors. + * Also we can better define what data we need for our events. + * @link http://jsbin.com/pagebi/1/edit?js,output + * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273 + */ +// ensure only added once +var addedToPouch = false; +var EVENT_EMITTER_BY_POUCH_INSTANCE = new Map(); +exports.EVENT_EMITTER_BY_POUCH_INSTANCE = EVENT_EMITTER_BY_POUCH_INSTANCE; + +function getCustomEventEmitterByPouch(pouch) { + var key = [pouch.name, pouch.adapter].join('|'); + var emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key); + + if (!emitter) { + emitter = { + subject: new _rxjs.Subject(), + obliviousSet: new _obliviousSet.ObliviousSet(60 * 1000) + }; + EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter); + } + + return emitter; +} + +var i = 0; + +function addCustomEventsPluginToPouch() { + if (addedToPouch) { + return; + } + + addedToPouch = true; + var oldBulkDocs = _pouchdbCore["default"].prototype.bulkDocs; + + var newBulkDocs = /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(body, options, callback) { + var _this = this; + + var startTime, t, docs, previousDocs, ids, viaChanges, previousDocsResult, deeperOptions; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + startTime = (0, _util.now)(); + t = i++; // normalize input + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (!options) { + options = {}; + } + + if (Array.isArray(body)) { + docs = body; + } else if (body === undefined) { + docs = []; + } else { + docs = body.docs; + + if (body.hasOwnProperty('new_edits')) { + options.new_edits = body.new_edits; + } + } + + if (!(docs.length === 0)) { + _context2.next = 7; + break; + } + + throw (0, _rxError.newRxError)('SNH', { + args: { + body: body, + options: options + } + }); + + case 7: + /** + * If new_edits=false we have to first find the current state + * of the document and can later check if the state was changed + * because a new revision was written and we have to emit an event. + */ + previousDocs = new Map(); + + if (!(options.hasOwnProperty('new_edits') && options.new_edits === false)) { + _context2.next = 18; + break; + } + + ids = docs.map(function (doc) { + return doc._id; + }); + /** + * Pouchdb does not return deleted documents via allDocs() + * So have to do use our hack with getting the newest revisions from the + * changes. + */ + + _context2.next = 12; + return this.changes({ + live: false, + since: 0, + doc_ids: ids, + style: 'all_docs' + }); + + case 12: + viaChanges = _context2.sent; + _context2.next = 15; + return Promise.all(viaChanges.results.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(result) { + var firstDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.get(result.id, { + rev: result.changes[0].rev, + deleted: 'ok', + revs: options.set_new_edit_as_latest_revision ? true : false, + style: 'all_docs' + }); + + case 2: + firstDoc = _context.sent; + return _context.abrupt("return", firstDoc); + + case 4: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }())); + + case 15: + previousDocsResult = _context2.sent; + previousDocsResult.forEach(function (doc) { + return previousDocs.set(doc._id, doc); + }); + + if (options.set_new_edit_as_latest_revision) { + docs.forEach(function (doc) { + var id = doc._id; + var previous = previousDocs.get(id); + + if (previous) { + var splittedRev = doc._rev.split('-'); + + var revHeight = parseInt(splittedRev[0], 10); + var revLabel = splittedRev[1]; + doc._revisions = { + start: revHeight, + ids: previous._revisions.ids + }; + + doc._revisions.ids.unshift(revLabel); + + delete previous._revisions; + } + }); + } + + case 18: + /** + * pouchdb calls this function again with transformed input. + * This would lead to duplicate events. So we marks the deeper calls via the options + * parameter and do not emit events if it is set. + */ + deeperOptions = (0, _util.flatClone)(options); + deeperOptions.isDeeper = true; + return _context2.abrupt("return", oldBulkDocs.call(this, docs, deeperOptions, function (err, result) { + if (err) { + if (callback) { + callback(err); + } else { + throw err; + } + } else { + if (!options.isDeeper) { + var endTime = (0, _util.now)(); + var emitData = { + emitId: t, + writeDocs: docs, + writeOptions: options, + writeResult: result, + previousDocs: previousDocs, + startTime: startTime, + endTime: endTime + }; + var emitter = getCustomEventEmitterByPouch(_this); + emitter.subject.next(emitData); + } + + if (callback) { + callback(null, result); + } else { + return result; + } + } + })); + + case 21: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function newBulkDocs(_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; + }(); + + _pouchdbCore["default"].plugin({ + bulkDocs: newBulkDocs + }); +} + +//# sourceMappingURL=custom-events-plugin.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/index.js b/dist/lib/plugins/pouchdb/index.js new file mode 100644 index 00000000000..f39c6c29fff --- /dev/null +++ b/dist/lib/plugins/pouchdb/index.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _pouchDb = require("./pouch-db"); + +Object.keys(_pouchDb).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _pouchDb[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _pouchDb[key]; + } + }); +}); + +var _rxStoragePouchdb = require("./rx-storage-pouchdb"); + +Object.keys(_rxStoragePouchdb).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rxStoragePouchdb[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rxStoragePouchdb[key]; + } + }); +}); + +var _adapterCheck = require("./adapter-check"); + +Object.keys(_adapterCheck).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _adapterCheck[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _adapterCheck[key]; + } + }); +}); + +var _customEventsPlugin = require("./custom-events-plugin"); + +Object.keys(_customEventsPlugin).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _customEventsPlugin[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _customEventsPlugin[key]; + } + }); +}); + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/pouch-db.js b/dist/lib/plugins/pouchdb/pouch-db.js new file mode 100644 index 00000000000..4d48c7c47c1 --- /dev/null +++ b/dist/lib/plugins/pouchdb/pouch-db.js @@ -0,0 +1,104 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isLevelDown = isLevelDown; +exports.pouchReplicationFunction = pouchReplicationFunction; +exports.isInstanceOf = isInstanceOf; +exports.addPouchPlugin = addPouchPlugin; +exports.PouchDB = void 0; + +var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); + +var _pouchdbFind = _interopRequireDefault(require("pouchdb-find")); + +var _rxError = require("../../rx-error"); + +var _customEventsPlugin = require("./custom-events-plugin"); + +/** + * this handles the pouchdb-instance + * to easy add modules and manipulate things + * Adapters can be found here: + * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules + */ +// pouchdb-find + +/* +// comment in to debug +const pouchdbDebug = require('pouchdb-debug'); +PouchDB.plugin(pouchdbDebug); +PouchDB.debug.enable('*'); +*/ +// TODO we can delete most of these functions in the file because it was migrated to rx-storage-pouchdb +addPouchPlugin(_pouchdbFind["default"]); +(0, _customEventsPlugin.addCustomEventsPluginToPouch)(); +/** + * check if the given module is a leveldown-adapter + * throws if not + */ + +function isLevelDown(adapter) { + if (!adapter || typeof adapter.super_ !== 'function') { + throw (0, _rxError.newRxError)('UT4', { + adapter: adapter + }); + } +} +/** + * get the correct function-name for pouchdb-replication + */ + + +function pouchReplicationFunction(pouch, _ref) { + var _ref$pull = _ref.pull, + pull = _ref$pull === void 0 ? true : _ref$pull, + _ref$push = _ref.push, + push = _ref$push === void 0 ? true : _ref$push; + if (pull && push) return pouch.sync.bind(pouch); + if (!pull && push) return pouch.replicate.to.bind(pouch); + if (pull && !push) return pouch.replicate.from.bind(pouch); + + if (!pull && !push) { + throw (0, _rxError.newRxError)('UT3', { + pull: pull, + push: push + }); + } +} + +function isInstanceOf(obj) { + return obj instanceof _pouchdbCore["default"]; +} +/** + * Add a pouchdb plugin to the pouchdb library. + */ + + +function addPouchPlugin(plugin) { + if (plugin.rxdb) { + throw (0, _rxError.newRxTypeError)('PL2', { + plugin: plugin + }); + } + /** + * Pouchdb has confusing typings and modules. + * So we monkeypatch the plugin to use the default property + * when it was imported or packaged this way. + */ + + + if (typeof plugin === 'object' && plugin["default"]) { + plugin = plugin["default"]; + } + + _pouchdbCore["default"].plugin(plugin); +} + +var PouchDB = _pouchdbCore["default"]; +exports.PouchDB = PouchDB; + +//# sourceMappingURL=pouch-db.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js b/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js new file mode 100644 index 00000000000..e4f59d10360 --- /dev/null +++ b/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js @@ -0,0 +1,1858 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.writeAttachmentsToAttachments = writeAttachmentsToAttachments; +exports.checkPouchAdapter = checkPouchAdapter; +exports.pouchHash = pouchHash; +exports.pouchSwapIdToPrimary = pouchSwapIdToPrimary; +exports.pouchDocumentDataToRxDocumentData = pouchDocumentDataToRxDocumentData; +exports.rxDocumentDataToPouchDocumentData = rxDocumentDataToPouchDocumentData; +exports.pouchSwapPrimaryToId = pouchSwapPrimaryToId; +exports.pouchStripLocalFlagFromPrimary = pouchStripLocalFlagFromPrimary; +exports.getEventKey = getEventKey; +exports.pouchChangeRowToChangeEvent = pouchChangeRowToChangeEvent; +exports.pouchChangeRowToChangeStreamEvent = pouchChangeRowToChangeStreamEvent; +exports.primarySwapPouchDbQuerySelector = primarySwapPouchDbQuerySelector; +exports.createIndexesOnPouch = createIndexesOnPouch; +exports.getPouchLocation = getPouchLocation; +exports.getRxStoragePouch = getRxStoragePouch; +exports.RxStoragePouch = exports.RxStorageInstancePouch = exports.RxStorageKeyObjectInstancePouch = exports.OPEN_POUCHDB_STORAGE_INSTANCES = exports.POUCHDB_DESIGN_PREFIX = exports.POUCHDB_LOCAL_PREFIX = void 0; + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _pouchdbSelectorCore = require("pouchdb-selector-core"); + +var _pouchdbMd = require("pouchdb-md5"); + +var _util = require("../../util"); + +var _pouchDb = require("./pouch-db"); + +var _rxError = require("../../rx-error"); + +var _rxjs = require("rxjs"); + +var _rxSchemaHelper = require("../../rx-schema-helper"); + +var _customEventsPlugin = require("./custom-events-plugin"); + +/** + * prefix of local pouchdb documents + */ +var POUCHDB_LOCAL_PREFIX = '_local/'; +/** + * Pouchdb stores indexes as design documents, + * we have to filter them out and not return the + * design documents to the outside. + */ + +exports.POUCHDB_LOCAL_PREFIX = POUCHDB_LOCAL_PREFIX; +var POUCHDB_DESIGN_PREFIX = '_design/'; +exports.POUCHDB_DESIGN_PREFIX = POUCHDB_DESIGN_PREFIX; + +/** + * Used to check in tests if all instances have been cleaned up. + */ +var OPEN_POUCHDB_STORAGE_INSTANCES = new Set(); +exports.OPEN_POUCHDB_STORAGE_INSTANCES = OPEN_POUCHDB_STORAGE_INSTANCES; + +var RxStorageKeyObjectInstancePouch = /*#__PURE__*/function () { + function RxStorageKeyObjectInstancePouch(databaseName, collectionName, internals, options) { + this.changes$ = new _rxjs.Subject(); + this.databaseName = databaseName; + this.collectionName = collectionName; + this.internals = internals; + this.options = options; + OPEN_POUCHDB_STORAGE_INSTANCES.add(this); + } + + var _proto = RxStorageKeyObjectInstancePouch.prototype; + + _proto.close = function close() { + OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); // TODO this did not work because a closed pouchdb cannot be recreated in the same process run + // await this.internals.pouch.close(); + + return Promise.resolve(); + }; + + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.internals.pouch.destroy(); + + case 2: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function remove() { + return _remove.apply(this, arguments); + } + + return remove; + }(); + + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(documentWrites) { + var _this = this; + + var writeRowById, insertDocs, startTime, pouchResult, endTime, ret; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + writeRowById = new Map(); + insertDocs = documentWrites.map(function (writeRow) { + writeRowById.set(writeRow.document._id, writeRow); + var storeDocumentData = (0, _util.flatClone)(writeRow.document); + /** + * add local prefix + * Local documents always have _id as primary + */ + + storeDocumentData._id = POUCHDB_LOCAL_PREFIX + storeDocumentData._id; // if previous document exists, we have to send the previous revision to pouchdb. + + if (writeRow.previous) { + storeDocumentData._rev = writeRow.previous._rev; + } + + return storeDocumentData; + }); + startTime = (0, _util.now)(); + _context2.next = 5; + return this.internals.pouch.bulkDocs(insertDocs); + + case 5: + pouchResult = _context2.sent; + endTime = (0, _util.now)(); + ret = { + success: new Map(), + error: new Map() + }; + pouchResult.forEach(function (resultRow) { + resultRow.id = pouchStripLocalFlagFromPrimary(resultRow.id); + var writeRow = (0, _util.getFromMapOrThrow)(writeRowById, resultRow.id); + + if (resultRow.error) { + var err = { + isError: true, + status: 409, + documentId: resultRow.id, + writeRow: writeRow + }; + ret.error.set(resultRow.id, err); + } else { + var pushObj = (0, _util.flatClone)(writeRow.document); + pushObj._rev = resultRow.rev; // local document cannot have attachments + + pushObj._attachments = {}; + ret.success.set(resultRow.id, pushObj); + /** + * Emit a write event to the changestream. + * We do this here and not by observing the internal pouchdb changes + * because here we have the previous document data and do + * not have to fill previous with 'UNKNOWN'. + */ + + var event; + + if (!writeRow.previous) { + // was insert + event = { + operation: 'INSERT', + doc: pushObj, + id: resultRow.id, + previous: null + }; + } else if (writeRow.document._deleted) { + // was delete + // we need to add the new revision to the previous doc + // so that the eventkey is calculated correctly. + // Is this a hack? idk. + var previousDoc = (0, _util.flatClone)(writeRow.previous); + previousDoc._rev = resultRow.rev; + event = { + operation: 'DELETE', + doc: null, + id: resultRow.id, + previous: previousDoc + }; + } else { + // was update + event = { + operation: 'UPDATE', + doc: pushObj, + id: resultRow.id, + previous: writeRow.previous + }; + } + + if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) { + /** + * A deleted document was newly added to the storage engine, + * do not emit an event. + */ + } else { + var doc = event.operation === 'DELETE' ? event.previous : event.doc; + var eventId = getEventKey(true, doc._id, doc._rev ? doc._rev : ''); + var storageChangeEvent = { + eventId: eventId, + documentId: resultRow.id, + change: event, + startTime: startTime, + endTime: endTime + }; + + _this.changes$.next(storageChangeEvent); + } + } + }); + return _context2.abrupt("return", ret); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function bulkWrite(_x) { + return _bulkWrite.apply(this, arguments); + } + + return bulkWrite; + }(); + + _proto.findLocalDocumentsById = /*#__PURE__*/function () { + var _findLocalDocumentsById = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ids) { + var _this2 = this; + + var ret; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + ret = new Map(); + /** + * Pouchdb is not able to bulk-request local documents + * with the pouch.allDocs() method. + * so we need to get each by a single call. + * TODO create an issue at the pouchdb repo + */ + + _context4.next = 3; + return Promise.all(ids.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(id) { + var prefixedId, docData; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + prefixedId = POUCHDB_LOCAL_PREFIX + id; + _context3.prev = 1; + _context3.next = 4; + return _this2.internals.pouch.get(prefixedId); + + case 4: + docData = _context3.sent; + docData._id = id; + ret.set(id, docData); + _context3.next = 11; + break; + + case 9: + _context3.prev = 9; + _context3.t0 = _context3["catch"](1); + + case 11: + case "end": + return _context3.stop(); + } + } + }, _callee3, null, [[1, 9]]); + })); + + return function (_x3) { + return _ref.apply(this, arguments); + }; + }())); + + case 3: + return _context4.abrupt("return", ret); + + case 4: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + + function findLocalDocumentsById(_x2) { + return _findLocalDocumentsById.apply(this, arguments); + } + + return findLocalDocumentsById; + }(); + + _proto.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + + return RxStorageKeyObjectInstancePouch; +}(); + +exports.RxStorageKeyObjectInstancePouch = RxStorageKeyObjectInstancePouch; + +var RxStorageInstancePouch = /*#__PURE__*/function () { + function RxStorageInstancePouch(databaseName, collectionName, schema, internals, options) { + var _this3 = this; + + this.changes$ = new _rxjs.Subject(); + this.subs = []; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + OPEN_POUCHDB_STORAGE_INSTANCES.add(this); + /** + * Instead of listening to pouch.changes, + * we have overwritten pouchdbs bulkDocs() + * and create our own event stream, this will work more relyable + * and does not mix up with write events from other sources. + */ + + var emitter = (0, _customEventsPlugin.getCustomEventEmitterByPouch)(this.internals.pouch); + this.emittedEventIds = emitter.obliviousSet; + var eventSub = emitter.subject.subscribe( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(ev) { + var writeDocsById, writeMap; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + if (!(ev.writeOptions.hasOwnProperty('new_edits') && !ev.writeOptions.new_edits)) { + _context8.next = 4; + break; + } + + _context8.next = 3; + return Promise.all(ev.writeDocs.map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(writeDoc) { + var id, previousDoc, event; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + id = writeDoc._id; + writeDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeDoc); + _context5.next = 4; + return writeAttachmentsToAttachments(writeDoc._attachments); + + case 4: + writeDoc._attachments = _context5.sent; + previousDoc = ev.previousDocs.get(id); + + if (previousDoc) { + previousDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, previousDoc); + } + + if (!(previousDoc && (0, _util.getHeightOfRevision)(previousDoc._rev) > (0, _util.getHeightOfRevision)(writeDoc._rev))) { + _context5.next = 9; + break; + } + + return _context5.abrupt("return"); + + case 9: + if (!(!previousDoc && writeDoc._deleted)) { + _context5.next = 11; + break; + } + + return _context5.abrupt("return"); + + case 11: + if (!(previousDoc && previousDoc._deleted && writeDoc._deleted)) { + _context5.next = 13; + break; + } + + return _context5.abrupt("return"); + + case 13: + if (!(!previousDoc && !writeDoc._deleted)) { + _context5.next = 17; + break; + } + + // was insert + event = { + operation: 'INSERT', + doc: writeDoc, + id: id, + previous: null + }; + _context5.next = 27; + break; + + case 17: + if (!(writeDoc._deleted && previousDoc && !previousDoc._deleted)) { + _context5.next = 22; + break; + } + + // was delete + previousDoc._rev = writeDoc._rev; + event = { + operation: 'DELETE', + doc: null, + id: id, + previous: previousDoc + }; + _context5.next = 27; + break; + + case 22: + if (!previousDoc) { + _context5.next = 26; + break; + } + + // was update + event = { + operation: 'UPDATE', + doc: writeDoc, + id: id, + previous: previousDoc + }; + _context5.next = 27; + break; + + case 26: + throw (0, _rxError.newRxError)('SNH', { + args: { + writeDoc: writeDoc + } + }); + + case 27: + _this3.addEventToChangeStream(event, ev.startTime, ev.endTime); + + case 28: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + + return function (_x5) { + return _ref3.apply(this, arguments); + }; + }())); + + case 3: + return _context8.abrupt("return"); + + case 4: + if (ev.writeOptions.custom) { + _context8.next = 10; + break; + } + + writeDocsById = new Map(); + ev.writeDocs.forEach(function (writeDoc) { + return writeDocsById.set(writeDoc._id, writeDoc); + }); + _context8.next = 9; + return Promise.all(ev.writeResult.map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(resultRow) { + var id, writeDoc, event; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + id = resultRow.id; + + if (!(id.startsWith(POUCHDB_DESIGN_PREFIX) || id.startsWith(POUCHDB_LOCAL_PREFIX))) { + _context6.next = 3; + break; + } + + return _context6.abrupt("return"); + + case 3: + writeDoc = (0, _util.getFromMapOrThrow)(writeDocsById, resultRow.id); + _context6.next = 6; + return writeAttachmentsToAttachments(writeDoc._attachments); + + case 6: + writeDoc._attachments = _context6.sent; + event = pouchChangeRowToChangeEvent(_this3.schema.primaryKey, writeDoc); + + _this3.addEventToChangeStream(event); + + case 9: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + + return function (_x6) { + return _ref4.apply(this, arguments); + }; + }())); + + case 9: + return _context8.abrupt("return"); + + case 10: + writeMap = ev.writeOptions.custom.writeRowById; + _context8.next = 13; + return Promise.all(ev.writeResult.map( /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(resultRow) { + var id, writeRow, newDoc, event, previousDoc; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + if (!resultRow.error) { + _context7.next = 2; + break; + } + + return _context7.abrupt("return"); + + case 2: + id = resultRow.id; + writeRow = (0, _util.getFromMapOrThrow)(writeMap, id); + newDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeRow.document); + _context7.next = 7; + return writeAttachmentsToAttachments(newDoc._attachments); + + case 7: + newDoc._attachments = _context7.sent; + newDoc._rev = resultRow.rev; + + if (writeRow.previous) { + _context7.next = 13; + break; + } + + // was insert + event = { + operation: 'INSERT', + doc: newDoc, + id: id, + previous: null + }; + _context7.next = 23; + break; + + case 13: + if (!writeRow.document._deleted) { + _context7.next = 22; + break; + } + + // was delete + // we need to add the new revision to the previous doc + // so that the eventkey is calculated correctly. + // Is this a hack? idk. + previousDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeRow.previous); + _context7.next = 17; + return writeAttachmentsToAttachments(previousDoc._attachments); + + case 17: + previousDoc._attachments = _context7.sent; + previousDoc._rev = resultRow.rev; + event = { + operation: 'DELETE', + doc: null, + id: resultRow.id, + previous: previousDoc + }; + _context7.next = 23; + break; + + case 22: + // was update + event = { + operation: 'UPDATE', + doc: newDoc, + id: resultRow.id, + previous: writeRow.previous + }; + + case 23: + if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) { + /** + * A deleted document was newly added to the storage engine, + * do not emit an event. + */ + } else { + _this3.addEventToChangeStream(event, ev.startTime, ev.endTime); + } + + case 24: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + + return function (_x7) { + return _ref5.apply(this, arguments); + }; + }())); + + case 13: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }()); + this.subs.push(eventSub); + } + + var _proto2 = RxStorageInstancePouch.prototype; + + _proto2.addEventToChangeStream = function addEventToChangeStream(change, startTime, endTime) { + var doc = change.operation === 'DELETE' ? change.previous : change.doc; + var primaryKey = this.schema.primaryKey; + var primary = doc[primaryKey]; + var eventId = getEventKey(false, primary, doc._rev); + + if (this.emittedEventIds.has(eventId)) { + return; + } + + this.emittedEventIds.add(eventId); + var storageChangeEvent = { + eventId: eventId, + documentId: primary, + change: change, + startTime: startTime, + endTime: endTime + }; + this.changes$.next(storageChangeEvent); + }; + + _proto2.close = function close() { + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); // TODO this did not work because a closed pouchdb cannot be recreated in the same process run + // await this.internals.pouch.close(); + + return Promise.resolve(); + }; + + _proto2.remove = /*#__PURE__*/function () { + var _remove2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9() { + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return this.internals.pouch.destroy(); + + case 2: + case "end": + return _context9.stop(); + } + } + }, _callee9, this); + })); + + function remove() { + return _remove2.apply(this, arguments); + } + + return remove; + }(); + + _proto2.getSortComparator = function getSortComparator(query) { + var _ref6; + + var primaryKey = this.schema.primaryKey; + var sortOptions = query.sort ? query.sort : [(_ref6 = {}, _ref6[primaryKey] = 'asc', _ref6)]; + var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); + var inMemoryFields = Object.keys(query.selector); + + var fun = function fun(a, b) { + // TODO use createFieldSorter + // TODO make a performance test + var rows = [a, b].map(function (doc) { + // swap primary to _id + var cloned = (0, _util.flatClone)(doc); + var primaryValue = cloned[primaryKey]; + delete cloned[primaryKey]; + cloned._id = primaryValue; + return { + doc: cloned + }; + }); + var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, { + selector: massagedSelector, + sort: sortOptions + }, inMemoryFields); + + if (sortedRows[0].doc._id === rows[0].doc._id) { + return -1; + } else { + return 1; + } + }; + + return fun; + } + /** + * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js + */ + ; + + _proto2.getQueryMatcher = function getQueryMatcher(query) { + var primaryKey = this.schema.primaryKey; + var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); + + var fun = function fun(doc) { + var cloned = pouchSwapPrimaryToId(primaryKey, doc); + var row = { + doc: cloned + }; + var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { + selector: massagedSelector + }, Object.keys(query.selector)); + var ret = rowsMatched && rowsMatched.length === 1; + return ret; + }; + + return fun; + } + /** + * pouchdb has many bugs and strange behaviors + * this functions takes a normal mango query + * and transforms it to one that fits for pouchdb + */ + ; + + _proto2.prepareQuery = function prepareQuery(mutateableQuery) { + var _this4 = this; + + var primaryKey = this.schema.primaryKey; + var query = mutateableQuery; + /** + * because sort wont work on unused keys we have to workaround + * so we add the key to the selector if necessary + * @link https://github.com/nolanlawson/pouchdb-find/issues/204 + */ + + if (query.sort) { + query.sort.forEach(function (sortPart) { + var key = Object.keys(sortPart)[0]; + var comparisonOperators = ['$gt', '$gte', '$lt', '$lte']; + var keyUsed = query.selector[key] && Object.keys(query.selector[key]).some(function (op) { + return comparisonOperators.includes(op); + }) || false; + + if (!keyUsed) { + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(_this4.schema, key); + + if (!schemaObj) { + throw (0, _rxError.newRxError)('QU5', { + key: key + }); + } + + if (!query.selector[key]) { + query.selector[key] = {}; + } + + switch (schemaObj.type) { + case 'number': + case 'integer': + // TODO change back to -Infinity when issue resolved + // @link https://github.com/pouchdb/pouchdb/issues/6454 + // -Infinity does not work since pouchdb 6.2.0 + query.selector[key].$gt = -9999999999999999999999999999; + break; + + case 'string': + /** + * strings need an empty string, see + * @link https://github.com/pubkey/rxdb/issues/585 + */ + if (typeof query.selector[key] !== 'string') { + query.selector[key].$gt = ''; + } + + break; + + default: + query.selector[key].$gt = null; + break; + } + } + }); + } // regex does not work over the primary key + // TODO move this to dev mode + + + if (query.selector[primaryKey] && query.selector[primaryKey].$regex) { + throw (0, _rxError.newRxError)('QU4', { + path: primaryKey, + query: mutateableQuery + }); + } // primary-swap sorting + + + if (query.sort) { + var sortArray = query.sort.map(function (part) { + var _newPart; + + var key = Object.keys(part)[0]; + var direction = Object.values(part)[0]; + var useKey = key === primaryKey ? '_id' : key; + var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); + return newPart; + }); + query.sort = sortArray; + } // strip empty selectors + + + Object.entries(query.selector).forEach(function (_ref7) { + var k = _ref7[0], + v = _ref7[1]; + + if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { + delete query.selector[k]; + } + }); + query.selector = primarySwapPouchDbQuerySelector(query.selector, primaryKey); + return query; + }; + + _proto2.bulkAddRevisions = /*#__PURE__*/function () { + var _bulkAddRevisions = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(documents) { + var _this5 = this; + + var writeData; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + writeData = documents.map(function (doc) { + return pouchSwapPrimaryToId(_this5.schema.primaryKey, doc); + }); // we do not need the response here because pouchdb returns an empty array on new_edits: false + + _context10.next = 3; + return this.internals.pouch.bulkDocs(writeData, { + new_edits: false, + set_new_edit_as_latest_revision: true + }); + + case 3: + case "end": + return _context10.stop(); + } + } + }, _callee10, this); + })); + + function bulkAddRevisions(_x8) { + return _bulkAddRevisions.apply(this, arguments); + } + + return bulkAddRevisions; + }(); + + _proto2.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(documentWrites) { + var primaryKey, writeRowById, insertDocs, pouchResult, ret; + return _regenerator["default"].wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + primaryKey = this.schema.primaryKey; + writeRowById = new Map(); + insertDocs = documentWrites.map(function (writeData) { + var primary = writeData.document[primaryKey]; + writeRowById.set(primary, writeData); + var storeDocumentData = rxDocumentDataToPouchDocumentData(primaryKey, writeData.document); // if previous document exists, we have to send the previous revision to pouchdb. + + if (writeData.previous) { + storeDocumentData._rev = writeData.previous._rev; + } + + return storeDocumentData; + }); + _context12.next = 5; + return this.internals.pouch.bulkDocs(insertDocs, { + custom: { + writeRowById: writeRowById + } + }); + + case 5: + pouchResult = _context12.sent; + ret = { + success: new Map(), + error: new Map() + }; + _context12.next = 9; + return Promise.all(pouchResult.map( /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(resultRow) { + var writeRow, err, pushObj; + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + writeRow = (0, _util.getFromMapOrThrow)(writeRowById, resultRow.id); + + if (!resultRow.error) { + _context11.next = 6; + break; + } + + err = { + isError: true, + status: 409, + documentId: resultRow.id, + writeRow: writeRow + }; + ret.error.set(resultRow.id, err); + _context11.next = 18; + break; + + case 6: + pushObj = (0, _util.flatClone)(writeRow.document); + pushObj = pouchSwapIdToPrimary(primaryKey, pushObj); + pushObj._rev = resultRow.rev; // replace the inserted attachments with their diggest + + // replace the inserted attachments with their diggest + pushObj._attachments = {}; + + if (writeRow.document._attachments) { + _context11.next = 14; + break; + } + + writeRow.document._attachments = {}; + _context11.next = 17; + break; + + case 14: + _context11.next = 16; + return writeAttachmentsToAttachments(writeRow.document._attachments); + + case 16: + pushObj._attachments = _context11.sent; + + case 17: + ret.success.set(resultRow.id, pushObj); + + case 18: + case "end": + return _context11.stop(); + } + } + }, _callee11); + })); + + return function (_x10) { + return _ref8.apply(this, arguments); + }; + }())); + + case 9: + _context12.next = 11; + return (0, _util.promiseWait)(0).then(function () { + return (0, _util.promiseWait)(0); + }); + + case 11: + return _context12.abrupt("return", ret); + + case 12: + case "end": + return _context12.stop(); + } + } + }, _callee12, this); + })); + + function bulkWrite(_x9) { + return _bulkWrite2.apply(this, arguments); + } + + return bulkWrite; + }(); + + _proto2.query = /*#__PURE__*/function () { + var _query = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(preparedQuery) { + var primaryKey, findResult, ret; + return _regenerator["default"].wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + primaryKey = this.schema.primaryKey; + _context13.next = 3; + return this.internals.pouch.find(preparedQuery); + + case 3: + findResult = _context13.sent; + ret = { + documents: findResult.docs.map(function (pouchDoc) { + var useDoc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); + return useDoc; + }) + }; + return _context13.abrupt("return", ret); + + case 6: + case "end": + return _context13.stop(); + } + } + }, _callee13, this); + })); + + function query(_x11) { + return _query.apply(this, arguments); + } + + return query; + }(); + + _proto2.getAttachmentData = /*#__PURE__*/function () { + var _getAttachmentData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(documentId, attachmentId) { + var attachmentData; + return _regenerator["default"].wrap(function _callee14$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return this.internals.pouch.getAttachment(documentId, attachmentId); + + case 2: + attachmentData = _context14.sent; + return _context14.abrupt("return", attachmentData); + + case 4: + case "end": + return _context14.stop(); + } + } + }, _callee14, this); + })); + + function getAttachmentData(_x12, _x13) { + return _getAttachmentData.apply(this, arguments); + } + + return getAttachmentData; + }(); + + _proto2.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(ids, deleted) { + var _this6 = this; + + var primaryKey, viaChanges, retDocs, pouchResult, ret; + return _regenerator["default"].wrap(function _callee16$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + primaryKey = this.schema.primaryKey; + /** + * On deleted documents, pouchdb will only return the tombstone. + * So we have to get the properties directly for each document + * with the hack of getting the changes and then make one request per document + * with the latest revision. + * TODO create an issue at pouchdb on how to get the document data of deleted documents, + * when one past revision was written via new_edits=false + * @link https://stackoverflow.com/a/63516761/3443137 + */ + + if (!deleted) { + _context16.next = 9; + break; + } + + _context16.next = 4; + return this.internals.pouch.changes({ + live: false, + since: 0, + doc_ids: ids, + style: 'all_docs' + }); + + case 4: + viaChanges = _context16.sent; + retDocs = new Map(); + _context16.next = 8; + return Promise.all(viaChanges.results.map( /*#__PURE__*/function () { + var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(result) { + var firstDoc, useFirstDoc; + return _regenerator["default"].wrap(function _callee15$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + _context15.next = 2; + return _this6.internals.pouch.get(result.id, { + rev: result.changes[0].rev, + deleted: 'ok', + style: 'all_docs' + }); + + case 2: + firstDoc = _context15.sent; + useFirstDoc = pouchDocumentDataToRxDocumentData(primaryKey, firstDoc); + retDocs.set(result.id, useFirstDoc); + + case 5: + case "end": + return _context15.stop(); + } + } + }, _callee15); + })); + + return function (_x16) { + return _ref9.apply(this, arguments); + }; + }())); + + case 8: + return _context16.abrupt("return", retDocs); + + case 9: + _context16.next = 11; + return this.internals.pouch.allDocs({ + include_docs: true, + keys: ids + }); + + case 11: + pouchResult = _context16.sent; + ret = new Map(); + pouchResult.rows.filter(function (row) { + return !!row.doc; + }).forEach(function (row) { + var docData = row.doc; + docData = pouchDocumentDataToRxDocumentData(primaryKey, docData); + ret.set(row.id, docData); + }); + return _context16.abrupt("return", ret); + + case 15: + case "end": + return _context16.stop(); + } + } + }, _callee16, this); + })); + + function findDocumentsById(_x14, _x15) { + return _findDocumentsById.apply(this, arguments); + } + + return findDocumentsById; + }(); + + _proto2.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + + _proto2.getChangedDocuments = /*#__PURE__*/function () { + var _getChangedDocuments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(options) { + var pouchChangesOpts, pouchResults, changedDocuments, lastSequence; + return _regenerator["default"].wrap(function _callee17$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + pouchChangesOpts = { + live: false, + limit: options.limit, + include_docs: false, + since: options.startSequence, + descending: options.order === 'desc' ? true : false + }; + _context17.next = 3; + return this.internals.pouch.changes(pouchChangesOpts); + + case 3: + pouchResults = _context17.sent; + changedDocuments = pouchResults.results.filter(function (row) { + return !row.id.startsWith(POUCHDB_DESIGN_PREFIX); + }).map(function (row) { + return { + id: row.id, + sequence: row.seq + }; + }); + lastSequence = pouchResults.last_seq; + return _context17.abrupt("return", { + changedDocuments: changedDocuments, + lastSequence: lastSequence + }); + + case 7: + case "end": + return _context17.stop(); + } + } + }, _callee17, this); + })); + + function getChangedDocuments(_x17) { + return _getChangedDocuments.apply(this, arguments); + } + + return getChangedDocuments; + }(); + + return RxStorageInstancePouch; +}(); + +exports.RxStorageInstancePouch = RxStorageInstancePouch; + +var RxStoragePouch = /*#__PURE__*/function () { + function RxStoragePouch(adapter) { + var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.name = 'pouchdb'; + this.adapter = adapter; + this.pouchSettings = pouchSettings; + checkPouchAdapter(adapter); + } + /** + * create the same diggest as an attachment with that data + * would have created by pouchdb internally. + */ + + + var _proto3 = RxStoragePouch.prototype; + + _proto3.hash = function hash(data) { + return pouchHash(data); + }; + + _proto3.createPouch = /*#__PURE__*/function () { + var _createPouch = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18(location, options) { + var pouchDbParameters, pouchDBOptions, pouch; + return _regenerator["default"].wrap(function _callee18$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + pouchDbParameters = { + location: location, + adapter: (0, _util.adapterObject)(this.adapter), + settings: options + }; + pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); + pouch = new _pouchDb.PouchDB(pouchDbParameters.location, pouchDBOptions); + /** + * In the past we found some errors where the PouchDB is not directly useable + * so we we had to call .info() first to ensure it can be used. + * I commented this out for now to get faster database/collection creation. + * We might have to add this again if something fails. + */ + // await pouch.info(); + + return _context18.abrupt("return", pouch); + + case 4: + case "end": + return _context18.stop(); + } + } + }, _callee18, this); + })); + + function createPouch(_x18, _x19) { + return _createPouch.apply(this, arguments); + } + + return createPouch; + }(); + + _proto3.createStorageInstance = /*#__PURE__*/function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19(params) { + var pouchLocation, pouch; + return _regenerator["default"].wrap(function _callee19$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + pouchLocation = getPouchLocation(params.databaseName, params.collectionName, params.schema.version); + _context19.next = 3; + return this.createPouch(pouchLocation, params.options); + + case 3: + pouch = _context19.sent; + _context19.next = 6; + return createIndexesOnPouch(pouch, params.schema); + + case 6: + return _context19.abrupt("return", new RxStorageInstancePouch(params.databaseName, params.collectionName, params.schema, { + pouch: pouch + }, params.options)); + + case 7: + case "end": + return _context19.stop(); + } + } + }, _callee19, this); + })); + + function createStorageInstance(_x20) { + return _createStorageInstance.apply(this, arguments); + } + + return createStorageInstance; + }(); + + _proto3.createKeyObjectStorageInstance = /*#__PURE__*/function () { + var _createKeyObjectStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20(databaseName, collectionName, options) { + var useOptions, pouchLocation, pouch; + return _regenerator["default"].wrap(function _callee20$(_context20) { + while (1) { + switch (_context20.prev = _context20.next) { + case 0: + useOptions = (0, _util.flatClone)(options); // no compaction because this only stores local documents + + useOptions.auto_compaction = false; + useOptions.revs_limit = 1; + pouchLocation = getPouchLocation(databaseName, collectionName, 0); + _context20.next = 6; + return this.createPouch(pouchLocation, options); + + case 6: + pouch = _context20.sent; + return _context20.abrupt("return", new RxStorageKeyObjectInstancePouch(databaseName, collectionName, { + pouch: pouch + }, options)); + + case 8: + case "end": + return _context20.stop(); + } + } + }, _callee20, this); + })); + + function createKeyObjectStorageInstance(_x21, _x22, _x23) { + return _createKeyObjectStorageInstance.apply(this, arguments); + } + + return createKeyObjectStorageInstance; + }(); + + return RxStoragePouch; +}(); + +exports.RxStoragePouch = RxStoragePouch; + +function writeAttachmentsToAttachments(_x24) { + return _writeAttachmentsToAttachments.apply(this, arguments); +} +/** + * Checks if all is ok with the given adapter, + * else throws an error. + */ + + +function _writeAttachmentsToAttachments() { + _writeAttachmentsToAttachments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22(attachments) { + var ret; + return _regenerator["default"].wrap(function _callee22$(_context22) { + while (1) { + switch (_context22.prev = _context22.next) { + case 0: + if (attachments) { + _context22.next = 2; + break; + } + + return _context22.abrupt("return", {}); + + case 2: + ret = {}; + _context22.next = 5; + return Promise.all(Object.entries(attachments).map( /*#__PURE__*/function () { + var _ref14 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21(_ref13) { + var key, obj, asWrite, hash, asString, length; + return _regenerator["default"].wrap(function _callee21$(_context21) { + while (1) { + switch (_context21.prev = _context21.next) { + case 0: + key = _ref13[0], obj = _ref13[1]; + + if (obj.type) { + _context21.next = 3; + break; + } + + throw (0, _rxError.newRxError)('SNH', { + args: obj + }); + + case 3: + if (!obj.data) { + _context21.next = 15; + break; + } + + asWrite = obj; + _context21.next = 7; + return pouchHash(asWrite.data); + + case 7: + hash = _context21.sent; + _context21.next = 10; + return _util.blobBufferUtil.toString(asWrite.data); + + case 10: + asString = _context21.sent; + length = asString.length; + ret[key] = { + digest: hash, + length: length, + type: asWrite.type + }; + _context21.next = 16; + break; + + case 15: + ret[key] = obj; + + case 16: + case "end": + return _context21.stop(); + } + } + }, _callee21); + })); + + return function (_x27) { + return _ref14.apply(this, arguments); + }; + }())); + + case 5: + return _context22.abrupt("return", ret); + + case 6: + case "end": + return _context22.stop(); + } + } + }, _callee22); + })); + return _writeAttachmentsToAttachments.apply(this, arguments); +} + +function checkPouchAdapter(adapter) { + if (typeof adapter === 'string') { + // TODO make a function hasAdapter() + if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters[adapter]) { + throw (0, _rxError.newRxError)('DB9', { + adapter: adapter + }); + } + } else { + (0, _pouchDb.isLevelDown)(adapter); + + if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.leveldb) { + throw (0, _rxError.newRxError)('DB10', { + adapter: adapter + }); + } + } +} + +function pouchHash(data) { + return new Promise(function (res) { + (0, _pouchdbMd.binaryMd5)(data, function (digest) { + res('md5-' + digest); + }); + }); +} + +function pouchSwapIdToPrimary(primaryKey, docData) { + if (primaryKey === '_id' || docData[primaryKey]) { + return docData; + } + + docData = (0, _util.flatClone)(docData); + docData[primaryKey] = docData._id; + delete docData._id; + return docData; +} + +function pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc) { + var useDoc = pouchSwapIdToPrimary(primaryKey, pouchDoc); // always flat clone becaues we mutate the _attachments property. + + useDoc = (0, _util.flatClone)(useDoc); + delete useDoc._revisions; + useDoc._attachments = {}; + + if (pouchDoc._attachments) { + Object.entries(pouchDoc._attachments).forEach(function (_ref10) { + var key = _ref10[0], + value = _ref10[1]; + + if (value.data) { + useDoc._attachments[key] = { + data: value.data, + type: value.type + }; + } else { + useDoc._attachments[key] = { + digest: value.digest, + // TODO why do we need to access value.type? + type: value.type ? value.type : value.content_type, + length: value.length + }; + } + }); + } + + return useDoc; +} + +function rxDocumentDataToPouchDocumentData(primaryKey, doc) { + var pouchDoc = pouchSwapPrimaryToId(primaryKey, doc); // always flat clone becaues we mutate the _attachments property. + + pouchDoc = (0, _util.flatClone)(pouchDoc); + pouchDoc._attachments = {}; + + if (doc._attachments) { + Object.entries(doc._attachments).forEach(function (_ref11) { + var key = _ref11[0], + value = _ref11[1]; + var useValue = value; + + if (useValue.data) { + pouchDoc._attachments[key] = { + data: useValue.data, + content_type: useValue.type + }; + } else { + pouchDoc._attachments[key] = { + digest: useValue.digest, + content_type: useValue.type, + length: useValue.length, + stub: true + }; + } + }); + } + + return pouchDoc; +} + +function pouchSwapPrimaryToId(primaryKey, docData) { + if (primaryKey === '_id') { + return docData; + } + + var ret = {}; + Object.entries(docData).forEach(function (entry) { + var newKey = entry[0] === primaryKey ? '_id' : entry[0]; + ret[newKey] = entry[1]; + }); + return ret; +} +/** + * in: '_local/foobar' + * out: 'foobar' + */ + + +function pouchStripLocalFlagFromPrimary(str) { + return str.substring(POUCHDB_LOCAL_PREFIX.length); +} + +function getEventKey(isLocal, primary, revision) { + if (!primary) { + throw new Error('primary missing !!'); + } + + var prefix = isLocal ? 'local' : 'non-local'; + var eventKey = prefix + '|' + primary + '|' + revision; + return eventKey; +} + +function pouchChangeRowToChangeEvent(primaryKey, pouchDoc) { + if (!pouchDoc) { + throw (0, _rxError.newRxError)('SNH', { + args: { + pouchDoc: pouchDoc + } + }); + } + + var id = pouchDoc._id; + var doc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); + var revHeight = (0, _util.getHeightOfRevision)(doc._rev); + + if (pouchDoc._deleted) { + return { + operation: 'DELETE', + id: id, + doc: null, + previous: doc + }; + } else if (revHeight === 1) { + return { + operation: 'INSERT', + id: id, + doc: doc, + previous: null + }; + } else { + return { + operation: 'UPDATE', + id: id, + doc: doc, + previous: 'UNKNOWN' + }; + } +} + +function pouchChangeRowToChangeStreamEvent(primaryKey, pouchRow) { + var doc = pouchRow.doc; + + if (!doc) { + throw (0, _rxError.newRxError)('SNH', { + args: { + pouchRow: pouchRow + } + }); + } + + var revHeight = (0, _util.getHeightOfRevision)(doc._rev); + + if (pouchRow.deleted) { + var previousDoc = (0, _util.flatClone)(pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc)); + delete previousDoc._deleted; + var ev = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'DELETE', + doc: null, + previous: previousDoc + }; + return ev; + } else if (revHeight === 1) { + var _ev = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'INSERT', + doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), + previous: null + }; + return _ev; + } else { + var _ev2 = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'UPDATE', + doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), + previous: 'UNKNOWN' + }; + return _ev2; + } +} +/** + * Runs a primary swap with transform all custom primaryKey occurences + * into '_id' + * @recursive + */ + + +function primarySwapPouchDbQuerySelector(selector, primaryKey) { + if (primaryKey === '_id') { + return selector; + } + + if (Array.isArray(selector)) { + return selector.map(function (item) { + return primarySwapPouchDbQuerySelector(item, primaryKey); + }); + } else if (typeof selector === 'object') { + var ret = {}; + Object.entries(selector).forEach(function (_ref12) { + var k = _ref12[0], + v = _ref12[1]; + + if (k === primaryKey) { + ret._id = v; + } else { + if (k.startsWith('$')) { + ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); + } else { + ret[k] = v; + } + } + }); + return ret; + } else { + return selector; + } +} +/** + * Creates the indexes of the schema inside of the pouchdb instance. + * Will skip indexes that already exist. + */ + + +function createIndexesOnPouch(_x25, _x26) { + return _createIndexesOnPouch.apply(this, arguments); +} +/** + * returns the pouchdb-database-name + */ + + +function _createIndexesOnPouch() { + _createIndexesOnPouch = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee24(pouch, schema) { + var primaryKey, before, existingIndexes; + return _regenerator["default"].wrap(function _callee24$(_context24) { + while (1) { + switch (_context24.prev = _context24.next) { + case 0: + if (schema.indexes) { + _context24.next = 2; + break; + } + + return _context24.abrupt("return"); + + case 2: + primaryKey = schema.primaryKey; + _context24.next = 5; + return pouch.getIndexes(); + + case 5: + before = _context24.sent; + existingIndexes = new Set(before.indexes.map(function (idx) { + return idx.name; + })); + _context24.next = 9; + return Promise.all(schema.indexes.map( /*#__PURE__*/function () { + var _ref15 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23(indexMaybeArray) { + var indexArray, indexName; + return _regenerator["default"].wrap(function _callee23$(_context23) { + while (1) { + switch (_context23.prev = _context23.next) { + case 0: + indexArray = Array.isArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; + /** + * replace primary key with _id + * because that is the enforced primary key on pouchdb. + */ + + /** + * replace primary key with _id + * because that is the enforced primary key on pouchdb. + */ + indexArray = indexArray.map(function (key) { + if (key === primaryKey) { + return '_id'; + } else { + return key; + } + }); + indexName = 'idx-rxdb-index-' + indexArray.join(','); + + if (!existingIndexes.has(indexName)) { + _context23.next = 5; + break; + } + + return _context23.abrupt("return"); + + case 5: + return _context23.abrupt("return", pouch.createIndex({ + name: indexName, + ddoc: indexName, + index: { + fields: indexArray + } + })); + + case 6: + case "end": + return _context23.stop(); + } + } + }, _callee23); + })); + + return function (_x28) { + return _ref15.apply(this, arguments); + }; + }())); + + case 9: + case "end": + return _context24.stop(); + } + } + }, _callee24); + })); + return _createIndexesOnPouch.apply(this, arguments); +} + +function getPouchLocation(dbName, collectionName, schemaVersion) { + var prefix = dbName + '-rxdb-' + schemaVersion + '-'; + + if (!collectionName.includes('/')) { + return prefix + collectionName; + } else { + // if collectionName is a path, we have to prefix the last part only + var split = collectionName.split('/'); + var last = split.pop(); + var ret = split.join('/'); + ret += '/' + prefix + last; + return ret; + } +} + +function getRxStoragePouch(adapter, pouchSettings) { + if (!adapter) { + throw new Error('adapter missing'); + } + + var storage = new RxStoragePouch(adapter, pouchSettings); + return storage; +} + +//# sourceMappingURL=rx-storage-pouchdb.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication.js b/dist/lib/plugins/replication-couchdb.js similarity index 70% rename from dist/lib/plugins/replication.js rename to dist/lib/plugins/replication-couchdb.js index 80eb6ef2f2e..6d0e6317fb3 100644 --- a/dist/lib/plugins/replication.js +++ b/dist/lib/plugins/replication-couchdb.js @@ -6,9 +6,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.setPouchEventEmitter = setPouchEventEmitter; -exports.createRxReplicationState = createRxReplicationState; -exports.sync = sync; -exports.RxDBReplicationPlugin = exports.hooks = exports.prototypes = exports.rxdb = exports.RxReplicationStateBase = void 0; +exports.createRxCouchDBReplicationState = createRxCouchDBReplicationState; +exports.syncCouchDB = syncCouchDB; +exports.RxDBReplicationCouchDBPlugin = exports.hooks = exports.prototypes = exports.rxdb = exports.RxCouchDBReplicationStateBase = void 0; + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _pouchdbReplication = _interopRequireDefault(require("pouchdb-replication")); @@ -18,24 +22,20 @@ var _operators = require("rxjs/operators"); var _util = require("../util"); -var _core = require("../core"); - var _rxError = require("../rx-error"); -var _pouchDb = require("../pouch-db"); +var _pouchdb = require("../plugins/pouchdb"); var _rxCollection = require("../rx-collection"); -var _watchForChanges = require("./watch-for-changes"); +var _rxCollectionHelper = require("../rx-collection-helper"); /** * this plugin adds the RxCollection.sync()-function to rxdb * you can use it to sync collections with remote or local couchdb-instances */ // add pouchdb-replication-plugin -(0, _core.addRxPlugin)(_pouchdbReplication["default"]); // add the watch-for-changes-plugin - -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); +(0, _pouchdb.addPouchPlugin)(_pouchdbReplication["default"]); /** * Contains all pouchdb instances that * are used inside of RxDB by collections or databases. @@ -44,8 +44,8 @@ var _watchForChanges = require("./watch-for-changes"); var INTERNAL_POUCHDBS = new WeakSet(); -var RxReplicationStateBase = /*#__PURE__*/function () { - function RxReplicationStateBase(collection, syncOptions) { +var RxCouchDBReplicationStateBase = /*#__PURE__*/function () { + function RxCouchDBReplicationStateBase(collection, syncOptions) { var _this = this; this._subs = []; @@ -71,7 +71,7 @@ var RxReplicationStateBase = /*#__PURE__*/function () { }); } - var _proto = RxReplicationStateBase.prototype; + var _proto = RxCouchDBReplicationStateBase.prototype; _proto.awaitInitialReplication = function awaitInitialReplication() { if (this.syncOptions.options && this.syncOptions.options.live) { @@ -118,10 +118,10 @@ var RxReplicationStateBase = /*#__PURE__*/function () { return Promise.resolve(true); }; - return RxReplicationStateBase; + return RxCouchDBReplicationStateBase; }(); -exports.RxReplicationStateBase = RxReplicationStateBase; +exports.RxCouchDBReplicationStateBase = RxCouchDBReplicationStateBase; function setPouchEventEmitter(rxRepState, evEmitter) { if (rxRepState._pouchEventEmitterObject) { @@ -146,7 +146,7 @@ function setPouchEventEmitter(rxRepState, evEmitter) { return doc.language !== 'query'; }) // remove internal docs .map(function (doc) { - return rxRepState.collection._handleFromPouch(doc); + return (0, _rxCollectionHelper._handleFromStorageInstance)(rxRepState.collection, doc); }) // do primary-swap and keycompression .forEach(function (doc) { return rxRepState._subjects.docs.next(doc); @@ -168,17 +168,30 @@ function setPouchEventEmitter(rxRepState, evEmitter) { })); // complete - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'complete').subscribe(function (info) { - /** - * when complete fires, it might be that not all changeEvents - * have passed throught, because of the delay of .wachtForChanges() - * Therefore we have to first ensure that all previous changeEvents have been handled - */ - var unhandledEvents = Array.from(rxRepState.collection._watchForChangesUnhandled); - Promise.all(unhandledEvents).then(function () { - return rxRepState._subjects.complete.next(info); - }); - })); // auto-cancel one-time replications on complelete to not cause memory leak + rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'complete').subscribe( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(info) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _util.promiseWait)(100); + + case 2: + rxRepState._subjects.complete.next(info); + + case 3: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); // auto-cancel one-time replications on complelete to not cause memory leak if (!rxRepState.syncOptions.options || !rxRepState.syncOptions.options.live) { @@ -222,30 +235,30 @@ function setPouchEventEmitter(rxRepState, evEmitter) { })); } -function createRxReplicationState(collection, syncOptions) { - return new RxReplicationStateBase(collection, syncOptions); +function createRxCouchDBReplicationState(collection, syncOptions) { + return new RxCouchDBReplicationStateBase(collection, syncOptions); } -function sync(_ref) { +function syncCouchDB(_ref2) { var _this2 = this; - var remote = _ref.remote, - _ref$waitForLeadershi = _ref.waitForLeadership, - waitForLeadership = _ref$waitForLeadershi === void 0 ? true : _ref$waitForLeadershi, - _ref$direction = _ref.direction, - direction = _ref$direction === void 0 ? { + var remote = _ref2.remote, + _ref2$waitForLeadersh = _ref2.waitForLeadership, + waitForLeadership = _ref2$waitForLeadersh === void 0 ? true : _ref2$waitForLeadersh, + _ref2$direction = _ref2.direction, + direction = _ref2$direction === void 0 ? { pull: true, push: true - } : _ref$direction, - _ref$options = _ref.options, - options = _ref$options === void 0 ? { + } : _ref2$direction, + _ref2$options = _ref2.options, + options = _ref2$options === void 0 ? { live: true, retry: true - } : _ref$options, - query = _ref.query; + } : _ref2$options, + query = _ref2.query; var useOptions = (0, _util.flatClone)(options); // prevent #641 by not allowing internal pouchdbs as remote - if ((0, _pouchDb.isInstanceOf)(remote) && INTERNAL_POUCHDBS.has(remote)) { + if ((0, _pouchdb.isInstanceOf)(remote) && INTERNAL_POUCHDBS.has(remote)) { throw (0, _rxError.newRxError)('RC3', { database: this.database.name, collection: this.name @@ -253,9 +266,8 @@ function sync(_ref) { } // if remote is RxCollection, get internal pouchdb - if ((0, _rxCollection.isInstanceOf)(remote)) { - remote.watchForChanges(); - remote = remote.pouch; + if ((0, _rxCollection.isRxCollection)(remote)) { + remote = remote.storageInstance.internals.pouch; } if (query && this !== query.collection) { @@ -264,13 +276,13 @@ function sync(_ref) { }); } - var syncFun = (0, _pouchDb.pouchReplicationFunction)(this.pouch, direction); + var syncFun = (0, _pouchdb.pouchReplicationFunction)(this.storageInstance.internals.pouch, direction); if (query) { - useOptions.selector = query.keyCompress().selector; + useOptions.selector = query.toJSON().selector; } - var repState = createRxReplicationState(this, { + var repState = createRxCouchDBReplicationState(this, { remote: remote, waitForLeadership: waitForLeadership, direction: direction, @@ -285,8 +297,6 @@ function sync(_ref) { return; } - _this2.watchForChanges(); - var pouchSync = syncFun(remote, useOptions); setPouchEventEmitter(repState, pouchSync); @@ -299,22 +309,26 @@ var rxdb = true; exports.rxdb = rxdb; var prototypes = { RxCollection: function RxCollection(proto) { - proto.sync = sync; + proto.syncCouchDB = syncCouchDB; } }; exports.prototypes = prototypes; var hooks = { createRxCollection: function createRxCollection(collection) { - INTERNAL_POUCHDBS.add(collection.pouch); + var pouch = collection.storageInstance.internals.pouch; + + if (pouch) { + INTERNAL_POUCHDBS.add(collection.storageInstance.internals.pouch); + } } }; exports.hooks = hooks; -var RxDBReplicationPlugin = { - name: 'replication', +var RxDBReplicationCouchDBPlugin = { + name: 'replication-couchdb', rxdb: rxdb, prototypes: prototypes, hooks: hooks }; -exports.RxDBReplicationPlugin = RxDBReplicationPlugin; +exports.RxDBReplicationCouchDBPlugin = RxDBReplicationCouchDBPlugin; -//# sourceMappingURL=replication.js.map \ No newline at end of file +//# sourceMappingURL=replication-couchdb.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/crawling-checkpoint.js b/dist/lib/plugins/replication-graphql/crawling-checkpoint.js index be77d79d8db..61eeb50b8aa 100644 --- a/dist/lib/plugins/replication-graphql/crawling-checkpoint.js +++ b/dist/lib/plugins/replication-graphql/crawling-checkpoint.js @@ -15,15 +15,19 @@ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")) var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _helper = require("./helper"); + +var _rxStorageHelper = require("../../rx-storage-helper"); + var _util = require("../../util"); -var _helper = require("./helper"); +var _rxError = require("../../rx-error"); /** * when the replication starts, * we need a way to find out where it ended the last time. * - * For push-replication, we use the pouchdb-sequence: + * For push-replication, we use the storageInstance-sequence: * We get the documents newer then the last sequence-id * and push them to the server. * @@ -35,7 +39,7 @@ var _helper = require("./helper"); // things for the push-checkpoint // var pushSequenceId = function pushSequenceId(endpointHash) { - return _util.LOCAL_PREFIX + _helper.PLUGIN_IDENT + '-push-checkpoint-' + endpointHash; + return _helper.GRAPHQL_REPLICATION_PLUGIN_IDENT + '-push-checkpoint-' + endpointHash; }; /** * @return last sequence checkpoint @@ -54,7 +58,7 @@ function _getLastPushSequence() { switch (_context.prev = _context.next) { case 0: _context.next = 2; - return (0, _helper.getDocFromPouchOrNull)(collection, pushSequenceId(endpointHash)); + return (0, _rxStorageHelper.findLocalDocument)(collection.localDocumentsStore, pushSequenceId(endpointHash)); case 2: doc = _context.sent; @@ -84,8 +88,8 @@ function setLastPushSequence(_x3, _x4, _x5) { } function _setLastPushSequence() { - _setLastPushSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collection, endpointHash, seq) { - var _id, doc, res; + _setLastPushSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collection, endpointHash, sequence) { + var _id, doc, res, newDoc, _res; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { @@ -93,28 +97,47 @@ function _setLastPushSequence() { case 0: _id = pushSequenceId(endpointHash); _context2.next = 3; - return (0, _helper.getDocFromPouchOrNull)(collection, _id); + return (0, _rxStorageHelper.findLocalDocument)(collection.localDocumentsStore, _id); case 3: doc = _context2.sent; - if (!doc) { - doc = { - _id: _id, - value: seq - }; - } else { - doc.value = seq; + if (doc) { + _context2.next = 11; + break; } _context2.next = 7; - return collection.pouch.put(doc); + return (0, _rxStorageHelper.writeSingleLocal)(collection.localDocumentsStore, { + document: { + _id: _id, + value: sequence, + _attachments: {} + } + }); case 7: res = _context2.sent; return _context2.abrupt("return", res); - case 9: + case 11: + newDoc = (0, _util.flatClone)(doc); + newDoc.value = sequence; + _context2.next = 15; + return (0, _rxStorageHelper.writeSingleLocal)(collection.localDocumentsStore, { + previous: doc, + document: { + _id: _id, + value: sequence, + _attachments: {} + } + }); + + case 15: + _res = _context2.sent; + return _context2.abrupt("return", _res); + + case 17: case "end": return _context2.stop(); } @@ -124,7 +147,7 @@ function _setLastPushSequence() { return _setLastPushSequence.apply(this, arguments); } -function getChangesSinceLastPushSequence(_x6, _x7, _x8) { +function getChangesSinceLastPushSequence(_x6, _x7) { return _getChangesSinceLastPushSequence.apply(this, arguments); } // // things for pull-checkpoint @@ -132,113 +155,149 @@ function getChangesSinceLastPushSequence(_x6, _x7, _x8) { function _getChangesSinceLastPushSequence() { - _getChangesSinceLastPushSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collection, endpointHash, lastPulledRevField) { + _getChangesSinceLastPushSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collection, endpointHash) { var batchSize, - syncRevisions, lastPushSequence, retry, - changes, - filteredResults, - useResults, - docsSearch, - bulkGetDocs, - _args3 = arguments; - return _regenerator["default"].wrap(function _callee3$(_context3) { + lastSequence, + changedDocs, + _loop, + _ret, + _args4 = arguments; + + return _regenerator["default"].wrap(function _callee3$(_context4) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context4.prev = _context4.next) { case 0: - batchSize = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : 10; - syncRevisions = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : false; - _context3.next = 4; + batchSize = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : 10; + _context4.next = 3; return getLastPushSequence(collection, endpointHash); - case 4: - lastPushSequence = _context3.sent; + case 3: + lastPushSequence = _context4.sent; retry = true; + lastSequence = lastPushSequence; + changedDocs = new Map(); + /** + * it can happen that all docs in the batch + * do not have to be replicated. + * Then we have to continue grapping the feed + * until we reach the end of it + */ + + _loop = /*#__PURE__*/_regenerator["default"].mark(function _loop() { + var changesResults, docs; + return _regenerator["default"].wrap(function _loop$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return collection.storageInstance.getChangedDocuments({ + startSequence: lastPushSequence, + limit: batchSize, + order: 'asc' + }); + + case 2: + changesResults = _context3.sent; + lastSequence = changesResults.lastSequence; // optimisation shortcut, do not proceed if there are no changed documents + + if (!(changesResults.changedDocuments.length === 0)) { + _context3.next = 7; + break; + } + + retry = false; + return _context3.abrupt("return", "continue"); + + case 7: + _context3.next = 9; + return collection.storageInstance.findDocumentsById(changesResults.changedDocuments.map(function (row) { + return row.id; + }), true); + + case 9: + docs = _context3.sent; + changesResults.changedDocuments.forEach(function (row) { + var id = row.id; + + if (changedDocs.has(id)) { + return; + } + + var changedDoc = docs.get(id); + + if (!changedDoc) { + throw (0, _rxError.newRxError)('SNH', { + args: { + docs: docs + } + }); + } + /** + * filter out changes with revisions resulting from the pull-stream + * so that they will not be upstreamed again + */ + + + if ((0, _helper.wasRevisionfromPullReplication)(endpointHash, changedDoc._rev)) { + return false; + } + + changedDocs.set(id, { + id: id, + doc: changedDoc, + sequence: row.sequence + }); + }); + + if (changedDocs.size < batchSize && changesResults.changedDocuments.length === batchSize) { + // no pushable docs found but also not reached the end -> re-run + lastPushSequence = lastSequence; + retry = true; + } else { + retry = false; + } + + case 12: + case "end": + return _context3.stop(); + } + } + }, _loop); + }); - case 6: + case 8: if (!retry) { - _context3.next = 21; + _context4.next = 15; break; } - _context3.next = 9; - return collection.pouch.changes({ - since: lastPushSequence, - limit: batchSize, - include_docs: true // style: 'all_docs' + return _context4.delegateYield(_loop(), "t0", 10); - }); + case 10: + _ret = _context4.t0; - case 9: - changes = _context3.sent; - filteredResults = changes.results.filter(function (change) { - /** - * filter out changes with revisions resulting from the pull-stream - * so that they will not be upstreamed again - */ - if ((0, _helper.wasRevisionfromPullReplication)(endpointHash, change.doc._rev)) return false; - if (change.doc[lastPulledRevField] === change.doc._rev) return false; - /** - * filter out internal docs - * that are used for views or indexes in pouchdb - */ - - if (change.id.startsWith('_design/')) return false; - return true; - }); - useResults = filteredResults; - - if (!(filteredResults.length > 0 && syncRevisions)) { - _context3.next = 18; + if (!(_ret === "continue")) { + _context4.next = 13; break; } - docsSearch = filteredResults.map(function (result) { - return { - id: result.id, - rev: result.doc._rev - }; - }); - _context3.next = 16; - return collection.pouch.bulkGet({ - docs: docsSearch, - revs: true, - latest: true - }); - - case 16: - bulkGetDocs = _context3.sent; - useResults = bulkGetDocs.results.map(function (result) { - return { - id: result.id, - doc: result.docs[0]['ok'], - deleted: result.docs[0]['ok']._deleted - }; - }); - - case 18: - if (useResults.length === 0 && changes.results.length === batchSize) { - // no pushable docs found but also not reached the end -> re-run - lastPushSequence = changes.last_seq; - retry = true; - } else { - changes.results = useResults; - retry = false; - } + return _context4.abrupt("continue", 8); - _context3.next = 6; + case 13: + _context4.next = 8; break; - case 21: - changes.results.forEach(function (change) { - change.doc = collection._handleFromPouch(change.doc); + case 15: + return _context4.abrupt("return", { + changedDocs: changedDocs, + lastSequence: lastSequence }); - return _context3.abrupt("return", changes); - case 23: + case 16: case "end": - return _context3.stop(); + return _context4.stop(); } } }, _callee3); @@ -247,39 +306,39 @@ function _getChangesSinceLastPushSequence() { } var pullLastDocumentId = function pullLastDocumentId(endpointHash) { - return _util.LOCAL_PREFIX + _helper.PLUGIN_IDENT + '-pull-checkpoint-' + endpointHash; + return _helper.GRAPHQL_REPLICATION_PLUGIN_IDENT + '-pull-checkpoint-' + endpointHash; }; -function getLastPullDocument(_x9, _x10) { +function getLastPullDocument(_x8, _x9) { return _getLastPullDocument.apply(this, arguments); } function _getLastPullDocument() { _getLastPullDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(collection, endpointHash) { var localDoc; - return _regenerator["default"].wrap(function _callee4$(_context4) { + return _regenerator["default"].wrap(function _callee4$(_context5) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context5.prev = _context5.next) { case 0: - _context4.next = 2; - return (0, _helper.getDocFromPouchOrNull)(collection, pullLastDocumentId(endpointHash)); + _context5.next = 2; + return (0, _rxStorageHelper.findLocalDocument)(collection.localDocumentsStore, pullLastDocumentId(endpointHash)); case 2: - localDoc = _context4.sent; + localDoc = _context5.sent; if (localDoc) { - _context4.next = 7; + _context5.next = 7; break; } - return _context4.abrupt("return", null); + return _context5.abrupt("return", null); case 7: - return _context4.abrupt("return", localDoc.doc); + return _context5.abrupt("return", localDoc.doc); case 8: case "end": - return _context4.stop(); + return _context5.stop(); } } }, _callee4); @@ -287,39 +346,49 @@ function _getLastPullDocument() { return _getLastPullDocument.apply(this, arguments); } -function setLastPullDocument(_x11, _x12, _x13) { +function setLastPullDocument(_x10, _x11, _x12) { return _setLastPullDocument.apply(this, arguments); } function _setLastPullDocument() { _setLastPullDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(collection, endpointHash, doc) { - var _id, localDoc; + var _id, localDoc, newDoc; - return _regenerator["default"].wrap(function _callee5$(_context5) { + return _regenerator["default"].wrap(function _callee5$(_context6) { while (1) { - switch (_context5.prev = _context5.next) { + switch (_context6.prev = _context6.next) { case 0: _id = pullLastDocumentId(endpointHash); - _context5.next = 3; - return (0, _helper.getDocFromPouchOrNull)(collection, _id); + _context6.next = 3; + return (0, _rxStorageHelper.findLocalDocument)(collection.localDocumentsStore, _id); case 3: - localDoc = _context5.sent; + localDoc = _context6.sent; - if (!localDoc) { - localDoc = { - _id: _id, - doc: doc - }; - } else { - localDoc.doc = doc; + if (localDoc) { + _context6.next = 8; + break; } - return _context5.abrupt("return", collection.pouch.put(localDoc)); + return _context6.abrupt("return", (0, _rxStorageHelper.writeSingleLocal)(collection.localDocumentsStore, { + document: { + _id: _id, + doc: doc, + _attachments: {} + } + })); - case 6: + case 8: + newDoc = (0, _util.flatClone)(localDoc); + newDoc.doc = doc; + return _context6.abrupt("return", (0, _rxStorageHelper.writeSingleLocal)(collection.localDocumentsStore, { + previous: localDoc, + document: newDoc + })); + + case 11: case "end": - return _context5.stop(); + return _context6.stop(); } } }, _callee5); diff --git a/dist/lib/plugins/replication-graphql/helper.js b/dist/lib/plugins/replication-graphql/helper.js index 8be63a30ac3..f29c6e8721e 100644 --- a/dist/lib/plugins/replication-graphql/helper.js +++ b/dist/lib/plugins/replication-graphql/helper.js @@ -1,142 +1,39 @@ "use strict"; -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); - Object.defineProperty(exports, "__esModule", { value: true }); -exports.getDocFromPouchOrNull = getDocFromPouchOrNull; -exports.getDocsWithRevisionsFromPouch = getDocsWithRevisionsFromPouch; exports.createRevisionForPulledDocument = createRevisionForPulledDocument; exports.wasRevisionfromPullReplication = wasRevisionfromPullReplication; -exports.DEFAULT_MODIFIER = exports.PLUGIN_IDENT = void 0; - -var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); - -var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +exports.DEFAULT_MODIFIER = exports.GRAPHQL_REPLICATION_PLUGIN_IDENT = void 0; var _util = require("../../util"); -var PLUGIN_IDENT = 'rxdbreplicationgraphql'; // does nothing +var GRAPHQL_REPLICATION_PLUGIN_IDENT = 'rxdbreplicationgraphql'; // does nothing -exports.PLUGIN_IDENT = PLUGIN_IDENT; +exports.GRAPHQL_REPLICATION_PLUGIN_IDENT = GRAPHQL_REPLICATION_PLUGIN_IDENT; var DEFAULT_MODIFIER = function DEFAULT_MODIFIER(d) { return Promise.resolve(d); }; /** - * pouchdb will throw if a document is not found - * this instead return null + * Returns a new revision key without the revision height. + * The revision is crafted for the graphql replication + * and contains the information that this document data was pulled + * from the remote server and not saved by the client. */ exports.DEFAULT_MODIFIER = DEFAULT_MODIFIER; -function getDocFromPouchOrNull(collection, id) { - return collection.pouch.get(id, { - open_revs: true - }).then(function (docData) { - return docData; - })["catch"](function () { - return null; - }); -} -/** - * - * @return revisions and docs, indexed by id - */ - - -function getDocsWithRevisionsFromPouch(_x, _x2) { - return _getDocsWithRevisionsFromPouch.apply(this, arguments); -} - -function _getDocsWithRevisionsFromPouch() { - _getDocsWithRevisionsFromPouch = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(collection, docIds) { - var pouch, allDocs, docsSearch, bulkGetDocs, ret; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(docIds.length === 0)) { - _context.next = 2; - break; - } - - return _context.abrupt("return", {}); - - case 2: - // optimisation shortcut - pouch = collection.pouch; - _context.next = 5; - return pouch.allDocs({ - keys: docIds, - revs: true, - deleted: 'ok' - }); - - case 5: - allDocs = _context.sent; - // console.log('allDocs:'); - // console.log(JSON.stringify(allDocs, null, 2)); - docsSearch = allDocs.rows.filter(function (row) { - return !row.error; - }).map(function (row) { - return { - id: row.id, - rev: row.value.rev - }; - }); - - if (!(docsSearch.length === 0)) { - _context.next = 9; - break; - } - - return _context.abrupt("return", {}); - - case 9: - _context.next = 11; - return pouch.bulkGet({ - docs: docsSearch, - revs: true, - latest: true - }); - - case 11: - bulkGetDocs = _context.sent; - // console.log('bulkGetDocs:'); - // console.log(JSON.stringify(bulkGetDocs, null, 2)); - ret = {}; - bulkGetDocs.results.forEach(function (result) { - var doc = result.docs[0].ok; - var data = { - revisions: doc._revisions, - deleted: !!doc._deleted, - doc: doc - }; - ret[result.id] = data; - }); - return _context.abrupt("return", ret); - - case 15: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - return _getDocsWithRevisionsFromPouch.apply(this, arguments); -} - function createRevisionForPulledDocument(endpointHash, doc) { var dataHash = (0, _util.hash)(doc); - var ret = dataHash.substring(0, 8) + endpointHash.substring(0, 8) + PLUGIN_IDENT; + var ret = dataHash.substring(0, 8) + endpointHash.substring(0, 8) + GRAPHQL_REPLICATION_PLUGIN_IDENT; return ret; } function wasRevisionfromPullReplication(endpointHash, revision) { - var ending = endpointHash.substring(0, 8) + PLUGIN_IDENT; + var ending = endpointHash.substring(0, 8) + GRAPHQL_REPLICATION_PLUGIN_IDENT; var ret = revision.endsWith(ending); return ret; } diff --git a/dist/lib/plugins/replication-graphql/index.js b/dist/lib/plugins/replication-graphql/index.js index 3ba025a8660..ce093e833e9 100644 --- a/dist/lib/plugins/replication-graphql/index.js +++ b/dist/lib/plugins/replication-graphql/index.js @@ -57,13 +57,13 @@ Object.keys(_crawlingCheckpoint).forEach(function (key) { }); }); -var _watchForChanges = require("../watch-for-changes"); - var _leaderElection = require("../leader-election"); +var _overwritable = require("../../overwritable"); + var _rxChangeEvent = require("../../rx-change-event"); -var _overwritable = require("../../overwritable"); +var _rxCollectionHelper = require("../../rx-collection-helper"); var _graphqlSchemaFromRxSchema = require("./graphql-schema-from-rx-schema"); @@ -100,15 +100,9 @@ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o = function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } (0, _core.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); -/** - * add the watch-for-changes-plugin - * so pouchdb will emit events when something gets written to it - */ - -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); var RxGraphQLReplicationState = /*#__PURE__*/function () { - function RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, lastPulledRevField, live, liveInterval, retryTime, syncRevisions) { + function RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, live, liveInterval, retryTime) { this._subjects = { recieved: new _rxjs.Subject(), // all documents that are recieved from the endpoint @@ -139,11 +133,9 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { this.pull = pull; this.push = push; this.deletedFlag = deletedFlag; - this.lastPulledRevField = lastPulledRevField; this.live = live; this.liveInterval = liveInterval; this.retryTime = retryTime; - this.syncRevisions = syncRevisions; this.client = (0, _graphqlClient["default"])({ url: url, headers: headers @@ -180,7 +172,7 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { return true; } - if (!this.live && this._subjects.initialReplicationComplete['_value']) { + if (!this.live && this._subjects.initialReplicationComplete.getValue()) { return true; } @@ -245,7 +237,7 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { _this2._subjects.active.next(false); - if (retryOnFail && !willRetry && _this2._subjects.initialReplicationComplete['_value'] === false) { + if (retryOnFail && !willRetry && _this2._subjects.initialReplicationComplete.getValue() === false) { _this2._subjects.initialReplicationComplete.next(true); } @@ -364,7 +356,9 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { return _run; }() /** - * @return true if sucessfull + * Pull all changes from the server, + * start from the last pulled change. + * @return true if sucessfull, false if something errored */ ; @@ -374,7 +368,7 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { var _runPull = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { var _this4 = this; - var latestDocument, latestDocumentData, pullGraphQL, result, err, data, modified, docIds, docsWithRevisions, newLatestDocument; + var latestDocument, latestDocumentData, pullGraphQL, result, err, data, modified, newLatestDocument; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { @@ -437,8 +431,17 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { case 27: // this assumes that there will be always only one property in the response // is this correct? - data = result.data[Object.keys(result.data)[0]]; - _context5.next = 30; + data = result.data[Object.keys(result.data)[0]]; // optimisation shortcut, do not proceed if there are no documents. + + if (!(data.length === 0)) { + _context5.next = 30; + break; + } + + return _context5.abrupt("return", true); + + case 30: + _context5.next = 32; return Promise.all(data.map( /*#__PURE__*/function () { var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(doc) { return _regenerator["default"].wrap(function _callee4$(_context4) { @@ -464,63 +467,53 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { }; }())); - case 30: + case 32: modified = _context5.sent.filter(function (doc) { return !!doc; }); if (!_overwritable.overwritable.isDevMode()) { - _context5.next = 40; + _context5.next = 42; break; } - _context5.prev = 32; + _context5.prev = 34; modified.forEach(function (doc) { - var withoutDeleteFlag = Object.assign({}, doc); + var withoutDeleteFlag = (0, _util.flatClone)(doc); delete withoutDeleteFlag[_this4.deletedFlag]; - delete withoutDeleteFlag._revisions; _this4.collection.schema.validate(withoutDeleteFlag); }); - _context5.next = 40; + _context5.next = 42; break; - case 36: - _context5.prev = 36; - _context5.t1 = _context5["catch"](32); + case 38: + _context5.prev = 38; + _context5.t1 = _context5["catch"](34); this._subjects.error.next(_context5.t1); return _context5.abrupt("return", false); - case 40: - docIds = modified.map(function (doc) { - return doc[_this4.collection.schema.primaryPath]; - }); - _context5.next = 43; - return (0, _helper.getDocsWithRevisionsFromPouch)(this.collection, docIds); - - case 43: - docsWithRevisions = _context5.sent; - + case 42: if (!this.isStopped()) { - _context5.next = 46; + _context5.next = 44; break; } return _context5.abrupt("return", true); - case 46: - _context5.next = 48; - return this.handleDocumentsFromRemote(modified, docsWithRevisions); + case 44: + _context5.next = 46; + return this.handleDocumentsFromRemote(modified); - case 48: + case 46: modified.map(function (doc) { return _this4._subjects.recieved.next(doc); }); if (!(modified.length === 0)) { - _context5.next = 53; + _context5.next = 51; break; } @@ -528,27 +521,27 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { } else {// console.log('RxGraphQLReplicationState._run(): no more docs and not live; complete = true'); } - _context5.next = 58; + _context5.next = 56; break; - case 53: + case 51: newLatestDocument = modified[modified.length - 1]; - _context5.next = 56; + _context5.next = 54; return (0, _crawlingCheckpoint.setLastPullDocument)(this.collection, this.endpointHash, newLatestDocument); - case 56: - _context5.next = 58; + case 54: + _context5.next = 56; return this.runPull(); - case 58: + case 56: return _context5.abrupt("return", true); - case 59: + case 57: case "end": return _context5.stop(); } } - }, _callee5, this, [[9, 23], [32, 36]]); + }, _callee5, this, [[9, 23], [34, 38]]); })); function runPull() { @@ -568,55 +561,45 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { var _runPush = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { var _this5 = this; - var changes, changesWithDocs, lastSuccessfullChange, i, changeWithDoc, pushObj, result, err; + var changesResult, changesWithDocs, lastSuccessfullChange, i, changeWithDoc, pushObj, result, err; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; - return (0, _crawlingCheckpoint.getChangesSinceLastPushSequence)(this.collection, this.endpointHash, this.lastPulledRevField, this.push.batchSize, this.syncRevisions); + return (0, _crawlingCheckpoint.getChangesSinceLastPushSequence)(this.collection, this.endpointHash, this.push.batchSize); case 2: - changes = _context7.sent; + changesResult = _context7.sent; _context7.next = 5; - return Promise.all(changes.results.map( /*#__PURE__*/function () { - var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(change) { - var doc, seq; + return Promise.all(Array.from(changesResult.changedDocs.values()).map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(row) { + var changedDoc; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: - doc = change['doc']; - doc[_this5.deletedFlag] = !!change['deleted']; - delete doc._deleted; - delete doc._attachments; - delete doc[_this5.lastPulledRevField]; - - if (!_this5.syncRevisions) { - delete doc._rev; - } - - _context6.next = 8; - return _this5.push.modifier(doc); + changedDoc = row.doc; + _context6.next = 3; + return _this5.push.modifier(changedDoc); - case 8: - doc = _context6.sent; + case 3: + changedDoc = _context6.sent; - if (doc) { - _context6.next = 11; + if (changedDoc) { + _context6.next = 6; break; } return _context6.abrupt("return", null); - case 11: - seq = change.seq; + case 6: return _context6.abrupt("return", { - doc: doc, - seq: seq + doc: changedDoc, + sequence: row.sequence }); - case 13: + case 7: case "end": return _context6.stop(); } @@ -631,7 +614,7 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { case 5: changesWithDocs = _context7.sent.filter(function (doc) { - return doc; + return !!doc; }); lastSuccessfullChange = null; _context7.prev = 7; @@ -639,81 +622,87 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { case 9: if (!(i < changesWithDocs.length)) { - _context7.next = 32; + _context7.next = 33; break; } - changeWithDoc = changesWithDocs[i]; - _context7.next = 13; + changeWithDoc = changesWithDocs[i]; // TODO _deleted should be required on type RxDocumentData + // so we do not need this check here + + if (!changeWithDoc.doc.hasOwnProperty('_deleted')) { + changeWithDoc.doc._deleted = false; + } + + _context7.next = 14; return this.push.queryBuilder(changeWithDoc.doc); - case 13: + case 14: pushObj = _context7.sent; - _context7.next = 16; + _context7.next = 17; return this.client.query(pushObj.query, pushObj.variables); - case 16: + case 17: result = _context7.sent; if (!result.errors) { - _context7.next = 27; + _context7.next = 28; break; } if (!(typeof result.errors === 'string')) { - _context7.next = 22; + _context7.next = 23; break; } throw new Error(result.errors); - case 22: + case 23: err = new Error('unknown errors occured - see innerErrors for more details'); err.innerErrors = result.errors; throw err; - case 25: - _context7.next = 29; + case 26: + _context7.next = 30; break; - case 27: + case 28: this._subjects.send.next(changeWithDoc.doc); lastSuccessfullChange = changeWithDoc; - case 29: + case 30: i++; _context7.next = 9; break; - case 32: - _context7.next = 41; + case 33: + _context7.next = 42; break; - case 34: - _context7.prev = 34; + case 35: + _context7.prev = 35; _context7.t0 = _context7["catch"](7); if (!lastSuccessfullChange) { - _context7.next = 39; + _context7.next = 40; break; } - _context7.next = 39; - return (0, _crawlingCheckpoint.setLastPushSequence)(this.collection, this.endpointHash, lastSuccessfullChange.seq); + _context7.next = 40; + return (0, _crawlingCheckpoint.setLastPushSequence)(this.collection, this.endpointHash, lastSuccessfullChange.sequence); - case 39: + case 40: this._subjects.error.next(_context7.t0); return _context7.abrupt("return", false); - case 41: - _context7.next = 43; - return (0, _crawlingCheckpoint.setLastPushSequence)(this.collection, this.endpointHash, changes.last_seq); + case 42: + _context7.next = 44; + return (0, _crawlingCheckpoint.setLastPushSequence)(this.collection, this.endpointHash, changesResult.lastSequence); - case 43: - if (!(changes.results.length === 0)) { - _context7.next = 47; + case 44: + if (!(changesResult.changedDocs.size === 0)) { + _context7.next = 48; break; } @@ -721,22 +710,22 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { } else {// console.log('RxGraphQLReplicationState._runPull(): no more docs to push and not live; complete = true'); } - _context7.next = 49; + _context7.next = 50; break; - case 47: - _context7.next = 49; + case 48: + _context7.next = 50; return this.runPush(); - case 49: + case 50: return _context7.abrupt("return", true); - case 50: + case 51: case "end": return _context7.stop(); } } - }, _callee7, this, [[7, 34]]); + }, _callee7, this, [[7, 35]]); })); function runPush() { @@ -747,67 +736,64 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { }(); _proto.handleDocumentsFromRemote = /*#__PURE__*/function () { - var _handleDocumentsFromRemote = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(docs, docsWithRevisions) { + var _handleDocumentsFromRemote = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(docs) { var _this6 = this; - var toPouchDocs, _iterator, _step, doc, deletedValue, toPouch, primaryValue, pouchState, newRevision, newRevisionHeight, revisionId, startTime, endTime, _i, _toPouchDocs, tpd, originalDoc, cE; + var toStorageDocs, docIds, docsFromLocal, _iterator, _step, doc, documentId, deletedValue, docStateInLocalStorageInstance, newRevision, hasHeight, newRevisionHeight; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: - toPouchDocs = []; + toStorageDocs = []; + docIds = docs.map(function (doc) { + return doc[_this6.collection.schema.primaryPath]; + }); + _context9.next = 4; + return this.collection.storageInstance.findDocumentsById(docIds, true); + + case 4: + docsFromLocal = _context9.sent; for (_iterator = _createForOfIteratorHelperLoose(docs); !(_step = _iterator()).done;) { doc = _step.value; + documentId = doc[this.collection.schema.primaryPath]; deletedValue = doc[this.deletedFlag]; - toPouch = this.collection._handleToPouch(doc); - toPouch._deleted = deletedValue; - delete toPouch[this.deletedFlag]; - - if (!this.syncRevisions) { - primaryValue = toPouch._id; - pouchState = docsWithRevisions[primaryValue]; - newRevision = (0, _helper.createRevisionForPulledDocument)(this.endpointHash, toPouch); - - if (pouchState) { - newRevisionHeight = pouchState.revisions.start + 1; - revisionId = newRevision; - newRevision = newRevisionHeight + '-' + newRevision; - toPouch._revisions = { - start: newRevisionHeight, - ids: pouchState.revisions.ids - }; - - toPouch._revisions.ids.unshift(revisionId); - } else { - newRevision = '1-' + newRevision; - } - - toPouch._rev = newRevision; + doc._deleted = deletedValue; + delete doc[this.deletedFlag]; + docStateInLocalStorageInstance = docsFromLocal.get(documentId); + newRevision = (0, _helper.createRevisionForPulledDocument)(this.endpointHash, doc); + + if (docStateInLocalStorageInstance) { + hasHeight = (0, _util.getHeightOfRevision)(docStateInLocalStorageInstance._rev); + newRevisionHeight = hasHeight + 1; + newRevision = newRevisionHeight + '-' + newRevision; } else { - toPouch[this.lastPulledRevField] = toPouch._rev; + newRevision = '1-' + newRevision; } - toPouchDocs.push({ - doc: toPouch, + doc._rev = newRevision; + toStorageDocs.push({ + doc: doc, deletedValue: deletedValue }); } - startTime = (0, _util.now)(); - _context9.next = 5; + if (!(toStorageDocs.length > 0)) { + _context9.next = 9; + break; + } + + _context9.next = 9; return this.collection.database.lockedRun( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; - return _this6.collection.pouch.bulkDocs(toPouchDocs.map(function (tpd) { - return tpd.doc; - }), { - new_edits: false - }); + return _this6.collection.storageInstance.bulkAddRevisions(toStorageDocs.map(function (row) { + return (0, _rxCollectionHelper._handleToStorageInstance)(_this6.collection, row.doc); + })); case 2: case "end": @@ -817,34 +803,10 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { }, _callee8); }))); - case 5: - endTime = (0, _util.now)(); - /** - * because bulkDocs with new_edits: false - * does not stream changes to the pouchdb, - * we create the event and emit it, - * so other instances get informed about it - */ - - for (_i = 0, _toPouchDocs = toPouchDocs; _i < _toPouchDocs.length; _i++) { - tpd = _toPouchDocs[_i]; - originalDoc = (0, _util.flatClone)(tpd.doc); - - if (tpd.deletedValue) { - originalDoc._deleted = tpd.deletedValue; - } else { - delete originalDoc._deleted; - } - - delete originalDoc[this.deletedFlag]; - delete originalDoc._revisions; - cE = (0, _rxChangeEvent.changeEventfromPouchChange)(originalDoc, this.collection, startTime, endTime); - this.collection.$emit(cE); - } - + case 9: return _context9.abrupt("return", true); - case 8: + case 10: case "end": return _context9.stop(); } @@ -852,7 +814,7 @@ var RxGraphQLReplicationState = /*#__PURE__*/function () { }, _callee9, this); })); - function handleDocumentsFromRemote(_x3, _x4) { + function handleDocumentsFromRemote(_x3) { return _handleDocumentsFromRemote.apply(this, arguments); } @@ -894,8 +856,6 @@ function syncGraphQL(_ref5) { pull = _ref5.pull, push = _ref5.push, deletedFlag = _ref5.deletedFlag, - _ref5$lastPulledRevFi = _ref5.lastPulledRevField, - lastPulledRevField = _ref5$lastPulledRevFi === void 0 ? 'last_pulled_rev' : _ref5$lastPulledRevFi, _ref5$live = _ref5.live, live = _ref5$live === void 0 ? false : _ref5$live, _ref5$liveInterval = _ref5.liveInterval, @@ -903,9 +863,7 @@ function syncGraphQL(_ref5) { _ref5$retryTime = _ref5.retryTime, retryTime = _ref5$retryTime === void 0 ? 1000 * 5 : _ref5$retryTime, _ref5$autoStart = _ref5.autoStart, - autoStart = _ref5$autoStart === void 0 ? true : _ref5$autoStart, - _ref5$syncRevisions = _ref5.syncRevisions, - syncRevisions = _ref5$syncRevisions === void 0 ? false : _ref5$syncRevisions; + autoStart = _ref5$autoStart === void 0 ? true : _ref5$autoStart; var collection = this; // fill in defaults for pull & push if (pull) { @@ -914,11 +872,9 @@ function syncGraphQL(_ref5) { if (push) { if (!push.modifier) push.modifier = _helper.DEFAULT_MODIFIER; - } // ensure the collection is listening to plain-pouchdb writes - + } - collection.watchForChanges(); - var replicationState = new RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, lastPulledRevField, live, liveInterval, retryTime, syncRevisions); + var replicationState = new RxGraphQLReplicationState(collection, url, headers, pull, push, deletedFlag, live, liveInterval, retryTime); if (!autoStart) { return replicationState; @@ -979,13 +935,18 @@ function syncGraphQL(_ref5) { if (push) { /** - * we have to use the rxdb changestream - * because the pouchdb.changes stream sometimes - * does not emit events or stucks + * When a document is written to the collection, + * we might have to run the replication run() once */ - var changeEventsSub = collection.$.subscribe(function (changeEvent) { - if (replicationState.isStopped()) return; - var rev = changeEvent.documentData._rev; + var changeEventsSub = collection.$.pipe((0, _operators.filter)(function (cE) { + return !cE.isLocal; + })).subscribe(function (changeEvent) { + if (replicationState.isStopped()) { + return; + } + + var doc = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + var rev = doc._rev; if (rev && !(0, _helper.wasRevisionfromPullReplication)(replicationState.endpointHash, rev)) { replicationState.run(); diff --git a/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js b/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js index f87229bcd88..54789f915a3 100644 --- a/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js +++ b/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js @@ -64,10 +64,14 @@ function pushQueryBuilderFromRxSchema(collectionName, input) { var k = _ref[0], v = _ref[1]; - if (!input.ignoreInputKeys.includes(k)) { + if ( // skip if in ignoreInputKeys list + !input.ignoreInputKeys.includes(k) && // only use properties that are in the schema + input.schema.properties[k]) { sendDoc[k] = v; } - }); + }); // add deleted flag + + sendDoc[input.deletedFlag] = !!doc._deleted; var variables = (_variables = {}, _variables[collectionName] = sendDoc, _variables); return { query: query, diff --git a/dist/lib/plugins/server.js b/dist/lib/plugins/server.js index 7457c1e9743..9d1eea23156 100644 --- a/dist/lib/plugins/server.js +++ b/dist/lib/plugins/server.js @@ -13,25 +13,30 @@ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")) var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var os = _interopRequireWildcard(require("os")); + +var nodePath = _interopRequireWildcard(require("path")); + var _express = _interopRequireDefault(require("express")); var _cors = _interopRequireDefault(require("cors")); -var _pouchDb = require("../pouch-db"); +var _pouchdb = require("../plugins/pouchdb"); var _rxError = require("../rx-error"); var _core = require("../core"); -var _replication = require("./replication"); - -var _watchForChanges = require("./watch-for-changes"); +var _replicationCouchdb = require("./replication-couchdb"); var _pouchdbAdapterHttp = _interopRequireDefault(require("pouchdb-adapter-http")); -(0, _core.addRxPlugin)(_replication.RxDBReplicationPlugin); -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); -(0, _core.addRxPlugin)(_pouchdbAdapterHttp["default"]); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +(0, _core.addRxPlugin)(_replicationCouchdb.RxDBReplicationCouchDBPlugin); +(0, _pouchdb.addPouchPlugin)(_pouchdbAdapterHttp["default"]); var ExpressPouchDB; try { @@ -44,7 +49,7 @@ try { var PouchdbAllDbs = require('pouchdb-all-dbs'); -PouchdbAllDbs(_pouchDb.PouchDB); +PouchdbAllDbs(_pouchdb.PouchDB); var APP_OF_DB = new WeakMap(); var SERVERS_OF_DB = new WeakMap(); var DBS_WITH_SERVER = new WeakSet(); @@ -62,9 +67,16 @@ var getPrefix = function getPrefix(db) { }); splitted.pop(); // last was the name - if (splitted.length === 0) return ''; + if (splitted.length === 0) { + return ''; + } + var ret = splitted.join('/') + '/'; - if (db.name.startsWith('/')) ret = '/' + ret; + + if (db.name.startsWith('/')) { + ret = '/' + ret; + } + return ret; }; /** @@ -73,7 +85,6 @@ var getPrefix = function getPrefix(db) { function tunnelCollectionPath(db, path, app, colName) { - db[colName].watchForChanges(); var pathWithSlash = path.endsWith('/') ? path : path + '/'; var collectionPath = pathWithSlash + colName; app.use(collectionPath, /*#__PURE__*/function () { @@ -125,132 +136,173 @@ function tunnelCollectionPath(db, path, app, colName) { }()); } -function spawnServer(_ref2) { - var _ref2$path = _ref2.path, - path = _ref2$path === void 0 ? '/db' : _ref2$path, - _ref2$port = _ref2.port, - port = _ref2$port === void 0 ? 3000 : _ref2$port, - _ref2$cors = _ref2.cors, - cors = _ref2$cors === void 0 ? false : _ref2$cors, - _ref2$startServer = _ref2.startServer, - startServer = _ref2$startServer === void 0 ? true : _ref2$startServer, - _ref2$pouchdbExpressO = _ref2.pouchdbExpressOptions, - pouchdbExpressOptions = _ref2$pouchdbExpressO === void 0 ? {} : _ref2$pouchdbExpressO; - var db = this; - var collectionsPath = startServer ? path : '/'; - if (!SERVERS_OF_DB.has(db)) SERVERS_OF_DB.set(db, []); - - var pseudo = _pouchDb.PouchDB.defaults({ - adapter: db.adapter, - prefix: getPrefix(db), - log: false - }); +function spawnServer(_x4) { + return _spawnServer.apply(this, arguments); +} +/** + * when a server is created, no more collections can be spawned + */ - var app = (0, _express["default"])(); - APP_OF_DB.set(db, app); // tunnel requests so collection-names can be used as paths - Object.keys(db.collections).forEach(function (colName) { - return tunnelCollectionPath(db, collectionsPath, app, colName); - }); // remember to throw error if collection is created after the server is already there +function _spawnServer() { + _spawnServer = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(_ref2) { + var _ref2$path, path, _ref2$port, port, _ref2$cors, cors, _ref2$startServer, startServer, _ref2$pouchdbExpressO, pouchdbExpressOptions, db, collectionsPath, storage, pseudo, app, usePouchExpressOptions, pouchApp, server, startupPromise, response; - DBS_WITH_SERVER.add(db); + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _ref2$path = _ref2.path, path = _ref2$path === void 0 ? '/db' : _ref2$path, _ref2$port = _ref2.port, port = _ref2$port === void 0 ? 3000 : _ref2$port, _ref2$cors = _ref2.cors, cors = _ref2$cors === void 0 ? false : _ref2$cors, _ref2$startServer = _ref2.startServer, startServer = _ref2$startServer === void 0 ? true : _ref2$startServer, _ref2$pouchdbExpressO = _ref2.pouchdbExpressOptions, pouchdbExpressOptions = _ref2$pouchdbExpressO === void 0 ? {} : _ref2$pouchdbExpressO; + db = this; + collectionsPath = startServer ? path : '/'; - if (cors) { - app.use((0, _cors["default"])({ - 'origin': function origin(_origin, callback) { - var originToSend = _origin || '*'; - callback(null, originToSend); - }, - 'credentials': true, - 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT' - })); - } + if (!SERVERS_OF_DB.has(db)) { + SERVERS_OF_DB.set(db, []); + } - var pouchApp = ExpressPouchDB(pseudo, pouchdbExpressOptions); - app.use(collectionsPath, pouchApp); - var server = null; - var startupPromise = Promise.resolve(); - - if (startServer) { - /** - * Listen for errors on server startup. - * TODO in the next major release we should make db.server() async - * and properly handle the error instead of returning a startupPromise - */ - startupPromise = new Promise(function (res, rej) { - var answered = false; - server = app.listen(port, function () { - if (!answered) { - answered = true; - res(); - } - }); - server.on('error', function (err) { - if (!answered) { - answered = true; - rej(err); - } - }); - }); - SERVERS_OF_DB.get(db).push(server); - /** - * When the database has no documents, there is no db file - * and so the replication would not work. - * This is a hack which ensures that the couchdb instance exists - * and we can replicate even if there is no document in the beginning. - */ - - Promise.all(Object.values(db.collections).map( /*#__PURE__*/function () { - var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collection) { - var url, pingDb; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - url = 'http://localhost:' + port + collectionsPath + '/' + collection.name; - _context2.prev = 1; - pingDb = new _pouchDb.PouchDB(url); - _context2.next = 5; - return pingDb.info(); - - case 5: - _context2.next = 7; - return pingDb.close(); - - case 7: - _context2.next = 11; - break; + storage = db.storage; - case 9: - _context2.prev = 9; - _context2.t0 = _context2["catch"](1); + if (storage.adapter) { + _context3.next = 7; + break; + } - case 11: - case "end": - return _context2.stop(); + throw new Error('The RxDB server plugin only works with pouchdb storage.'); + + case 7: + pseudo = _pouchdb.PouchDB.defaults({ + adapter: storage.adapter, + prefix: getPrefix(db), + log: false + }); + app = (0, _express["default"])(); + APP_OF_DB.set(db, app); + Object.keys(db.collections).forEach(function (colName) { + // tunnel requests so collection-names can be used as paths + tunnelCollectionPath(db, collectionsPath, app, colName); + }); // remember to throw error if collection is created after the server is already there + + DBS_WITH_SERVER.add(db); + + if (cors) { + app.use((0, _cors["default"])({ + 'origin': function origin(_origin, callback) { + var originToSend = _origin || '*'; + callback(null, originToSend); + }, + 'credentials': true, + 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT' + })); } - } - }, _callee2, null, [[1, 9]]); - })); + /** + * Overwrite the defaults of PouchDBExpressServerOptions. + * In RxDB the defaults should not polute anything with folders so we store the config in memory + * and the logs in the tmp folder of the os. + */ - return function (_x4) { - return _ref3.apply(this, arguments); - }; - }())); - } - var response = { - app: app, - pouchApp: pouchApp, - server: server, - startupPromise: startupPromise - }; - return response; -} -/** - * when a server is created, no more collections can be spawned - */ + usePouchExpressOptions = (0, _core.flatClone)(pouchdbExpressOptions); + + if (typeof usePouchExpressOptions.inMemoryConfig === 'undefined') { + usePouchExpressOptions.inMemoryConfig = true; + } + + if (typeof usePouchExpressOptions.logPath === 'undefined') { + usePouchExpressOptions.logPath = nodePath.join(os.tmpdir(), 'rxdb-server-log.txt'); + } + + pouchApp = ExpressPouchDB(pseudo, usePouchExpressOptions); + app.use(collectionsPath, pouchApp); + server = null; + startupPromise = Promise.resolve(); + + if (startServer) { + /** + * Listen for errors on server startup. + * and properly handle the error instead of returning a startupPromise + */ + startupPromise = new Promise(function (res, rej) { + var answered = false; + server = app.listen(port, function () { + if (!answered) { + answered = true; + res(); + } + }); + server.on('error', function (err) { + if (!answered) { + answered = true; + rej(err); + } + }); + }); + SERVERS_OF_DB.get(db).push(server); + /** + * When the database has no documents, there is no db file + * and so the replication would not work. + * This is a hack which ensures that the couchdb instance exists + * and we can replicate even if there is no document in the beginning. + */ + + Promise.all(Object.values(db.collections).map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collection) { + var url, pingDb; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + url = 'http://localhost:' + port + collectionsPath + '/' + collection.name; + _context2.prev = 1; + pingDb = new _pouchdb.PouchDB(url); + _context2.next = 5; + return pingDb.info(); + + case 5: + _context2.next = 7; + return pingDb.close(); + + case 7: + _context2.next = 11; + break; + + case 9: + _context2.prev = 9; + _context2.t0 = _context2["catch"](1); + + case 11: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[1, 9]]); + })); + + return function (_x5) { + return _ref3.apply(this, arguments); + }; + }())); + } + + _context3.next = 23; + return startupPromise; + + case 23: + response = { + app: app, + pouchApp: pouchApp, + server: server + }; + return _context3.abrupt("return", response); + case 25: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + return _spawnServer.apply(this, arguments); +} function ensureNoMoreCollections(args) { if (DBS_WITH_SERVER.has(args.database)) { diff --git a/dist/lib/plugins/update.js b/dist/lib/plugins/update.js index d922fa943f5..b5db6714f14 100644 --- a/dist/lib/plugins/update.js +++ b/dist/lib/plugins/update.js @@ -24,7 +24,9 @@ function update(updateObj) { function RxQueryUpdate(updateObj) { return this.exec().then(function (docs) { - if (!docs) return null; + if (!docs) { + return null; + } if (Array.isArray(docs)) { return Promise.all(docs.map(function (doc) { diff --git a/dist/lib/plugins/watch-for-changes.js b/dist/lib/plugins/watch-for-changes.js deleted file mode 100644 index c8a55f6bab1..00000000000 --- a/dist/lib/plugins/watch-for-changes.js +++ /dev/null @@ -1,119 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.watchForChanges = watchForChanges; -exports.RxDBWatchForChangesPlugin = exports.prototypes = exports.rxdb = void 0; - -var _rxjs = require("rxjs"); - -var _operators = require("rxjs/operators"); - -var _util = require("../util"); - -var _rxChangeEvent = require("../rx-change-event"); - -/** - * listens to changes of the internal pouchdb - * and ensures they are emitted to the internal RxChangeEvent-Stream - */ -function watchForChanges() { - var _this = this; - - // do not call twice on same collection - if (this.synced) return; - this.synced = true; - this._watchForChangesUnhandled = new Set(); - /** - * this will grap the changes and publish them to the rx-stream - * this is to ensure that changes from 'synced' dbs will be published - */ - - var pouch$ = (0, _rxjs.fromEvent)(this.pouch.changes({ - since: 'now', - live: true, - include_docs: true - }), 'change').pipe((0, _operators.map)(function (ar) { - return ar[0]; - }) // rxjs6.x fires an array for whatever reason - ).subscribe(function (change) { - var resPromise = _handleSingleChange(_this, change); // add and remove to the Set so RxReplicationState.complete$ can know when all events where handled - - - _this._watchForChangesUnhandled.add(resPromise); - - resPromise.then(function () { - _this._watchForChangesUnhandled["delete"](resPromise); - }); - }); - - this._subs.push(pouch$); -} -/** - * handles a single change-event - * and ensures that it is not already handled - */ - - -function _handleSingleChange(collection, change) { - if (change.id.charAt(0) === '_') { - // do not handle changes of internal docs - return Promise.resolve(false); - } - - var startTime = (0, _util.now)(); - var endTime = (0, _util.now)(); // wait 2 ticks and 20 ms to give the internal event-handling time to run - - return (0, _util.promiseWait)(20).then(function () { - return (0, _util.nextTick)(); - }).then(function () { - return (0, _util.nextTick)(); - }).then(function () { - var docData = change.doc; // already handled by internal event-stream - - if (collection._changeEventBuffer.hasChangeWithRevision(docData._rev)) { - return false; - } - - var cE = (0, _rxChangeEvent.changeEventfromPouchChange)(docData, collection, startTime, endTime); - collection.$emit(cE); - return true; - }); -} -/** - * After a collection is destroyed, - * we must await all promises of collection._watchForChangesUnhandled - * to ensure nothing is running anymore. - */ - - -function postDestroyRxCollection(collection) { - var unhandled = collection._watchForChangesUnhandled; - - if (!unhandled) { - return Promise.resolve(); - } - - return Promise.all(Array.from(unhandled)); -} - -var rxdb = true; -exports.rxdb = rxdb; -var prototypes = { - RxCollection: function RxCollection(proto) { - proto.watchForChanges = watchForChanges; - } -}; -exports.prototypes = prototypes; -var RxDBWatchForChangesPlugin = { - name: 'watch-for-changes', - rxdb: rxdb, - prototypes: prototypes, - hooks: { - postDestroyRxCollection: postDestroyRxCollection - } -}; -exports.RxDBWatchForChangesPlugin = RxDBWatchForChangesPlugin; - -//# sourceMappingURL=watch-for-changes.js.map \ No newline at end of file diff --git a/dist/lib/pouch-db.js b/dist/lib/pouch-db.js deleted file mode 100644 index 0218ce19b38..00000000000 --- a/dist/lib/pouch-db.js +++ /dev/null @@ -1,204 +0,0 @@ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.countAllUndeleted = countAllUndeleted; -exports.getBatch = getBatch; -exports.isLevelDown = isLevelDown; -exports.validateCouchDBString = validateCouchDBString; -exports.pouchReplicationFunction = pouchReplicationFunction; -exports.pouchAttachmentBinaryHash = pouchAttachmentBinaryHash; -exports.getNewestSequence = getNewestSequence; -exports.isInstanceOf = isInstanceOf; -exports.PouchDB = void 0; - -var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); - -var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); - -var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); - -var _pouchdbFind = _interopRequireDefault(require("pouchdb-find")); - -var _pouchdbMd = require("pouchdb-md5"); - -var _rxError = require("./rx-error"); - -var _util = require("./util"); - -/** - * this handles the pouchdb-instance - * to easy add modules and manipulate things - * Adapters can be found here: - * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules - */ -// pouchdb-find -_pouchdbCore["default"].plugin(_pouchdbFind["default"]); -/* -// comment in to debug -const pouchdbDebug = require('pouchdb-debug'); -PouchDB.plugin(pouchdbDebug); -PouchDB.debug.enable('*'); -*/ - - -/** - * get the number of all undeleted documents - */ -function countAllUndeleted(pouchdb) { - return pouchdb.allDocs({ - include_docs: false, - attachments: false - }).then(function (docs) { - return docs.rows.filter(function (row) { - return !row.id.startsWith('_design/'); - }).length; - }); -} -/** - * get a batch of documents from the pouch-instance - */ - - -function getBatch(pouchdb, limit) { - if (limit <= 1) { - throw (0, _rxError.newRxError)('P1', { - limit: limit - }); - } - - return pouchdb.allDocs({ - include_docs: true, - attachments: false, - limit: limit - }).then(function (docs) { - return docs.rows.map(function (row) { - return row.doc; - }).filter(function (doc) { - return !doc._id.startsWith('_design'); - }); - }); -} -/** - * check if the given module is a leveldown-adapter - * throws if not - */ - - -function isLevelDown(adapter) { - if (!adapter || typeof adapter.super_ !== 'function') { - throw (0, _rxError.newRxError)('UT4', { - adapter: adapter - }); - } -} - -var validCouchDBStringRegexStr = '^[a-z][_$a-z0-9]*$'; -var validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr); -/** - * validates that a given string is ok to be used with couchdb-collection-names - * @link https://wiki.apache.org/couchdb/HTTP_database_API - * @throws {Error} - */ - -function validateCouchDBString(name) { - if (typeof name !== 'string' || name.length === 0) { - throw (0, _rxError.newRxTypeError)('UT1', { - name: name - }); - } // do not check, if foldername is given - - - if ((0, _util.isFolderPath)(name)) { - return true; - } - - if (!name.match(validCouchDBStringRegex)) { - throw (0, _rxError.newRxError)('UT2', { - regex: validCouchDBStringRegexStr, - givenName: name - }); - } - - return true; -} -/** - * get the correct function-name for pouchdb-replication - */ - - -function pouchReplicationFunction(pouch, _ref) { - var _ref$pull = _ref.pull, - pull = _ref$pull === void 0 ? true : _ref$pull, - _ref$push = _ref.push, - push = _ref$push === void 0 ? true : _ref$push; - if (pull && push) return pouch.sync.bind(pouch); - if (!pull && push) return pouch.replicate.to.bind(pouch); - if (pull && !push) return pouch.replicate.from.bind(pouch); - - if (!pull && !push) { - throw (0, _rxError.newRxError)('UT3', { - pull: pull, - push: push - }); - } -} -/** - * create the same diggest as an attachment with that data - * would have - */ - - -function pouchAttachmentBinaryHash(data) { - return new Promise(function (res) { - (0, _pouchdbMd.binaryMd5)(data, function (d) { - res('md5-' + d); - }); - }); -} - -function getNewestSequence(_x) { - return _getNewestSequence.apply(this, arguments); -} - -function _getNewestSequence() { - _getNewestSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(pouch) { - var pouchChanges; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return pouch.changes({ - live: false, - since: 0, - limit: 1, - descending: true, - include_docs: false - }); - - case 2: - pouchChanges = _context.sent; - return _context.abrupt("return", pouchChanges.last_seq); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - return _getNewestSequence.apply(this, arguments); -} - -function isInstanceOf(obj) { - return obj instanceof _pouchdbCore["default"]; -} - -var PouchDB = _pouchdbCore["default"]; -exports.PouchDB = PouchDB; - -//# sourceMappingURL=pouch-db.js.map \ No newline at end of file diff --git a/dist/lib/rx-change-event.js b/dist/lib/rx-change-event.js index cc5262933cb..e3be939bc9a 100644 --- a/dist/lib/rx-change-event.js +++ b/dist/lib/rx-change-event.js @@ -3,127 +3,58 @@ Object.defineProperty(exports, "__esModule", { value: true }); -exports.changeEventfromPouchChange = changeEventfromPouchChange; -exports.createInsertEvent = createInsertEvent; -exports.createUpdateEvent = createUpdateEvent; -exports.createDeleteEvent = createDeleteEvent; -exports.isInstanceOf = isInstanceOf; -exports.RxChangeEvent = void 0; +exports.getDocumentDataOfRxChangeEvent = getDocumentDataOfRxChangeEvent; +exports.isRxChangeEventIntern = isRxChangeEventIntern; +exports.rxChangeEventToEventReduceChangeEvent = rxChangeEventToEventReduceChangeEvent; + +var _overwritable = require("./overwritable"); /** * RxChangeEvents a emitted when something in the database changes * they can be grabbed by the observables of database, collection and document */ -var RxChangeEvent = /*#__PURE__*/function () { - function RxChangeEvent(operation, documentId, documentData, databaseToken, collectionName, isLocal, - /** - * timestam on when the operation was triggered - * and when it was finished - * This is optional because we do not have this time - * for events that come from pouchdbs changestream. - */ - startTime, endTime, previousData, rxDocument) { - this.operation = operation; - this.documentId = documentId; - this.documentData = documentData; - this.databaseToken = databaseToken; - this.collectionName = collectionName; - this.isLocal = isLocal; - this.startTime = startTime; - this.endTime = endTime; - this.previousData = previousData; - this.rxDocument = rxDocument; +function getDocumentDataOfRxChangeEvent(rxChangeEvent) { + if (rxChangeEvent.documentData) { + return rxChangeEvent.documentData; + } else { + return rxChangeEvent.previousDocumentData; } - - var _proto = RxChangeEvent.prototype; - - _proto.isIntern = function isIntern() { - if (this.collectionName && this.collectionName.charAt(0) === '_') { - return true; - } else { - return false; - } - }; - - _proto.toJSON = function toJSON() { - var ret = { - operation: this.operation, - documentId: this.documentId, - documentData: this.documentData, - previousData: this.previousData ? this.previousData : undefined, - databaseToken: this.databaseToken, - collectionName: this.collectionName, - isLocal: this.isLocal, - startTime: this.startTime, - endTime: this.endTime - }; - return ret; - }; - - _proto.toEventReduceChangeEvent = function toEventReduceChangeEvent() { - switch (this.operation) { - case 'INSERT': - return { - operation: this.operation, - id: this.documentId, - doc: this.documentData, - previous: null - }; - - case 'UPDATE': - return { - operation: this.operation, - id: this.documentId, - doc: this.documentData, - previous: this.previousData ? this.previousData : 'UNKNOWN' - }; - - case 'DELETE': - return { - operation: this.operation, - id: this.documentId, - doc: null, - previous: this.previousData - }; - } - }; - - return RxChangeEvent; -}(); - -exports.RxChangeEvent = RxChangeEvent; - -function changeEventfromPouchChange(changeDoc, collection, startTime, // time when the event was streamed out of pouchdb -endTime) { - var operation = changeDoc._rev.startsWith('1-') ? 'INSERT' : 'UPDATE'; - - if (changeDoc._deleted) { - operation = 'DELETE'; - } // decompress / primarySwap - - - var doc = collection._handleFromPouch(changeDoc); - - var documentId = doc[collection.schema.primaryPath]; - var cE = new RxChangeEvent(operation, documentId, doc, collection.database.token, collection.name, false, startTime, endTime); - return cE; -} - -function createInsertEvent(collection, docData, startTime, endTime, doc) { - var ret = new RxChangeEvent('INSERT', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, null, doc); - return ret; -} - -function createUpdateEvent(collection, docData, previous, startTime, endTime, rxDocument) { - return new RxChangeEvent('UPDATE', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, previous, rxDocument); } -function createDeleteEvent(collection, docData, previous, startTime, endTime, rxDocument) { - return new RxChangeEvent('DELETE', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, previous, rxDocument); +function isRxChangeEventIntern(rxChangeEvent) { + if (rxChangeEvent.collectionName && rxChangeEvent.collectionName.charAt(0) === '_') { + return true; + } else { + return false; + } } -function isInstanceOf(obj) { - return obj instanceof RxChangeEvent; +function rxChangeEventToEventReduceChangeEvent(rxChangeEvent) { + switch (rxChangeEvent.operation) { + case 'INSERT': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: rxChangeEvent.documentData, + previous: null + }; + + case 'UPDATE': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: _overwritable.overwritable.deepFreezeWhenDevMode(rxChangeEvent.documentData), + previous: rxChangeEvent.previousDocumentData ? rxChangeEvent.previousDocumentData : 'UNKNOWN' + }; + + case 'DELETE': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: null, + previous: rxChangeEvent.previousDocumentData + }; + } } //# sourceMappingURL=rx-change-event.js.map \ No newline at end of file diff --git a/dist/lib/rx-collection-helper.js b/dist/lib/rx-collection-helper.js index e721cab965d..4237d50928e 100644 --- a/dist/lib/rx-collection-helper.js +++ b/dist/lib/rx-collection-helper.js @@ -1,63 +1,183 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + Object.defineProperty(exports, "__esModule", { value: true }); -exports._handleToPouch = _handleToPouch; -exports._handleFromPouch = _handleFromPouch; +exports.writeToStorageInstance = writeToStorageInstance; +exports._handleToStorageInstance = _handleToStorageInstance; +exports._handleFromStorageInstance = _handleFromStorageInstance; exports.fillObjectDataBeforeInsert = fillObjectDataBeforeInsert; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + var _util = require("./util"); var _rxError = require("./rx-error"); +var _hooks = require("./hooks"); + +var _rxStorageHelper = require("./rx-storage-helper"); + /** - * wrappers for Pouch.put/get to handle keycompression etc + * Every write access on the storage engine, + * goes throught this method + * so we can run hooks and resolve stuff etc. + */ +function writeToStorageInstance(_x, _x2) { + return _writeToStorageInstance.apply(this, arguments); +} +/** + * wrappers to process document data beofre/after it goes to the storage instnace. + * Used to handle keycompression, encryption etc */ -function _handleToPouch(col, data) { - data = col._crypter.encrypt(data); - data = col.schema.swapPrimaryToId(data); - if (col.schema.doKeyCompression()) { - data = col._keyCompressor.compress(data); - } - return data; +function _writeToStorageInstance() { + _writeToStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collection, writeRow) { + var overwrite, + toStorageInstance, + writeResult, + ret, + _args2 = arguments; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + overwrite = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; + toStorageInstance = { + previous: writeRow.previous ? _handleToStorageInstance(collection, (0, _util.flatClone)(writeRow.previous)) : undefined, + document: _handleToStorageInstance(collection, (0, _util.flatClone)(writeRow.document)) + }; + + case 2: + if (!true) { + _context2.next = 16; + break; + } + + _context2.prev = 3; + _context2.next = 6; + return collection.database.lockedRun(function () { + return (0, _rxStorageHelper.writeSingle)(collection.storageInstance, toStorageInstance); + }); + + case 6: + writeResult = _context2.sent; + // on success, just return the result + ret = _handleFromStorageInstance(collection, writeResult); + return _context2.abrupt("return", ret); + + case 11: + _context2.prev = 11; + _context2.t0 = _context2["catch"](3); + return _context2.delegateYield( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var useErr, primary, singleRes; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + useErr = _context2.t0; + primary = useErr.documentId; + + if (!(overwrite && useErr.status === 409)) { + _context.next = 11; + break; + } + + _context.next = 5; + return collection.database.lockedRun(function () { + return (0, _rxStorageHelper.getSingleDocument)(collection.storageInstance, primary); + }); + + case 5: + singleRes = _context.sent; + + if (singleRes) { + _context.next = 8; + break; + } + + throw (0, _rxError.newRxError)('SNH'); + + case 8: + toStorageInstance.previous = singleRes; // now we can retry + + _context.next = 16; + break; + + case 11: + if (!(useErr.status === 409)) { + _context.next = 15; + break; + } + + throw (0, _rxError.newRxError)('COL19', { + id: primary, + pouchDbError: useErr, + data: writeRow + }); + + case 15: + throw useErr; + + case 16: + case "end": + return _context.stop(); + } + } + }, _callee); + })(), "t1", 14); + + case 14: + _context2.next = 2; + break; + + case 16: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[3, 11]]); + })); + return _writeToStorageInstance.apply(this, arguments); } -function _handleFromPouch(col, data) { +function _handleToStorageInstance(col, data) { + data = col._crypter.encrypt(data); + var hookParams = { + collection: col, + doc: data + }; + (0, _hooks.runPluginHooks)('preWriteToStorageInstance', hookParams); + return hookParams.doc; +} + +function _handleFromStorageInstance(col, data) { var noDecrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - data = col.schema.swapIdToPrimary(data); - if (col.schema.doKeyCompression()) data = col._keyCompressor.decompress(data); + var hookParams = { + collection: col, + doc: data + }; + (0, _hooks.runPluginHooks)('postReadFromInstance', hookParams); if (noDecrypt) { - return data; + return hookParams.doc; } - data = col._crypter.decrypt(data); - return data; + return col._crypter.decrypt(hookParams.doc); } /** - * fills in the _id and the - * default data. - * This also clones the data + * fills in the default data. + * This also clones the data. */ function fillObjectDataBeforeInsert(collection, data) { var useJson = collection.schema.fillObjectWithDefaults(data); - - if (useJson._id && collection.schema.primaryPath !== '_id') { - throw (0, _rxError.newRxError)('COL2', { - data: data - }); - } // fill _id - - - if (collection.schema.primaryPath === '_id' && !useJson._id) { - useJson._id = (0, _util.generateId)(); - } - return useJson; } diff --git a/dist/lib/rx-collection.js b/dist/lib/rx-collection.js index e7052e59932..1a4c52d4886 100644 --- a/dist/lib/rx-collection.js +++ b/dist/lib/rx-collection.js @@ -5,9 +5,9 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.create = create; -exports.isInstanceOf = isInstanceOf; -exports["default"] = exports.RxCollectionBase = void 0; +exports.createRxCollection = createRxCollection; +exports.isRxCollection = isRxCollection; +exports.RxCollectionBase = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -19,16 +19,12 @@ var _operators = require("rxjs/operators"); var _util = require("./util"); -var _pouchDb = require("./pouch-db"); - var _rxCollectionHelper = require("./rx-collection-helper"); var _rxQuery = require("./rx-query"); var _rxSchema = require("./rx-schema"); -var _rxChangeEvent = require("./rx-change-event"); - var _rxError = require("./rx-error"); var _crypter = require("./crypter"); @@ -39,21 +35,23 @@ var _queryCache = require("./query-cache"); var _changeEventBuffer = require("./change-event-buffer"); -var _overwritable = require("./overwritable"); - var _hooks = require("./hooks"); var _rxDocument = require("./rx-document"); var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); +var _rxStorageHelper = require("./rx-storage-helper"); + +var _checkNames = require("./plugins/dev-mode/check-names"); + var HOOKS_WHEN = ['pre', 'post']; var HOOKS_KEYS = ['insert', 'save', 'remove', 'create']; var hooksApplied = false; var RxCollectionBase = /*#__PURE__*/function () { function RxCollectionBase(database, name, schema) { - var pouchSettings = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var instanceCreationOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var migrationStrategies = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var methods = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; var attachments = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; @@ -67,15 +65,17 @@ var RxCollectionBase = /*#__PURE__*/function () { this.hooks = {}; this._subs = []; this._repStates = new Set(); - this.pouch = {}; + this.storageInstance = {}; + this.localDocumentsStore = {}; this._docCache = (0, _docCache.createDocCache)(); this._queryCache = (0, _queryCache.createQueryCache)(); this._crypter = {}; + this._observable$ = {}; this._changeEventBuffer = {}; this.database = database; this.name = name; this.schema = schema; - this.pouchSettings = pouchSettings; + this.instanceCreationOptions = instanceCreationOptions; this.migrationStrategies = migrationStrategies; this.methods = methods; this.attachments = attachments; @@ -92,49 +92,95 @@ var RxCollectionBase = /*#__PURE__*/function () { var _proto = RxCollectionBase.prototype; - _proto.prepare = function prepare( - /** - * set to true if the collection data already exists on this storage adapter - */ - wasCreatedBefore) { - var _this = this; + _proto.prepare = /*#__PURE__*/function () { + var _prepare = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee( + /** + * set to true if the collection data already exists on this storage adapter + */ + wasCreatedBefore) { + var _this = this; + + var storageInstanceCreationParams, _yield$Promise$all, storageInstance, localDocumentsStore, subDocs, subLocalDocs; - this.pouch = this.database._spawnPouchDB(this.name, this.schema.version, this.pouchSettings); + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + storageInstanceCreationParams = { + databaseName: this.database.name, + collectionName: this.name, + schema: this.schema.jsonSchema, + options: this.instanceCreationOptions + }; + (0, _hooks.runPluginHooks)('preCreateRxStorageInstance', storageInstanceCreationParams); + _context.next = 4; + return Promise.all([this.database.storage.createStorageInstance(storageInstanceCreationParams), this.database.storage.createKeyObjectStorageInstance(this.database.name, + /** + * Use a different collection name for the local documents instance + * so that the local docs can be kept while deleting the normal instance + * after migration. + */ + this.name + '-local', this.instanceCreationOptions)]); + + case 4: + _yield$Promise$all = _context.sent; + storageInstance = _yield$Promise$all[0]; + localDocumentsStore = _yield$Promise$all[1]; + this.storageInstance = storageInstance; + this.localDocumentsStore = localDocumentsStore; // we trigger the non-blocking things first and await them later so we can do stuff in the mean time + + this._crypter = (0, _crypter.createCrypter)(this.database.password, this.schema); + this._observable$ = this.database.$.pipe((0, _operators.filter)(function (event) { + return event.collectionName === _this.name; + })); + this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(this.asRxCollection); + subDocs = storageInstance.changeStream().pipe((0, _operators.map)(function (storageEvent) { + return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(false, storageEvent, _this.database, _this); + })).subscribe(function (cE) { + _this.$emit(cE); + }); - if (this.schema.doKeyCompression()) { - this._keyCompressor = _overwritable.overwritable.createKeyCompressor(this.schema); - } // we trigger the non-blocking things first and await them later so we can do stuff in the mean time + this._subs.push(subDocs); - /** - * Sometimes pouchdb emits before the instance is useable. - * To prevent random errors, we wait until the .info() call resolved - */ + subLocalDocs = this.localDocumentsStore.changeStream().pipe((0, _operators.map)(function (storageEvent) { + return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(true, storageEvent, _this.database, _this); + })).subscribe(function (cE) { + return _this.$emit(cE); + }); + this._subs.push(subLocalDocs); + /** + * When a write happens to the collection + * we find the changed document in the docCache + * and tell it that it has to change its data. + */ - var spawnedPouchPromise = wasCreatedBefore ? Promise.resolve() : this.pouch.info(); - /** - * if wasCreatedBefore we can assume that the indexes already exist - * because changing them anyway requires a schema-version change - */ - var createIndexesPromise = wasCreatedBefore ? Promise.resolve() : _prepareCreateIndexes(this.asRxCollection, spawnedPouchPromise); - this._crypter = (0, _crypter.createCrypter)(this.database.password, this.schema); - this._observable$ = this.database.$.pipe((0, _operators.filter)(function (event) { - return event.collectionName === _this.name; - })); - this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(this.asRxCollection); + this._subs.push(this._observable$.pipe((0, _operators.filter)(function (cE) { + return !cE.isLocal; + })).subscribe(function (cE) { + // when data changes, send it to RxDocument in docCache + var doc = _this._docCache.get(cE.documentId); - this._subs.push(this._observable$.pipe((0, _operators.filter)(function (cE) { - return !cE.isLocal; - })).subscribe(function (cE) { - // when data changes, send it to RxDocument in docCache - var doc = _this._docCache.get(cE.documentId); + if (doc) { + doc._handleChangeEvent(cE); + } + })); - if (doc) doc._handleChangeEvent(cE); + case 17: + case "end": + return _context.stop(); + } + } + }, _callee, this); })); - return Promise.all([spawnedPouchPromise, createIndexesPromise]); - } // overwritte by migration-plugin + function prepare(_x) { + return _prepare.apply(this, arguments); + } + + return prepare; + }() // overwritte by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { @@ -159,296 +205,286 @@ var RxCollectionBase = /*#__PURE__*/function () { return this.getDataMigrator().migratePromise(batchSize); } /** - * wrappers for Pouch.put/get to handle keycompression etc + * wrapps pouch-find */ ; - _proto._handleToPouch = function _handleToPouch(docData) { - return (0, _rxCollectionHelper._handleToPouch)(this, docData); - }; + _proto._queryStorageInstance = + /*#__PURE__*/ + function () { + var _queryStorageInstance2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rxQuery, limit) { + var _this2 = this; + + var noDecrypt, + preparedQuery, + queryResult, + docs, + _args2 = arguments; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + noDecrypt = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; + preparedQuery = rxQuery.toJSON(); - _proto._handleFromPouch = function _handleFromPouch(docData) { - var noDecrypt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - return (0, _rxCollectionHelper._handleFromPouch)(this, docData, noDecrypt); - } - /** - * every write on the pouchdb - * is tunneld throught this function - */ - ; + if (limit) { + preparedQuery['limit'] = limit; + } - _proto._pouchPut = function _pouchPut(obj) { - var _this2 = this; - - var overwrite = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - obj = this._handleToPouch(obj); - return this.database.lockedRun(function () { - return _this2.pouch.put(obj); - })["catch"](function (err) { - if (overwrite && err.status === 409) { - return _this2.database.lockedRun(function () { - return _this2.pouch.get(obj._id); - }).then(function (exist) { - obj._rev = exist._rev; - return _this2.database.lockedRun(function () { - return _this2.pouch.put(obj); - }); - }); - } else if (err.status === 409) { - throw (0, _rxError.newRxError)('COL19', { - id: obj._id, - pouchDbError: err, - data: obj - }); - } else throw err; - }); - } - /** - * get document from pouchdb by its _id - */ - ; + _context2.next = 5; + return this.database.lockedRun(function () { + return _this2.storageInstance.query(preparedQuery); + }); - _proto._pouchGet = function _pouchGet(key) { - var _this3 = this; + case 5: + queryResult = _context2.sent; + docs = queryResult.documents.map(function (doc) { + return (0, _rxCollectionHelper._handleFromStorageInstance)(_this2, doc, noDecrypt); + }); + return _context2.abrupt("return", docs); - return this.pouch.get(key).then(function (doc) { - return _this3._handleFromPouch(doc); - }); + case 8: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function _queryStorageInstance(_x2, _x3) { + return _queryStorageInstance2.apply(this, arguments); + } + + return _queryStorageInstance; + }(); + + _proto.$emit = function $emit(changeEvent) { + return this.database.$emit(changeEvent); } /** - * wrapps pouch-find + * TODO internally call bulkInsert + * to not have duplicated code. */ ; - _proto._pouchFind = function _pouchFind(rxQuery, limit) { - var _this4 = this; + _proto.insert = + /*#__PURE__*/ + function () { + var _insert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(json) { + var tempDoc, useJson, newDoc, insertResult; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + // inserting a temporary-document + tempDoc = null; - var noDecrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var compressedQueryJSON = rxQuery.keyCompress(); + if (!(0, _rxDocument.isRxDocument)(json)) { + _context3.next = 6; + break; + } - if (limit) { - compressedQueryJSON['limit'] = limit; - } + tempDoc = json; - return this.database.lockedRun(function () { - return _this4.pouch.find(compressedQueryJSON); - }).then(function (docsCompressed) { - var docs = docsCompressed.docs.map(function (doc) { - return _this4._handleFromPouch(doc, noDecrypt); - }); - return docs; - }); - }; + if (tempDoc._isTemporary) { + _context3.next = 5; + break; + } - _proto.$emit = function $emit(changeEvent) { - return this.database.$emit(changeEvent); - }; + throw (0, _rxError.newRxError)('COL1', { + data: json + }); - _proto.insert = function insert(json) { - var _this5 = this; + case 5: + json = tempDoc.toJSON(); - // inserting a temporary-document - var tempDoc = null; + case 6: + useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this, json); + newDoc = tempDoc; + _context3.next = 10; + return this._runHooks('pre', 'insert', useJson); + + case 10: + this.schema.validate(useJson); + _context3.next = 13; + return (0, _rxCollectionHelper.writeToStorageInstance)(this, { + document: useJson + }); - if ((0, _rxDocument.isInstanceOf)(json)) { - tempDoc = json; + case 13: + insertResult = _context3.sent; - if (!tempDoc._isTemporary) { - throw (0, _rxError.newRxError)('COL1', { - data: json - }); - } + if (tempDoc) { + tempDoc._dataSync$.next(insertResult); + } else { + newDoc = (0, _rxDocumentPrototypeMerge.createRxDocument)(this, insertResult); + } + + _context3.next = 17; + return this._runHooks('post', 'insert', useJson, newDoc); + + case 17: + return _context3.abrupt("return", newDoc); + + case 18: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); - json = tempDoc.toJSON(); + function insert(_x4) { + return _insert.apply(this, arguments); } - var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this, json); - var newDoc = tempDoc; - var startTime; - var endTime; - return this._runHooks('pre', 'insert', useJson).then(function () { - _this5.schema.validate(useJson); + return insert; + }(); - startTime = (0, _util.now)(); - return _this5._pouchPut(useJson); - }).then(function (insertResult) { - endTime = (0, _util.now)(); - useJson[_this5.schema.primaryPath] = insertResult.id; - useJson._rev = insertResult.rev; + _proto.bulkInsert = /*#__PURE__*/function () { + var _bulkInsert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(docsData) { + var _this3 = this; - if (tempDoc) { - tempDoc._dataSync$.next(useJson); - } else newDoc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this5, useJson); + var useDocs, docs, insertDocs, docsMap, results, successEntries, rxDocuments; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + useDocs = docsData.map(function (docData) { + var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this3, docData); + return useDocData; + }); + _context4.next = 3; + return Promise.all(useDocs.map(function (doc) { + return _this3._runHooks('pre', 'insert', doc).then(function () { + _this3.schema.validate(doc); - return _this5._runHooks('post', 'insert', useJson, newDoc); - }).then(function () { - // event - var emitEvent = (0, _rxChangeEvent.createInsertEvent)(_this5, useJson, startTime, endTime, newDoc); + return doc; + }); + })); - _this5.$emit(emitEvent); + case 3: + docs = _context4.sent; + insertDocs = docs.map(function (d) { + return { + document: (0, _rxCollectionHelper._handleToStorageInstance)(_this3, d) + }; + }); + docsMap = new Map(); + docs.forEach(function (d) { + docsMap.set(d[_this3.schema.primaryPath], d); + }); + _context4.next = 9; + return this.database.lockedRun(function () { + return _this3.storageInstance.bulkWrite(insertDocs); + }); - return newDoc; - }); - }; + case 9: + results = _context4.sent; + // create documents + successEntries = Array.from(results.success.entries()); + rxDocuments = successEntries.map(function (_ref) { + var key = _ref[0], + writtenDocData = _ref[1]; + var docData = (0, _util.getFromMapOrThrow)(docsMap, key); + docData._rev = writtenDocData._rev; + var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this3, docData); + return doc; + }); + _context4.next = 14; + return Promise.all(rxDocuments.map(function (doc) { + return _this3._runHooks('post', 'insert', docsMap.get(doc.primary), doc); + })); - _proto.bulkInsert = function bulkInsert(docsData) { - var _this6 = this; + case 14: + return _context4.abrupt("return", { + success: rxDocuments, + error: Array.from(results.error.values()) + }); - var useDocs = docsData.map(function (docData) { - var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this6, docData); - return useDocData; - }); - return Promise.all(useDocs.map(function (doc) { - return _this6._runHooks('pre', 'insert', doc).then(function () { - _this6.schema.validate(doc); + case 15: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); - return doc; - }); - })).then(function (docs) { - var insertDocs = docs.map(function (d) { - return _this6._handleToPouch(d); - }); - var docsMap = new Map(); - docs.forEach(function (d) { - docsMap.set(d[_this6.schema.primaryPath], d); - }); - return _this6.database.lockedRun(function () { - var startTime = (0, _util.now)(); - return _this6.pouch.bulkDocs(insertDocs).then(function (results) { - var okResults = results.filter(function (r) { - return r.ok; - }); // create documents - - var rxDocuments = okResults.map(function (r) { - var docData = docsMap.get(r.id); - docData._rev = r.rev; - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this6, docData); - return doc; - }); - return Promise.all(rxDocuments.map(function (doc) { - return _this6._runHooks('post', 'insert', docsMap.get(doc.primary), doc); - })).then(function () { - var errorResults = results.filter(function (r) { - return !r.ok; - }); - return { - rxDocuments: rxDocuments, - errorResults: errorResults - }; - }); - }).then(function (_ref) { - var rxDocuments = _ref.rxDocuments, - errorResults = _ref.errorResults; - var endTime = (0, _util.now)(); // emit events - - rxDocuments.forEach(function (doc) { - var emitEvent = (0, _rxChangeEvent.createInsertEvent)(_this6, doc.toJSON(true), startTime, endTime, doc); - - _this6.$emit(emitEvent); - }); - return { - success: rxDocuments, - error: errorResults - }; - }); - }); - }); - }; + function bulkInsert(_x5) { + return _bulkInsert.apply(this, arguments); + } + + return bulkInsert; + }(); _proto.bulkRemove = /*#__PURE__*/function () { - var _bulkRemove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(ids) { - var _this7 = this; + var _bulkRemove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(ids) { + var _this4 = this; - var rxDocumentMap, docsData, docsMap, removeDocs, startTime, results, endTime, okResults, rxDocuments; - return _regenerator["default"].wrap(function _callee2$(_context2) { + var rxDocumentMap, docsData, docsMap, removeDocs, results, successIds, rxDocuments; + return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context5.prev = _context5.next) { case 0: - _context2.next = 2; + _context5.next = 2; return this.findByIds(ids); case 2: - rxDocumentMap = _context2.sent; + rxDocumentMap = _context5.sent; docsData = []; docsMap = new Map(); Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { - var data = rxDocument.toJSON(true); + var data = (0, _util.clone)(rxDocument.toJSON(true)); docsData.push(data); docsMap.set(rxDocument.primary, data); }); - _context2.next = 8; + _context5.next = 8; return Promise.all(docsData.map(function (doc) { - var primary = doc[_this7.schema.primaryPath]; - return _this7._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); + var primary = doc[_this4.schema.primaryPath]; + return _this4._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); })); case 8: - docsData.forEach(function (doc) { - return doc._deleted = true; - }); removeDocs = docsData.map(function (doc) { - return _this7._handleToPouch(doc); + var writeDoc = (0, _util.flatClone)(doc); + writeDoc._deleted = true; + return { + previous: (0, _rxCollectionHelper._handleToStorageInstance)(_this4, doc), + document: (0, _rxCollectionHelper._handleToStorageInstance)(_this4, writeDoc) + }; }); - _context2.next = 12; - return this.database.lockedRun( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { - var bulkResults; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - startTime = (0, _util.now)(); - _context.next = 3; - return _this7.pouch.bulkDocs(removeDocs); - - case 3: - bulkResults = _context.sent; - return _context.abrupt("return", bulkResults); - - case 5: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); - - case 12: - results = _context2.sent; - endTime = (0, _util.now)(); - okResults = results.filter(function (r) { - return r.ok; + _context5.next = 11; + return this.database.lockedRun(function () { + return _this4.storageInstance.bulkWrite(removeDocs); }); - _context2.next = 17; - return Promise.all(okResults.map(function (r) { - return _this7._runHooks('post', 'remove', docsMap.get(r.id), rxDocumentMap.get(r.id)); - })); - case 17: - okResults.forEach(function (r) { - var rxDocument = rxDocumentMap.get(r.id); - var emitEvent = (0, _rxChangeEvent.createDeleteEvent)(_this7, docsMap.get(r.id), rxDocument._data, startTime, endTime, rxDocument); + case 11: + results = _context5.sent; + successIds = Array.from(results.success.keys()); // run hooks - _this7.$emit(emitEvent); - }); - rxDocuments = okResults.map(function (r) { - return rxDocumentMap.get(r.id); + _context5.next = 15; + return Promise.all(successIds.map(function (id) { + return _this4._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); + })); + + case 15: + rxDocuments = successIds.map(function (id) { + return rxDocumentMap.get(id); }); - return _context2.abrupt("return", { + return _context5.abrupt("return", { success: rxDocuments, - error: okResults.filter(function (r) { - return !r.ok; - }) + error: Array.from(results.error.values()) }); - case 20: + case 17: case "end": - return _context2.stop(); + return _context5.stop(); } } - }, _callee2, this); + }, _callee5, this); })); - function bulkRemove(_x) { + function bulkRemove(_x6) { return _bulkRemove.apply(this, arguments); } @@ -460,7 +496,7 @@ var RxCollectionBase = /*#__PURE__*/function () { ; _proto.upsert = function upsert(json) { - var _this8 = this; + var _this5 = this; var useJson = (0, _util.flatClone)(json); var primary = useJson[this.schema.primaryPath]; @@ -481,7 +517,7 @@ var RxCollectionBase = /*#__PURE__*/function () { return existing; }); } else { - return _this8.insert(json); + return _this5.insert(json); } }); } @@ -491,7 +527,7 @@ var RxCollectionBase = /*#__PURE__*/function () { ; _proto.atomicUpsert = function atomicUpsert(json) { - var _this9 = this; + var _this6 = this; var primary = json[this.schema.primaryPath]; @@ -511,13 +547,21 @@ var RxCollectionBase = /*#__PURE__*/function () { } queue = queue.then(function () { - return _atomicUpsertEnsureRxDocumentExists(_this9, primary, json); + return _atomicUpsertEnsureRxDocumentExists(_this6, primary, json); }).then(function (wasInserted) { if (!wasInserted.inserted) { - return _atomicUpsertUpdate(wasInserted.doc, json).then(function () { - return (0, _util.nextTick)(); - }) // tick here so the event can propagate + return _atomicUpsertUpdate(wasInserted.doc, json) + /** + * tick here so the event can propagate + * TODO we should not need that here + */ .then(function () { + return (0, _util.nextTick)(); + }).then(function () { + return (0, _util.nextTick)(); + }).then(function () { + return (0, _util.nextTick)(); + }).then(function () { return wasInserted.doc; }); } else return wasInserted.doc; @@ -547,10 +591,10 @@ var RxCollectionBase = /*#__PURE__*/function () { var query; if (typeof queryObj === 'string') { + var _selector; + query = (0, _rxQuery.createRxQuery)('findOne', { - selector: { - _id: queryObj - } + selector: (_selector = {}, _selector[this.schema.primaryPath] = queryObj, _selector) }, this); } else { if (!queryObj) { @@ -582,19 +626,19 @@ var RxCollectionBase = /*#__PURE__*/function () { _proto.findByIds = /*#__PURE__*/ function () { - var _findByIds = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(ids) { - var _this10 = this; + var _findByIds = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(ids) { + var _this7 = this; - var ret, mustBeQueried, result; - return _regenerator["default"].wrap(function _callee3$(_context3) { + var ret, mustBeQueried, docs; + return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context6.prev = _context6.next) { case 0: ret = new Map(); mustBeQueried = []; // first try to fill from docCache ids.forEach(function (id) { - var doc = _this10._docCache.get(id); + var doc = _this7._docCache.get(id); if (doc) { ret.set(id, doc); @@ -604,42 +648,33 @@ var RxCollectionBase = /*#__PURE__*/function () { }); // find everything which was not in docCache if (!(mustBeQueried.length > 0)) { - _context3.next = 8; + _context6.next = 8; break; } - _context3.next = 6; - return this.pouch.allDocs({ - include_docs: true, - keys: mustBeQueried - }); + _context6.next = 6; + return this.storageInstance.findDocumentsById(mustBeQueried, false); case 6: - result = _context3.sent; - result.rows.forEach(function (row) { - if (!row.doc) { - // not found - return; - } - - var plainData = _this10._handleFromPouch(row.doc); - - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this10, plainData); + docs = _context6.sent; + Array.from(docs.values()).forEach(function (docData) { + docData = (0, _rxCollectionHelper._handleFromStorageInstance)(_this7, docData); + var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this7, docData); ret.set(doc.primary, doc); }); case 8: - return _context3.abrupt("return", ret); + return _context6.abrupt("return", ret); case 9: case "end": - return _context3.stop(); + return _context6.stop(); } } - }, _callee3, this); + }, _callee6, this); })); - function findByIds(_x2) { + function findByIds(_x7) { return _findByIds.apply(this, arguments); } @@ -652,12 +687,12 @@ var RxCollectionBase = /*#__PURE__*/function () { ; _proto.findByIds$ = function findByIds$(ids) { - var _this11 = this; + var _this8 = this; var currentValue = null; var lastChangeEvent = -1; var initialPromise = this.findByIds(ids).then(function (docsMap) { - lastChangeEvent = _this11._changeEventBuffer.counter; + lastChangeEvent = _this8._changeEventBuffer.counter; currentValue = docsMap; }); return this.$.pipe((0, _operators.startWith)(null), (0, _operators.mergeMap)(function (ev) { @@ -672,32 +707,32 @@ var RxCollectionBase = /*#__PURE__*/function () { * since the last subscription. */ (0, _operators.mergeMap)( /*#__PURE__*/function () { - var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ev) { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(ev) { var resultMap, missedChangeEvents, newResult; - return _regenerator["default"].wrap(function _callee4$(_context4) { + return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context7.prev = _context7.next) { case 0: resultMap = (0, _util.ensureNotFalsy)(currentValue); - missedChangeEvents = _this11._changeEventBuffer.getFrom(lastChangeEvent + 1); + missedChangeEvents = _this8._changeEventBuffer.getFrom(lastChangeEvent + 1); if (!(missedChangeEvents === null)) { - _context4.next = 10; + _context7.next = 10; break; } - _context4.next = 5; - return _this11.findByIds(ids); + _context7.next = 5; + return _this8.findByIds(ids); case 5: - newResult = _context4.sent; - lastChangeEvent = _this11._changeEventBuffer.counter; - Array.from(newResult.entries()).forEach(function (_ref4) { - var k = _ref4[0], - v = _ref4[1]; + newResult = _context7.sent; + lastChangeEvent = _this8._changeEventBuffer.counter; + Array.from(newResult.entries()).forEach(function (_ref3) { + var k = _ref3[0], + v = _ref3[1]; return resultMap.set(k, v); }); - _context4.next = 11; + _context7.next = 11; break; case 10: @@ -707,25 +742,25 @@ var RxCollectionBase = /*#__PURE__*/function () { var op = rxChangeEvent.operation; if (op === 'INSERT' || op === 'UPDATE') { - resultMap.set(rxChangeEvent.documentId, _this11._docCache.get(rxChangeEvent.documentId)); + resultMap.set(rxChangeEvent.documentId, _this8._docCache.get(rxChangeEvent.documentId)); } else { resultMap["delete"](rxChangeEvent.documentId); } }); case 11: - return _context4.abrupt("return", resultMap); + return _context7.abrupt("return", resultMap); case 12: case "end": - return _context4.stop(); + return _context7.stop(); } } - }, _callee4); + }, _callee7); })); - return function (_x3) { - return _ref3.apply(this, arguments); + return function (_x8) { + return _ref2.apply(this, arguments); }; }()), (0, _operators.filter)(function (x) { return !!x; @@ -743,36 +778,26 @@ var RxCollectionBase = /*#__PURE__*/function () { */ ; - _proto.dump = function dump() { + _proto.exportJSON = function exportJSON() { var _decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; throw (0, _util.pluginMissing)('json-dump'); } /** * Import the parsed JSON export into the collection. - * @param _exportedJSON The previously exported data from the `.dump()` method. + * @param _exportedJSON The previously exported data from the `.exportJSON()` method. */ ; - _proto.importDump = function importDump(_exportedJSON) { + _proto.importJSON = function importJSON(_exportedJSON) { throw (0, _util.pluginMissing)('json-dump'); } /** - * waits for external changes to the database - * and ensures they are emitted to the internal RxChangeEvent-Stream - * TODO this can be removed by listening to the pull-change-events of the RxReplicationState - */ - ; - - _proto.watchForChanges = function watchForChanges() { - throw (0, _util.pluginMissing)('watch-for-changes'); - } - /** - * sync with another database + * sync with a CouchDB endpoint */ ; - _proto.sync = function sync(_syncOptions) { + _proto.syncCouchDB = function syncCouchDB(_syncOptions) { throw (0, _util.pluginMissing)('replication'); } /** @@ -894,6 +919,8 @@ var RxCollectionBase = /*#__PURE__*/function () { }; _proto.destroy = function destroy() { + var _this9 = this; + if (this.destroyed) { return Promise.resolve(false); } @@ -913,10 +940,12 @@ var RxCollectionBase = /*#__PURE__*/function () { Array.from(this._repStates).forEach(function (replicationState) { return replicationState.cancel(); }); - delete this.database.collections[this.name]; - this.destroyed = true; - return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', this).then(function () { - return true; + return this.storageInstance.close().then(function () { + delete _this9.database.collections[_this9.name]; + _this9.destroyed = true; + return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', _this9).then(function () { + return true; + }); }); } /** @@ -957,11 +986,11 @@ var RxCollectionBase = /*#__PURE__*/function () { }, { key: "onDestroy", get: function get() { - var _this12 = this; + var _this10 = this; if (!this._onDestroy) { this._onDestroy = new Promise(function (res) { - return _this12._onDestroyCall = res; + return _this10._onDestroyCall = res; }); } @@ -1015,6 +1044,19 @@ function _atomicUpsertUpdate(doc, json) { function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { + /** + * Optimisation shortcut, + * first try to find the document in the doc-cache + */ + var docFromCache = rxCollection._docCache.get(primary); + + if (docFromCache) { + return Promise.resolve({ + doc: docFromCache, + inserted: false + }); + } + return rxCollection.findOne(primary).exec().then(function (doc) { if (!doc) { return rxCollection.insert(json).then(function (newDoc) { @@ -1031,90 +1073,32 @@ function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { } }); } -/** - * creates the indexes in the pouchdb - */ - - -function _prepareCreateIndexes(rxCollection, spawnedPouchPromise) { - /** - * pouchdb does no check on already existing indexes - * which makes collection re-creation really slow on page reloads - * So we have to manually check if the index already exists - */ - return spawnedPouchPromise.then(function () { - return rxCollection.pouch.getIndexes(); - }).then(function (indexResult) { - var existingIndexes = new Set(); - indexResult.indexes.forEach(function (idx) { - return existingIndexes.add(idx.name); - }); - return existingIndexes; - }).then(function (existingIndexes) { - return Promise.all(rxCollection.schema.indexes.map(function (indexAr) { - var compressedIdx = indexAr.map(function (key) { - var primPath = rxCollection.schema.primaryPath; - var useKey = key === primPath ? '_id' : key; - - if (!rxCollection.schema.doKeyCompression()) { - return useKey; - } else { - var indexKey = rxCollection._keyCompressor.transformKey(useKey); - - return indexKey; - } - }); - var indexName = 'idx-rxdb-index-' + compressedIdx.join(','); - - if (existingIndexes.has(indexName)) { - // index already exists - return; - } - /** - * TODO - * we might have even better performance by doing a bulkDocs - * on index creation - */ - - - return spawnedPouchPromise.then(function () { - return rxCollection.pouch.createIndex({ - name: indexName, - ddoc: indexName, - index: { - fields: compressedIdx - } - }); - }); - })); - }); -} /** * creates and prepares a new collection */ -function create(_ref5, wasCreatedBefore) { - var database = _ref5.database, - name = _ref5.name, - schema = _ref5.schema, - _ref5$pouchSettings = _ref5.pouchSettings, - pouchSettings = _ref5$pouchSettings === void 0 ? {} : _ref5$pouchSettings, - _ref5$migrationStrate = _ref5.migrationStrategies, - migrationStrategies = _ref5$migrationStrate === void 0 ? {} : _ref5$migrationStrate, - _ref5$autoMigrate = _ref5.autoMigrate, - autoMigrate = _ref5$autoMigrate === void 0 ? true : _ref5$autoMigrate, - _ref5$statics = _ref5.statics, - statics = _ref5$statics === void 0 ? {} : _ref5$statics, - _ref5$methods = _ref5.methods, - methods = _ref5$methods === void 0 ? {} : _ref5$methods, - _ref5$attachments = _ref5.attachments, - attachments = _ref5$attachments === void 0 ? {} : _ref5$attachments, - _ref5$options = _ref5.options, - options = _ref5$options === void 0 ? {} : _ref5$options, - _ref5$cacheReplacemen = _ref5.cacheReplacementPolicy, - cacheReplacementPolicy = _ref5$cacheReplacemen === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref5$cacheReplacemen; - (0, _pouchDb.validateCouchDBString)(name); // ensure it is a schema-object +function createRxCollection(_ref4, wasCreatedBefore) { + var database = _ref4.database, + name = _ref4.name, + schema = _ref4.schema, + _ref4$instanceCreatio = _ref4.instanceCreationOptions, + instanceCreationOptions = _ref4$instanceCreatio === void 0 ? {} : _ref4$instanceCreatio, + _ref4$migrationStrate = _ref4.migrationStrategies, + migrationStrategies = _ref4$migrationStrate === void 0 ? {} : _ref4$migrationStrate, + _ref4$autoMigrate = _ref4.autoMigrate, + autoMigrate = _ref4$autoMigrate === void 0 ? true : _ref4$autoMigrate, + _ref4$statics = _ref4.statics, + statics = _ref4$statics === void 0 ? {} : _ref4$statics, + _ref4$methods = _ref4.methods, + methods = _ref4$methods === void 0 ? {} : _ref4$methods, + _ref4$attachments = _ref4.attachments, + attachments = _ref4$attachments === void 0 ? {} : _ref4$attachments, + _ref4$options = _ref4.options, + options = _ref4$options === void 0 ? {} : _ref4$options, + _ref4$cacheReplacemen = _ref4.cacheReplacementPolicy, + cacheReplacementPolicy = _ref4$cacheReplacemen === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref4$cacheReplacemen; + (0, _checkNames.validateDatabaseName)(name); // ensure it is a schema-object if (!(0, _rxSchema.isInstanceOf)(schema)) { schema = (0, _rxSchema.createRxSchema)(schema); @@ -1127,12 +1111,12 @@ function create(_ref5, wasCreatedBefore) { funName: funName }); }); - var collection = new RxCollectionBase(database, name, schema, pouchSettings, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics); + var collection = new RxCollectionBase(database, name, schema, instanceCreationOptions, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics); return collection.prepare(wasCreatedBefore).then(function () { // ORM add statics - Object.entries(statics).forEach(function (_ref6) { - var funName = _ref6[0], - fun = _ref6[1]; + Object.entries(statics).forEach(function (_ref5) { + var funName = _ref5[0], + fun = _ref5[1]; Object.defineProperty(collection, funName, { get: function get() { return fun.bind(collection); @@ -1152,15 +1136,8 @@ function create(_ref5, wasCreatedBefore) { }); } -function isInstanceOf(obj) { +function isRxCollection(obj) { return obj instanceof RxCollectionBase; } -var _default = { - create: create, - isInstanceOf: isInstanceOf, - RxCollectionBase: RxCollectionBase -}; -exports["default"] = _default; - //# sourceMappingURL=rx-collection.js.map \ No newline at end of file diff --git a/dist/lib/rx-database-internal-store.js b/dist/lib/rx-database-internal-store.js deleted file mode 100644 index 0ea53ec8b87..00000000000 --- a/dist/lib/rx-database-internal-store.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getLocalDocument = getLocalDocument; -exports.setLocalDocument = setLocalDocument; -exports.putDocument = putDocument; -exports.getAllDocuments = getAllDocuments; -exports.deleteStorageInstance = deleteStorageInstance; -exports.INTERNAL_STORAGE_NAME = void 0; - -var _util = require("./util"); - -/** - * In this file we handle all accesses to the internal store of the database - * This store is used to save hashes and checksums and metadata - * ATM this only works with PouchDB but in the future - * it should work by using the storage.interface - */ -// will be typed when we have more then one -var INTERNAL_STORAGE_NAME = '_rxdb_internal'; -/** - * returns to local document with the given id - * or null if not exists - */ - -exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; - -function getLocalDocument(storageInstance, id) { - return storageInstance.get(_util.LOCAL_PREFIX + id)["catch"](function () { - return null; - }); -} - -function setLocalDocument(storageInstance, id, value) { - return storageInstance.put({ - _id: id, - value: value - }).then(function () {}); -} - -function putDocument(storageInstance, doc) { - return storageInstance.put(doc).then(function (putResult) { - return Object.assign({ - _id: putResult.id, - _rev: putResult.rev - }, doc); - }); -} -/** - * returns all NON-LOCAL documents - */ - - -function getAllDocuments(storageInstance) { - return storageInstance.allDocs({ - include_docs: true - }).then(function (result) { - return result.rows; - }); -} -/** - * deletes the storage instance and all of it's data - */ - - -function deleteStorageInstance(storageInstance) { - return storageInstance.destroy(); -} - -//# sourceMappingURL=rx-database-internal-store.js.map \ No newline at end of file diff --git a/dist/lib/rx-database.js b/dist/lib/rx-database.js index a7b7416ab9a..12d220d7fe7 100644 --- a/dist/lib/rx-database.js +++ b/dist/lib/rx-database.js @@ -11,10 +11,9 @@ exports._collectionNamePrimary = _collectionNamePrimary; exports._removeAllOfCollection = _removeAllOfCollection; exports.createRxDatabase = createRxDatabase; exports.removeRxDatabase = removeRxDatabase; -exports.checkAdapter = checkAdapter; -exports.isInstanceOf = isInstanceOf; +exports.isRxDatabase = isRxDatabase; exports.dbCount = dbCount; -exports["default"] = exports.RxDatabaseBase = void 0; +exports.RxDatabaseBase = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -42,46 +41,45 @@ var _hooks = require("./hooks"); var _rxjs = require("rxjs"); -var _operators = require("rxjs/operators"); - -var _pouchDb = require("./pouch-db"); - var _rxCollection = require("./rx-collection"); -var _rxStoragePouchdb = require("./rx-storage-pouchdb"); +var _rxStorageHelper = require("./rx-storage-helper"); -var _rxDatabaseInternalStore = require("./rx-database-internal-store"); +var _rxSchemaHelper = require("./rx-schema-helper"); /** - * stores the combinations - * of used database-names with their adapters - * so we can throw when the same database is created more then once + * stores the used database names + * so we can throw when the same database is created more then once. */ -var USED_COMBINATIONS = {}; -var DB_COUNT = 0; +var USED_DATABASE_NAMES = new Set(); +var DB_COUNT = 0; // stores information about the collections var RxDatabaseBase = /*#__PURE__*/function () { - function RxDatabaseBase(name, adapter, password, multiInstance) { - var eventReduce = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; - var pouchSettings = arguments.length > 6 ? arguments[6] : undefined; + /** + * Stores information documents about the collections of the database + */ + + /** + * Stores the local documents which are attached to this database. + */ + function RxDatabaseBase(name, storage, instanceCreationOptions, password, multiInstance) { + var eventReduce = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + var options = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; this.internalStore = {}; + this.localDocumentsStore = {}; this.idleQueue = new _customIdleQueue.IdleQueue(); this.token = (0, _randomToken["default"])(10); this._subs = []; this.destroyed = false; this.subject = new _rxjs.Subject(); - this.observable$ = this.subject.asObservable().pipe((0, _operators.filter)(function (cEvent) { - return (0, _rxChangeEvent.isInstanceOf)(cEvent); - })); + this.observable$ = this.subject.asObservable(); this.name = name; - this.adapter = adapter; + this.storage = storage; + this.instanceCreationOptions = instanceCreationOptions; this.password = password; this.multiInstance = multiInstance; this.eventReduce = eventReduce; this.options = options; - this.pouchSettings = pouchSettings; - this.storage = (0, _rxStoragePouchdb.getRxStoragePouchDb)(adapter, pouchSettings); this.collections = {}; DB_COUNT++; } @@ -93,31 +91,45 @@ var RxDatabaseBase = /*#__PURE__*/function () { * only use this if you have to upgrade from a major rxdb-version * do NEVER use this to change the schema of a collection */ - _proto.dangerousRemoveCollectionInfo = function dangerousRemoveCollectionInfo() { - var _this = this; - - return (0, _rxDatabaseInternalStore.getAllDocuments)(this.internalStore).then(function (docsRes) { - return Promise.all(docsRes.map(function (row) { - return { - _id: row.key, - _rev: row.value.rev - }; - }).map(function (doc) { - return _this.internalStore.remove(doc._id, doc._rev); - })); - }); - } - /** - * spawns a new pouch-instance - */ - ; + _proto.dangerousRemoveCollectionInfo = + /*#__PURE__*/ + function () { + var _dangerousRemoveCollectionInfo = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var allDocs, writeData; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _rxStorageHelper.getAllDocuments)(this.internalStore); + + case 2: + allDocs = _context.sent; + writeData = allDocs.map(function (doc) { + var deletedDoc = (0, _util.flatClone)(doc); + deletedDoc._deleted = true; + return { + previous: doc, + document: deletedDoc + }; + }); + _context.next = 6; + return this.internalStore.bulkWrite(writeData); - _proto._spawnPouchDB = function _spawnPouchDB(collectionName, schemaVersion) { - var pouchSettings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - return this.storage.createStorageInstance(this.name, collectionName, schemaVersion, { - pouchSettings: pouchSettings - }); - } + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function dangerousRemoveCollectionInfo() { + return _dangerousRemoveCollectionInfo.apply(this, arguments); + } + + return dangerousRemoveCollectionInfo; + }() /** * This is the main handle-point for all change events * ChangeEvents created by this instance go: @@ -128,8 +140,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.$emit = function $emit(changeEvent) { - if (!changeEvent) return; // emit into own stream - + // emit into own stream this.subject.next(changeEvent); // write to socket if event was created by this instance if (changeEvent.databaseToken === this.token) { @@ -137,77 +148,113 @@ var RxDatabaseBase = /*#__PURE__*/function () { } } /** - * removes the collection-doc from this._collectionsPouch + * removes the collection-doc from the internalStore */ ; - _proto.removeCollectionDoc = function removeCollectionDoc(name, schema) { - var _this2 = this; + _proto.removeCollectionDoc = + /*#__PURE__*/ + function () { + var _removeCollectionDoc = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(name, schema) { + var _this = this; + + var docId, doc, writeDoc; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + docId = _collectionNamePrimary(name, schema); + _context2.next = 3; + return (0, _rxStorageHelper.getSingleDocument)(this.internalStore, docId); - var docId = _collectionNamePrimary(name, schema); + case 3: + doc = _context2.sent; - return this.internalStore.get(docId).then(function (doc) { - return _this2.lockedRun(function () { - return _this2.internalStore.remove(doc); - }); - }); - } + if (doc) { + _context2.next = 6; + break; + } + + throw (0, _rxError.newRxError)('SNH'); + + case 6: + writeDoc = (0, _util.flatClone)(doc); + writeDoc._deleted = true; + _context2.next = 10; + return this.lockedRun(function () { + return _this.internalStore.bulkWrite([{ + document: writeDoc, + previous: doc + }]); + }); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function removeCollectionDoc(_x, _x2) { + return _removeCollectionDoc.apply(this, arguments); + } + + return removeCollectionDoc; + }() /** * creates multiple RxCollections at once * to be much faster by saving db txs and doing stuff in bulk-operations * This function is not called often, but mostly in the critical path at the initial page load - * So it must be as fast as possible + * So it must be as fast as possible. */ ; _proto.addCollections = /*#__PURE__*/ function () { - var _addCollections = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(collectionCreators) { - var _this3 = this; + var _addCollections = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collectionCreators) { + var _this2 = this; - var pouch, result, internalDocByCollectionName, schemaHashByName, collections, bulkPutDocs, ret; - return _regenerator["default"].wrap(function _callee$(_context) { + var collectionDocs, internalDocByCollectionName, schemaHashByName, collections, bulkPutDocs, ret; + return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { - switch (_context.prev = _context.next) { + switch (_context3.prev = _context3.next) { case 0: - pouch = this.internalStore; // get local management docs in bulk request - - _context.next = 3; - return pouch.allDocs({ - include_docs: true, - keys: Object.keys(collectionCreators).map(function (name) { - return _collectionNamePrimary(name, collectionCreators[name].schema); - }) - }); - - case 3: - result = _context.sent; + _context3.next = 2; + return this.internalStore.findDocumentsById(Object.keys(collectionCreators).map(function (name) { + var schema = collectionCreators[name].schema; + return _collectionNamePrimary(name, schema); + }), false); + + case 2: + collectionDocs = _context3.sent; internalDocByCollectionName = {}; - result.rows.forEach(function (row) { - if (!row.error) { - internalDocByCollectionName[row.key] = row.doc; - } + Array.from(collectionDocs.entries()).forEach(function (_ref) { + var key = _ref[0], + doc = _ref[1]; + internalDocByCollectionName[key] = doc; }); schemaHashByName = {}; - _context.next = 9; - return Promise.all(Object.entries(collectionCreators).map(function (_ref) { - var name = _ref[0], - args = _ref[1]; + _context3.next = 8; + return Promise.all(Object.entries(collectionCreators).map(function (_ref2) { + var name = _ref2[0], + args = _ref2[1]; + var useName = name; - var internalDoc = internalDocByCollectionName[_collectionNamePrimary(name, collectionCreators[name].schema)]; + var internalDoc = internalDocByCollectionName[_collectionNamePrimary(name, collectionCreators[useName].schema)]; var useArgs = (0, _util.flatClone)(args); - useArgs.name = name; + useArgs.name = useName; var schema = (0, _rxSchema.createRxSchema)(args.schema); - schemaHashByName[name] = schema.hash; + schemaHashByName[useName] = schema.hash; useArgs.schema = schema; - useArgs.database = _this3; // TODO check if already exists and schema hash has changed + useArgs.database = _this2; // TODO check if already exists and schema hash has changed // collection already exists // TODO check if already exists and schema hash has changed // collection already exists - if (_this3.collections[name]) { + if (_this2.collections[name]) { throw (0, _rxError.newRxError)('DB3', { name: name }); @@ -215,32 +262,32 @@ var RxDatabaseBase = /*#__PURE__*/function () { // collection already exists but has different schema - if (internalDoc && internalDoc.schemaHash !== schemaHashByName[name]) { + if (internalDoc && internalDoc.schemaHash !== schemaHashByName[useName]) { throw (0, _rxError.newRxError)('DB6', { name: name, previousSchemaHash: internalDoc.schemaHash, - schemaHash: schemaHashByName[name] + schemaHash: schemaHashByName[useName] }); } // run hooks // run hooks var hookData = (0, _util.flatClone)(args); - hookData.database = _this3; + hookData.database = _this2; hookData.name = name; (0, _hooks.runPluginHooks)('preCreateRxCollection', hookData); - return (0, _rxCollection.create)(useArgs, !!internalDoc); + return (0, _rxCollection.createRxCollection)(useArgs, !!internalDoc); })); - case 9: - collections = _context.sent; + case 8: + collections = _context3.sent; bulkPutDocs = []; ret = {}; collections.forEach(function (collection) { var name = collection.name; ret[name] = collection; - if (collection.schema.crypt && !_this3.password) { + if (collection.schema.crypt && !_this2.password) { throw (0, _rxError.newRxError)('DB7', { name: name }); @@ -249,90 +296,81 @@ var RxDatabaseBase = /*#__PURE__*/function () { if (!internalDocByCollectionName[name]) { bulkPutDocs.push({ - _id: _collectionNamePrimary(name, collectionCreators[name].schema), - schemaHash: schemaHashByName[name], - schema: collection.schema.normalized, - version: collection.schema.version + document: { + collectionName: _collectionNamePrimary(name, collectionCreators[name].schema), + schemaHash: schemaHashByName[name], + schema: collection.schema.normalized, + version: collection.schema.version, + _attachments: {} + } }); } // set as getter to the database - _this3.collections[name] = collection; + _this2.collections[name] = collection; - if (!_this3[name]) { - Object.defineProperty(_this3, name, { + if (!_this2[name]) { + Object.defineProperty(_this2, name, { get: function get() { - return _this3.collections[name]; + return _this2.collections[name]; } }); } }); // make a single call to the pouchdb instance if (!(bulkPutDocs.length > 0)) { - _context.next = 16; + _context3.next = 15; break; } - _context.next = 16; - return pouch.bulkDocs({ - docs: bulkPutDocs - }); + _context3.next = 15; + return this.internalStore.bulkWrite(bulkPutDocs); - case 16: - return _context.abrupt("return", ret); + case 15: + return _context3.abrupt("return", ret); - case 17: + case 16: case "end": - return _context.stop(); + return _context3.stop(); } } - }, _callee, this); + }, _callee3, this); })); - function addCollections(_x) { + function addCollections(_x3) { return _addCollections.apply(this, arguments); } return addCollections; }() - /** - * create or fetch a collection - * @deprecated use addCollections() instead, it is faster and better typed - */ - ; - - _proto.collection = function collection(args) { - var _this$addCollections; - - if (typeof args === 'string') { - return Promise.resolve(this.collections[args]); - } // collection() is deprecated, call new bulk-creation method - - - return this.addCollections((_this$addCollections = {}, _this$addCollections[args.name] = args, _this$addCollections)).then(function (colObject) { - return colObject[args.name]; - }); - } /** * delete all data of the collection and its previous versions */ ; _proto.removeCollection = function removeCollection(collectionName) { - var _this4 = this; + var _this3 = this; + + if (this.collections[collectionName]) { + this.collections[collectionName].destroy(); + } // remove schemas from internal db - if (this.collections[collectionName]) this.collections[collectionName].destroy(); // remove schemas from internal db return _removeAllOfCollection(this, collectionName) // get all relevant pouchdb-instances .then(function (knownVersions) { - return knownVersions.map(function (v) { - return _this4._spawnPouchDB(collectionName, v); - }); + return Promise.all(knownVersions.map(function (v) { + return _this3.storage.createStorageInstance({ + databaseName: _this3.name, + collectionName: collectionName, + schema: (0, _rxSchemaHelper.getPseudoSchemaForVersion)(v, 'collectionName'), + options: _this3.instanceCreationOptions + }); + })); }) // remove documents - .then(function (pouches) { - return Promise.all(pouches.map(function (pouch) { - return _this4.lockedRun(function () { - return pouch.destroy(); + .then(function (storageInstance) { + return Promise.all(storageInstance.map(function (instance) { + return _this3.lockedRun(function () { + return instance.remove(); }); })); }).then(function () {}); @@ -356,7 +394,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { */ ; - _proto.dump = function dump() { + _proto.exportJSON = function exportJSON() { var _decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var _collections = arguments.length > 1 ? arguments[1] : undefined; @@ -365,13 +403,13 @@ var RxDatabaseBase = /*#__PURE__*/function () { } /** * Import the parsed JSON export into the collection. - * @param _exportedJSON The previously exported data from the `.dump()` method. + * @param _exportedJSON The previously exported data from the `.exportJSON()` method. * @note When an interface is loaded in this collection all base properties of the type are typed as `any` * since data could be encrypted. */ ; - _proto.importDump = function importDump(_exportedJSON) { + _proto.importJSON = function importJSON(_exportedJSON) { throw (0, _util.pluginMissing)('json-dump'); } /** @@ -412,7 +450,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.destroy = function destroy() { - var _this5 = this; + var _this4 = this; if (this.destroyed) return Promise.resolve(false); (0, _hooks.runPluginHooks)('preDestroyRxDatabase', this); @@ -426,17 +464,20 @@ var RxDatabaseBase = /*#__PURE__*/function () { return this.requestIdlePromise() // destroy all collections .then(function () { - return Promise.all(Object.keys(_this5.collections).map(function (key) { - return _this5.collections[key]; + return Promise.all(Object.keys(_this4.collections).map(function (key) { + return _this4.collections[key]; }).map(function (col) { return col.destroy(); })); + }) // destroy internal storage instances + .then(function () { + return _this4.internalStore.close ? _this4.internalStore.close() : null; }) // close broadcastChannel if exists .then(function () { - return _this5.broadcastChannel ? _this5.broadcastChannel.close() : Promise.resolve(); + return _this4.broadcastChannel ? _this4.broadcastChannel.close() : Promise.resolve(); }) // remove combination from USED_COMBINATIONS-map .then(function () { - return _removeUsedCombination(_this5.name, _this5.adapter); + return USED_DATABASE_NAMES["delete"](_this4.name); }).then(function () { return true; }); @@ -447,10 +488,10 @@ var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.remove = function remove() { - var _this6 = this; + var _this5 = this; return this.destroy().then(function () { - return removeRxDatabase(_this6.name, _this6.adapter); + return removeRxDatabase(_this5.name, _this5.storage); }); }; @@ -470,27 +511,16 @@ var RxDatabaseBase = /*#__PURE__*/function () { exports.RxDatabaseBase = RxDatabaseBase; -function _isNameAdapterUsed(name, adapter) { - if (!USED_COMBINATIONS[name]) return false; - var used = false; - USED_COMBINATIONS[name].forEach(function (ad) { - if (ad === adapter) used = true; - }); - - if (used) { +function throwIfDatabaseNameUsed(name) { + if (!USED_DATABASE_NAMES.has(name)) { + return; + } else { throw (0, _rxError.newRxError)('DB8', { name: name, - adapter: adapter, link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate' }); } } - -function _removeUsedCombination(name, adapter) { - if (!USED_COMBINATIONS[name]) return; - var index = USED_COMBINATIONS[name].indexOf(adapter); - USED_COMBINATIONS[name].splice(index, 1); -} /** * to not confuse multiInstance-messages with other databases that have the same * name and adapter, but do not share state with this one (for example in-memory-instances), @@ -498,30 +528,67 @@ function _removeUsedCombination(name, adapter) { */ -function _ensureStorageTokenExists(rxDatabase) { - return rxDatabase.internalStore.get(_util.LOCAL_PREFIX + 'storageToken')["catch"](function () { - // no doc exists -> insert - return rxDatabase.internalStore.put({ - _id: _util.LOCAL_PREFIX + 'storageToken', - value: (0, _randomToken["default"])(10) - })["catch"](function () {}).then(function () { - return (0, _util.promiseWait)(0); - }); - }).then(function () { - return rxDatabase.internalStore.get(_util.LOCAL_PREFIX + 'storageToken'); - }).then(function (storageTokenDoc2) { - return storageTokenDoc2.value; - }); +function _ensureStorageTokenExists(_x4) { + return _ensureStorageTokenExists2.apply(this, arguments); } /** * writes the changeEvent to the broadcastChannel */ +function _ensureStorageTokenExists2() { + _ensureStorageTokenExists2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(rxDatabase) { + var storageTokenDocumentId, storageTokenDoc, storageToken; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + storageTokenDocumentId = 'storageToken'; + _context4.next = 3; + return (0, _rxStorageHelper.findLocalDocument)(rxDatabase.localDocumentsStore, storageTokenDocumentId); + + case 3: + storageTokenDoc = _context4.sent; + + if (storageTokenDoc) { + _context4.next = 11; + break; + } + + storageToken = (0, _randomToken["default"])(10); + _context4.next = 8; + return rxDatabase.localDocumentsStore.bulkWrite([{ + document: { + _id: storageTokenDocumentId, + value: storageToken, + _attachments: {} + } + }]); + + case 8: + return _context4.abrupt("return", storageToken); + + case 11: + return _context4.abrupt("return", storageTokenDoc.value); + + case 12: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + return _ensureStorageTokenExists2.apply(this, arguments); +} + function writeToSocket(rxDatabase, changeEvent) { - if (rxDatabase.multiInstance && !changeEvent.isIntern() && rxDatabase.broadcastChannel) { + if (rxDatabase.destroyed) { + return Promise.resolve(false); + } + + if (rxDatabase.multiInstance && !(0, _rxChangeEvent.isRxChangeEventIntern)(changeEvent) && rxDatabase.broadcastChannel) { var sendOverChannel = { - cE: changeEvent.toJSON(), + cE: changeEvent, storageToken: rxDatabase.storageToken }; return rxDatabase.broadcastChannel.postMessage(sendOverChannel).then(function () { @@ -544,27 +611,51 @@ function _collectionNamePrimary(name, schema) { */ -function _removeAllOfCollection(rxDatabase, collectionName) { - return rxDatabase.lockedRun(function () { - return (0, _rxDatabaseInternalStore.getAllDocuments)(rxDatabase.internalStore); - }).then(function (data) { - var relevantDocs = data.map(function (row) { - return row.doc; - }).filter(function (doc) { - var name = doc._id.split('-')[0]; +function _removeAllOfCollection(_x5, _x6) { + return _removeAllOfCollection2.apply(this, arguments); +} - return name === collectionName; - }); - return Promise.all(relevantDocs.map(function (doc) { - return rxDatabase.lockedRun(function () { - return rxDatabase.internalStore.remove(doc); - }); - })).then(function () { - return relevantDocs.map(function (doc) { - return doc.version; - }); - }); - }); +function _removeAllOfCollection2() { + _removeAllOfCollection2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(rxDatabase, collectionName) { + var docs, relevantDocs; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return rxDatabase.lockedRun(function () { + return (0, _rxStorageHelper.getAllDocuments)(rxDatabase.internalStore); + }); + + case 2: + docs = _context5.sent; + relevantDocs = docs.filter(function (doc) { + var name = doc.collectionName.split('-')[0]; + return name === collectionName; + }); + return _context5.abrupt("return", Promise.all(relevantDocs.map(function (doc) { + var writeDoc = (0, _util.flatClone)(doc); + writeDoc._deleted = true; + return rxDatabase.lockedRun(function () { + return (0, _rxStorageHelper.writeSingle)(rxDatabase.internalStore, { + previous: doc, + document: writeDoc + }); + }); + })).then(function () { + return relevantDocs.map(function (doc) { + return doc.version; + }); + })); + + case 5: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + return _removeAllOfCollection2.apply(this, arguments); } function _prepareBroadcastChannel(rxDatabase) { @@ -577,74 +668,134 @@ function _prepareBroadcastChannel(rxDatabase) { if (msg.cE.databaseToken === rxDatabase.token) return; // same db - var changeEvent = new _rxChangeEvent.RxChangeEvent(msg.cE.operation, msg.cE.documentId, msg.cE.documentData, msg.cE.databaseToken, msg.cE.collectionName, msg.cE.isLocal, msg.cE.startTime, msg.cE.endTime, msg.cE.previousData); + var changeEvent = msg.cE; rxDatabase.broadcastChannel$.next(changeEvent); - }; // TODO only subscribe when something is listening to the event-chain - + }; rxDatabase._subs.push(rxDatabase.broadcastChannel$.subscribe(function (cE) { rxDatabase.$emit(cE); })); } +/** + * Creates the storage instances that are used internally in the database + * to store schemas and other configuration stuff. + */ + + +function createRxDatabaseStorageInstances(_x7, _x8, _x9) { + return _createRxDatabaseStorageInstances.apply(this, arguments); +} /** * do the async things for this database */ -function prepare(rxDatabase) { - return rxDatabase.storage.createInternalStorageInstance(rxDatabase.name).then(function (internalStore) { - rxDatabase.internalStore = internalStore; - return _ensureStorageTokenExists(rxDatabase); - }).then(function (storageToken) { - rxDatabase.storageToken = storageToken; +function _createRxDatabaseStorageInstances() { + _createRxDatabaseStorageInstances = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(storage, databaseName, options) { + var internalStore, localDocumentsStore; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return storage.createStorageInstance({ + databaseName: databaseName, + collectionName: _rxStorageHelper.INTERNAL_STORAGE_NAME, + schema: (0, _rxSchemaHelper.getPseudoSchemaForVersion)(0, 'collectionName'), + options: options + }); + + case 2: + internalStore = _context6.sent; + _context6.next = 5; + return storage.createKeyObjectStorageInstance(databaseName, // TODO having to set an empty string here is ugly. + // we should change the rx-storage interface to account for non-collection storage instances. + '', options); + + case 5: + localDocumentsStore = _context6.sent; + return _context6.abrupt("return", { + internalStore: internalStore, + localDocumentsStore: localDocumentsStore + }); + + case 7: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + return _createRxDatabaseStorageInstances.apply(this, arguments); +} - if (rxDatabase.multiInstance) { - _prepareBroadcastChannel(rxDatabase); - } - }); +function prepare(_x10) { + return _prepare.apply(this, arguments); } -function createRxDatabase(_ref2) { - var name = _ref2.name, - adapter = _ref2.adapter, - password = _ref2.password, - _ref2$multiInstance = _ref2.multiInstance, - multiInstance = _ref2$multiInstance === void 0 ? true : _ref2$multiInstance, - _ref2$eventReduce = _ref2.eventReduce, - eventReduce = _ref2$eventReduce === void 0 ? false : _ref2$eventReduce, - _ref2$ignoreDuplicate = _ref2.ignoreDuplicate, - ignoreDuplicate = _ref2$ignoreDuplicate === void 0 ? false : _ref2$ignoreDuplicate, - _ref2$options = _ref2.options, - options = _ref2$options === void 0 ? {} : _ref2$options, - _ref2$pouchSettings = _ref2.pouchSettings, - pouchSettings = _ref2$pouchSettings === void 0 ? {} : _ref2$pouchSettings; +function _prepare() { + _prepare = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(rxDatabase) { + var storageInstances, localDocsSub; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return createRxDatabaseStorageInstances(rxDatabase.storage, rxDatabase.name, rxDatabase.instanceCreationOptions); + + case 2: + storageInstances = _context7.sent; + rxDatabase.internalStore = storageInstances.internalStore; + rxDatabase.localDocumentsStore = storageInstances.localDocumentsStore; + localDocsSub = rxDatabase.localDocumentsStore.changeStream().subscribe(function (rxStorageChangeEvent) { + rxDatabase.$emit((0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(true, rxStorageChangeEvent, rxDatabase)); + }); + + rxDatabase._subs.push(localDocsSub); + + _context7.next = 9; + return _ensureStorageTokenExists(rxDatabase); + + case 9: + rxDatabase.storageToken = _context7.sent; + + if (rxDatabase.multiInstance) { + _prepareBroadcastChannel(rxDatabase); + } + + case 11: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + return _prepare.apply(this, arguments); +} + +function createRxDatabase(_ref3) { + var storage = _ref3.storage, + instanceCreationOptions = _ref3.instanceCreationOptions, + name = _ref3.name, + password = _ref3.password, + _ref3$multiInstance = _ref3.multiInstance, + multiInstance = _ref3$multiInstance === void 0 ? true : _ref3$multiInstance, + _ref3$eventReduce = _ref3.eventReduce, + eventReduce = _ref3$eventReduce === void 0 ? false : _ref3$eventReduce, + _ref3$ignoreDuplicate = _ref3.ignoreDuplicate, + ignoreDuplicate = _ref3$ignoreDuplicate === void 0 ? false : _ref3$ignoreDuplicate, + _ref3$options = _ref3.options, + options = _ref3$options === void 0 ? {} : _ref3$options; (0, _hooks.runPluginHooks)('preCreateRxDatabase', { + storage: storage, + instanceCreationOptions: instanceCreationOptions, name: name, - adapter: adapter, password: password, multiInstance: multiInstance, eventReduce: eventReduce, ignoreDuplicate: ignoreDuplicate, - options: options, - pouchSettings: pouchSettings - }); // check if pouchdb-adapter - - if (typeof adapter === 'string') { - // TODO make a function hasAdapter() - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters[adapter]) { - throw (0, _rxError.newRxError)('DB9', { - adapter: adapter - }); - } - } else { - (0, _pouchDb.isLevelDown)(adapter); - - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.leveldb) { - throw (0, _rxError.newRxError)('DB10', { - adapter: adapter - }); - } - } + options: options + }); if (password) { _overwritable.overwritable.validatePassword(password); @@ -652,16 +803,11 @@ function createRxDatabase(_ref2) { if (!ignoreDuplicate) { - _isNameAdapterUsed(name, adapter); - } // add to used_map - - - if (!USED_COMBINATIONS[name]) { - USED_COMBINATIONS[name] = []; + throwIfDatabaseNameUsed(name); } - USED_COMBINATIONS[name].push(adapter); - var rxDatabase = new RxDatabaseBase(name, adapter, password, multiInstance, eventReduce, options, pouchSettings); + USED_DATABASE_NAMES.add(name); + var rxDatabase = new RxDatabaseBase(name, storage, instanceCreationOptions, password, multiInstance, eventReduce, options); return prepare(rxDatabase).then(function () { return (0, _hooks.runAsyncPluginHooks)('createRxDatabase', rxDatabase); }).then(function () { @@ -673,36 +819,79 @@ function createRxDatabase(_ref2) { */ -function removeRxDatabase(databaseName, adapter) { - var storage = (0, _rxStoragePouchdb.getRxStoragePouchDb)(adapter); - return storage.createInternalStorageInstance(databaseName).then(function (internalStore) { - return (0, _rxDatabaseInternalStore.getAllDocuments)(internalStore).then(function (docs) { - // remove collections storages - return Promise.all(docs.map(function (colDoc) { - return colDoc.id; - }).map(function (id) { - var split = id.split('-'); - var name = split[0]; - var version = parseInt(split[1], 10); - var instance = storage.createStorageInstance(databaseName, name, version); - return instance.destroy(); - })); - }) // remove internals - .then(function () { - return (0, _rxDatabaseInternalStore.deleteStorageInstance)(internalStore); - }); - }); +function removeRxDatabase(_x11, _x12) { + return _removeRxDatabase.apply(this, arguments); } -/** - * check if the given adapter can be used - */ +function _removeRxDatabase() { + _removeRxDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(databaseName, storage) { + var storageInstance, docs; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return createRxDatabaseStorageInstances(storage, databaseName, {}); + + case 2: + storageInstance = _context9.sent; + _context9.next = 5; + return (0, _rxStorageHelper.getAllDocuments)(storageInstance.internalStore); + + case 5: + docs = _context9.sent; + _context9.next = 8; + return Promise.all(docs.map(function (colDoc) { + return colDoc.collectionName; + }).map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(id) { + var split, name, version, instance; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + split = id.split('-'); + name = split[0]; + version = parseInt(split[1], 10); + _context8.next = 5; + return storage.createStorageInstance({ + databaseName: databaseName, + collectionName: name, + schema: (0, _rxSchemaHelper.getPseudoSchemaForVersion)(version, 'collectionName'), + options: {} + }); + + case 5: + instance = _context8.sent; + return _context8.abrupt("return", instance.remove()); + + case 7: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + + return function (_x13) { + return _ref4.apply(this, arguments); + }; + }())); -function checkAdapter(adapter) { - return _overwritable.overwritable.checkAdapter(adapter); + case 8: + return _context9.abrupt("return", Promise.all([storageInstance.internalStore.remove(), storageInstance.localDocumentsStore.remove()])); + + case 9: + case "end": + return _context9.stop(); + } + } + }, _callee9); + })); + return _removeRxDatabase.apply(this, arguments); } -function isInstanceOf(obj) { +function isRxDatabase(obj) { return obj instanceof RxDatabaseBase; } @@ -710,14 +899,4 @@ function dbCount() { return DB_COUNT; } -var _default = { - createRxDatabase: createRxDatabase, - removeRxDatabase: removeRxDatabase, - checkAdapter: checkAdapter, - isInstanceOf: isInstanceOf, - RxDatabaseBase: RxDatabaseBase, - dbCount: dbCount -}; -exports["default"] = _default; - //# sourceMappingURL=rx-database.js.map \ No newline at end of file diff --git a/dist/lib/rx-document-prototype-merge.js b/dist/lib/rx-document-prototype-merge.js index 8f54653f613..f0899915824 100644 --- a/dist/lib/rx-document-prototype-merge.js +++ b/dist/lib/rx-document-prototype-merge.js @@ -81,15 +81,17 @@ function getRxDocumentConstructor(rxCollection) { function createRxDocument(rxCollection, docData) { - // return from cache if exsists - var id = docData[rxCollection.schema.primaryPath]; + var primary = docData[rxCollection.schema.primaryPath]; // return from cache if exsists - var cacheDoc = rxCollection._docCache.get(id); + var cacheDoc = rxCollection._docCache.get(primary); + + if (cacheDoc) { + return cacheDoc; + } - if (cacheDoc) return cacheDoc; var doc = (0, _rxDocument.createWithConstructor)(getRxDocumentConstructor(rxCollection), rxCollection, docData); - rxCollection._docCache.set(id, doc); + rxCollection._docCache.set(primary, doc); rxCollection._runHooksSync('post', 'create', docData, doc); diff --git a/dist/lib/rx-document.js b/dist/lib/rx-document.js index 3c51c0d82dc..e0161d8e7d3 100644 --- a/dist/lib/rx-document.js +++ b/dist/lib/rx-document.js @@ -8,7 +8,7 @@ Object.defineProperty(exports, "__esModule", { exports.createRxDocumentConstructor = createRxDocumentConstructor; exports.defineGetterSetter = defineGetterSetter; exports.createWithConstructor = createWithConstructor; -exports.isInstanceOf = isInstanceOf; +exports.isRxDocument = isRxDocument; exports.basePrototype = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -23,12 +23,18 @@ var _operators = require("rxjs/operators"); var _util = require("./util"); -var _rxChangeEvent = require("./rx-change-event"); - var _rxError = require("./rx-error"); var _hooks = require("./hooks"); +var _rxChangeEvent = require("./rx-change-event"); + +var _rxCollectionHelper = require("./rx-collection-helper"); + +var _overwritable = require("./overwritable"); + +var _rxSchemaHelper = require("./rx-schema-helper"); + var basePrototype = { /** * TODO @@ -87,7 +93,7 @@ var basePrototype = { return undefined; } - return _this._deleted$.asObservable(); + return _this._isDeleted$.asObservable(); }, get deleted() { @@ -97,7 +103,7 @@ var basePrototype = { return undefined; } - return _this._deleted$.getValue(); + return _this._isDeleted$.getValue(); }, /** @@ -110,9 +116,13 @@ var basePrototype = { }, _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) return; // ensure that new _rev is higher then current + if (changeEvent.documentId !== this.primary) { + return; + } // ensure that new _rev is higher then current - var newRevNr = (0, _util.getHeightOfRevision)(changeEvent.documentData._rev); + + var docData = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + var newRevNr = (0, _util.getHeightOfRevision)(docData._rev); var currentRevNr = (0, _util.getHeightOfRevision)(this._data._rev); if (currentRevNr > newRevNr) return; @@ -131,7 +141,7 @@ var basePrototype = { // remove from docCache to assure new upserted RxDocuments will be a new instance this.collection._docCache["delete"](this.primary); - this._deleted$.next(true); + this._isDeleted$.next(true); break; } @@ -162,7 +172,7 @@ var basePrototype = { }); } - var schemaObj = this.collection.schema.getSchemaByObjectPath(path); + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); if (!schemaObj) { throw (0, _rxError.newRxError)('DOC4', { @@ -179,7 +189,7 @@ var basePrototype = { * populate the given path */ populate: function populate(path) { - var schemaObj = this.collection.schema.getSchemaByObjectPath(path); + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); var value = this.get(path); if (!value) { @@ -225,24 +235,33 @@ var basePrototype = { get: function get(objPath) { if (!this._data) return undefined; - var valueObj = _objectPath["default"].get(this._data, objPath); + var valueObj = _objectPath["default"].get(this._data, objPath); // direct return if array or non-object + + + if (typeof valueObj !== 'object' || Array.isArray(valueObj)) { + return _overwritable.overwritable.deepFreezeWhenDevMode(valueObj); + } + /** + * TODO find a way to deep-freeze together with defineGetterSetter + * so we do not have to do a deep clone here. + */ - valueObj = (0, _util.clone)(valueObj); // direct return if array or non-object - if (typeof valueObj !== 'object' || Array.isArray(valueObj)) return valueObj; + valueObj = (0, _util.clone)(valueObj); defineGetterSetter(this.collection.schema, valueObj, objPath, this); return valueObj; }, toJSON: function toJSON() { var withRevAndAttachments = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var data = (0, _util.clone)(this._data); if (!withRevAndAttachments) { + var data = (0, _util.flatClone)(this._data); delete data._rev; delete data._attachments; + return _overwritable.overwritable.deepFreezeWhenDevMode(data); + } else { + return _overwritable.overwritable.deepFreezeWhenDevMode(this._data); } - - return data; }, /** @@ -400,60 +419,59 @@ var basePrototype = { }); }, - /** - * @deprecated use atomicPatch instead because it is better typed - * and does not allow any keys and values - */ - atomicSet: function atomicSet(key, value) { - return this.atomicUpdate(function (docData) { - _objectPath["default"].set(docData, key, value); - - return docData; - }); - }, - /** * saves the new document-data * and handles the events */ - _saveData: function _saveData(newData, oldData) { - var _this3 = this; - - newData = newData; // deleted documents cannot be changed - - if (this._deleted$.getValue()) { - throw (0, _rxError.newRxError)('DOC11', { - id: this.primary, - document: this - }); - } // ensure modifications are ok - - - this.collection.schema.validateChange(oldData, newData); - var startTime; - return this.collection._runHooks('pre', 'save', newData, this).then(function () { - _this3.collection.schema.validate(newData); - - startTime = (0, _util.now)(); - return _this3.collection._pouchPut(newData); - }).then(function (ret) { - var endTime = (0, _util.now)(); - - if (!ret.ok) { - throw (0, _rxError.newRxError)('DOC12', { - data: ret - }); - } - - newData._rev = ret.rev; // emit event - - var changeEvent = (0, _rxChangeEvent.createUpdateEvent)(_this3.collection, newData, oldData, startTime, endTime, _this3); + _saveData: function () { + var _saveData2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(newData, oldData) { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + newData = newData; // deleted documents cannot be changed + + if (!this._isDeleted$.getValue()) { + _context2.next = 3; + break; + } + + throw (0, _rxError.newRxError)('DOC11', { + id: this.primary, + document: this + }); + + case 3: + // ensure modifications are ok + this.collection.schema.validateChange(oldData, newData); + _context2.next = 6; + return this.collection._runHooks('pre', 'save', newData, this); + + case 6: + this.collection.schema.validate(newData); + _context2.next = 9; + return (0, _rxCollectionHelper.writeToStorageInstance)(this.collection, { + previous: oldData, + document: newData + }); + + case 9: + return _context2.abrupt("return", this.collection._runHooks('post', 'save', newData, this)); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); - _this3.$emit(changeEvent); + function _saveData(_x, _x2) { + return _saveData2.apply(this, arguments); + } - return _this3.collection._runHooks('post', 'save', newData, _this3); - }); - }, + return _saveData; + }(), /** * saves the temporary document and makes a non-temporary out of it @@ -461,7 +479,7 @@ var basePrototype = { * @return false if nothing to save */ save: function save() { - var _this4 = this; + var _this3 = this; // .save() cannot be called on non-temporary-documents if (!this._isTemporary) { @@ -472,12 +490,12 @@ var basePrototype = { } return this.collection.insert(this).then(function () { - _this4._isTemporary = false; + _this3._isTemporary = false; - _this4.collection._docCache.set(_this4.primary, _this4); // internal events + _this3.collection._docCache.set(_this3.primary, _this3); // internal events - _this4._dataSync$.next(_this4._data); + _this3._dataSync$.next(_this3._data); return true; }); @@ -489,7 +507,7 @@ var basePrototype = { * instead we keep the values and only set _deleted: true */ remove: function remove() { - var _this5 = this; + var _this4 = this; if (this.deleted) { return Promise.reject((0, _rxError.newRxError)('DOC13', { @@ -498,25 +516,19 @@ var basePrototype = { })); } - var deletedData = (0, _util.clone)(this._data); + var deletedData = (0, _util.flatClone)(this._data); var startTime; return this.collection._runHooks('pre', 'remove', deletedData, this).then(function () { deletedData._deleted = true; startTime = (0, _util.now)(); - /** - * because pouch.remove will also empty the object, - * we set _deleted: true and use pouch.put - */ - - return _this5.collection._pouchPut(deletedData); + return (0, _rxCollectionHelper.writeToStorageInstance)(_this4.collection, { + previous: _this4._data, + document: deletedData + }); }).then(function () { - var endTime = (0, _util.now)(); - - _this5.$emit((0, _rxChangeEvent.createDeleteEvent)(_this5.collection, deletedData, _this5._data, startTime, endTime, _this5)); - - return _this5.collection._runHooks('post', 'remove', deletedData, _this5); + return _this4.collection._runHooks('post', 'remove', deletedData, _this4); }).then(function () { - return _this5; + return _this4; }); }, destroy: function destroy() { @@ -534,7 +546,7 @@ function createRxDocumentConstructor() { this._isTemporary = false; // assume that this is always equal to the doc-data in the database this._dataSync$ = new _rxjs.BehaviorSubject(jsonData); - this._deleted$ = new _rxjs.BehaviorSubject(false); + this._isDeleted$ = new _rxjs.BehaviorSubject(false); this._atomicQueue = Promise.resolve(); /** * because of the prototype-merge, @@ -552,7 +564,7 @@ function defineGetterSetter(schema, valueObj) { var objPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var thisObj = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (valueObj === null) return; - var pathProperties = schema.getSchemaByObjectPath(objPath); + var pathProperties = (0, _rxSchemaHelper.getSchemaByObjectPath)(schema.jsonSchema, objPath); if (typeof pathProperties === 'undefined') return; if (pathProperties.properties) pathProperties = pathProperties.properties; Object.keys(pathProperties).forEach(function (key) { @@ -611,7 +623,7 @@ function createWithConstructor(constructor, collection, jsonData) { return doc; } -function isInstanceOf(obj) { +function isRxDocument(obj) { if (typeof obj === 'undefined') return false; return !!obj.isInstanceOfRxDocument; } diff --git a/dist/lib/rx-query.js b/dist/lib/rx-query.js index de7880c95b7..e37a2b7c870 100644 --- a/dist/lib/rx-query.js +++ b/dist/lib/rx-query.js @@ -19,8 +19,6 @@ var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _pouchdbSelectorCore = require("pouchdb-selector-core"); - var _util = require("./util"); var _rxError = require("./rx-error"); @@ -33,6 +31,8 @@ var _eventReduce = require("./event-reduce"); var _queryCache = require("./query-cache"); +var _rxCollectionHelper = require("./rx-collection-helper"); + var _queryCount = 0; var newQueryID = function newQueryID() { @@ -98,11 +98,11 @@ var RxQueryBase = /*#__PURE__*/function () { switch (this.op) { case 'find': - docsPromise = this.collection._pouchFind(this); + docsPromise = this.collection._queryStorageInstance(this); break; case 'findOne': - docsPromise = this.collection._pouchFind(this, 1); + docsPromise = this.collection._queryStorageInstance(this, 1); break; default: @@ -164,7 +164,7 @@ var RxQueryBase = /*#__PURE__*/function () { }); } /** - * cached call to get the massageSelector + * cached call to get the queryMatcher * @overwrites itself with the actual value */ ; @@ -189,35 +189,23 @@ var RxQueryBase = /*#__PURE__*/function () { } /** * returns the prepared query + * which can be send to the storage instance to query for documents. * @overwrites itself with the actual value + * TODO rename this function, toJSON is missleading + * because we do not return the plain mango query object. */ ; _proto.toJSON = function toJSON() { - var value = this.collection.database.storage.prepareQuery(this.asRxQuery, (0, _util.clone)(this.mangoQuery)); - - this.toJSON = function () { - return value; + var hookInput = { + rxQuery: this, + // can be mutated by the hooks so we have to deep clone first. + mangoQuery: (0, _util.clone)(this.mangoQuery) }; + (0, _hooks.runPluginHooks)('prePrepareQuery', hookInput); + var value = this.collection.storageInstance.prepareQuery(hookInput.mangoQuery); - return value; - } - /** - * returns the key-compressed version of the query - * @overwrites itself with the actual value - */ - ; - - _proto.keyCompress = function keyCompress() { - var value; - - if (!this.collection.schema.doKeyCompression()) { - value = this.toJSON(); - } else { - value = this.collection._keyCompressor.compressQuery(this.toJSON()); - } - - this.keyCompress = function () { + this.toJSON = function () { return value; }; @@ -232,24 +220,11 @@ var RxQueryBase = /*#__PURE__*/function () { _proto.doesDocumentDataMatch = function doesDocumentDataMatch(docData) { // if doc is deleted, it cannot match - if (docData._deleted) return false; - docData = this.collection.schema.swapPrimaryToId(docData); // return matchesSelector(docData, selector); - - /** - * the following is equal to the implementation of pouchdb - * we do not use matchesSelector() directly so we can cache the - * result of massageSelector - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ + if (docData._deleted) { + return false; + } - var selector = this.massageSelector; - var row = { - doc: docData - }; - var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { - selector: selector - }, Object.keys(selector)); - return rowsMatched && rowsMatched.length === 1; + return this.queryMatcher((0, _rxCollectionHelper._handleToStorageInstance)(this.collection, docData)); } /** * deletes all found documents @@ -261,9 +236,14 @@ var RxQueryBase = /*#__PURE__*/function () { var ret; return this.exec().then(function (docs) { ret = docs; - if (Array.isArray(docs)) return Promise.all(docs.map(function (doc) { - return doc.remove(); - }));else return docs.remove(); + + if (Array.isArray(docs)) { + return Promise.all(docs.map(function (doc) { + return doc.remove(); + })); + } else { + return docs.remove(); + } }).then(function () { return ret; }); @@ -311,19 +291,25 @@ var RxQueryBase = /*#__PURE__*/function () { */ var results$ = this._resultsDocs$.pipe((0, _operators.mergeMap)(function (docs) { return _ensureEqual(_this3).then(function (hasChanged) { - if (hasChanged) return false; // wait for next emit - else return docs; + if (hasChanged) { + // wait for next emit + return false; + } else { + return docs; + } }); }), (0, _operators.filter)(function (docs) { return !!docs; }), // not if previous returned false (0, _operators.map)(function (docs) { - // findOne()-queries emit document or null if (_this3.op === 'findOne') { + // findOne()-queries emit document or null var doc = docs.length === 0 ? null : docs[0]; return doc; - } else return docs; // find()-queries emit RxDocument[] - + } else { + // find()-queries emit RxDocument[] + return docs; + } }), (0, _operators.map)(function (docs) { // copy the array so it wont matter if the user modifies it var ret = Array.isArray(docs) ? docs.slice() : docs; @@ -349,9 +335,9 @@ var RxQueryBase = /*#__PURE__*/function () { } // stores the changeEvent-Number of the last handled change-event }, { - key: "massageSelector", + key: "queryMatcher", get: function get() { - return (0, _util.overwriteGetterForCaching)(this, 'massageSelector', (0, _pouchdbSelectorCore.massageSelector)(this.mangoQuery.selector)); + return (0, _util.overwriteGetterForCaching)(this, 'queryMatcher', this.collection.storageInstance.getQueryMatcher(this.toJSON())); } }, { key: "asRxQuery", @@ -426,15 +412,11 @@ function _isResultsInSync(rxQuery) { function _ensureEqual(rxQuery) { rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue.then(function () { - return new Promise(function (res) { - return setTimeout(res, 0); - }); + return (0, _util.promiseWait)(0); }).then(function () { return __ensureEqual(rxQuery); }).then(function (ret) { - return new Promise(function (res) { - return setTimeout(res, 0); - }).then(function () { + return (0, _util.promiseWait)(0).then(function () { return ret; }); }); diff --git a/dist/lib/rx-schema-helper.js b/dist/lib/rx-schema-helper.js new file mode 100644 index 00000000000..7c2186715ad --- /dev/null +++ b/dist/lib/rx-schema-helper.js @@ -0,0 +1,48 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getPseudoSchemaForVersion = getPseudoSchemaForVersion; +exports.getSchemaByObjectPath = getSchemaByObjectPath; + +var _objectPath = _interopRequireDefault(require("object-path")); + +var _util = require("./util"); + +/** + * Helper function to create a valid RxJsonSchema + * with a given version. + */ +function getPseudoSchemaForVersion(version, primaryKey) { + var _properties; + + var pseudoSchema = { + version: version, + type: 'object', + primaryKey: primaryKey, + properties: (_properties = {}, _properties[primaryKey] = { + type: 'string' + }, _properties) + }; + return pseudoSchema; +} +/** + * Returns the sub-schema for a given path + */ + + +function getSchemaByObjectPath(rxJsonSchema, path) { + var usePath = path; + usePath = usePath.replace(/\./g, '.properties.'); + usePath = 'properties.' + usePath; + usePath = (0, _util.trimDots)(usePath); + + var ret = _objectPath["default"].get(rxJsonSchema, usePath); + + return ret; +} + +//# sourceMappingURL=rx-schema-helper.js.map \ No newline at end of file diff --git a/dist/lib/rx-schema.js b/dist/lib/rx-schema.js index 377b272920f..85a3e727c3c 100644 --- a/dist/lib/rx-schema.js +++ b/dist/lib/rx-schema.js @@ -6,18 +6,16 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.getIndexes = getIndexes; -exports.getPrimary = getPrimary; exports.getPreviousVersions = getPreviousVersions; exports.getFinalFields = getFinalFields; exports.normalize = normalize; +exports.fillWithDefaultSettings = fillWithDefaultSettings; exports.createRxSchema = createRxSchema; exports.isInstanceOf = isInstanceOf; -exports.fillWithDefaultSettings = exports.RxSchema = void 0; +exports.RxSchema = void 0; var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); -var _objectPath = _interopRequireDefault(require("object-path")); - var _deepEqual = _interopRequireDefault(require("deep-equal")); var _util = require("./util"); @@ -33,7 +31,7 @@ var RxSchema = /*#__PURE__*/function () { this.jsonSchema = jsonSchema; this.indexes = getIndexes(this.jsonSchema); // primary is always required - this.primaryPath = getPrimary(this.jsonSchema); + this.primaryPath = this.jsonSchema.primaryKey; if (this.primaryPath) { this.jsonSchema.required.push(this.primaryPath); @@ -44,28 +42,10 @@ var RxSchema = /*#__PURE__*/function () { this.jsonSchema.required = this.jsonSchema.required.concat(this.finalFields).filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos; }); // unique; - // add primary to schema if not there (if _id) - - if (!this.jsonSchema.properties[this.primaryPath]) { - this.jsonSchema.properties[this.primaryPath] = { - type: 'string', - minLength: 1 - }; - } } var _proto = RxSchema.prototype; - _proto.getSchemaByObjectPath = function getSchemaByObjectPath(path) { - var usePath = path; - usePath = usePath.replace(/\./g, '.properties.'); - usePath = 'properties.' + usePath; - usePath = (0, _util.trimDots)(usePath); - - var ret = _objectPath["default"].get(this.jsonSchema, usePath); - - return ret; - } /** * checks if a given change on a document is allowed * Ensures that: @@ -73,8 +53,6 @@ var RxSchema = /*#__PURE__*/function () { * - final fields are not modified * @throws {Error} if not valid */ - ; - _proto.validateChange = function validateChange(dataBefore, dataAfter) { this.finalFields.forEach(function (fieldName) { if (!(0, _deepEqual["default"])(dataBefore[fieldName], dataAfter[fieldName])) { @@ -114,39 +92,6 @@ var RxSchema = /*#__PURE__*/function () { return obj[k] = v; }); return obj; - }; - - _proto.swapIdToPrimary = function swapIdToPrimary(obj) { - if (this.primaryPath === '_id' || obj[this.primaryPath]) { - return obj; - } - - obj[this.primaryPath] = obj._id; - delete obj._id; - return obj; - }; - - _proto.swapPrimaryToId = function swapPrimaryToId(obj) { - var _this = this; - - if (this.primaryPath === '_id') { - return obj; - } - - var ret = {}; - Object.entries(obj).forEach(function (entry) { - var newKey = entry[0] === _this.primaryPath ? '_id' : entry[0]; - ret[newKey] = entry[1]; - }); - return ret; - } - /** - * returns true if key-compression should be done - */ - ; - - _proto.doKeyCompression = function doKeyCompression() { - return this.jsonSchema.keyCompression; } /** * creates the schema-based document-prototype, @@ -234,18 +179,6 @@ function getIndexes(jsonSchema) { return Array.isArray(index) ? index : [index]; }); } -/** - * returns the primary path of a jsonschema - * @return primaryPath which is _id if none defined - */ - - -function getPrimary(jsonSchema) { - var ret = Object.keys(jsonSchema.properties).filter(function (key) { - return jsonSchema.properties[key].primary; - }).shift(); - if (!ret) return '_id';else return ret; -} /** * array with previous version-numbers */ @@ -269,7 +202,7 @@ function getFinalFields(jsonSchema) { return jsonSchema.properties[key]["final"]; }); // primary is also final - ret.push(getPrimary(jsonSchema)); + ret.push(jsonSchema.primaryKey); return ret; } /** @@ -285,6 +218,12 @@ function normalize(jsonSchema) { normalizedSchema.indexes = Array.from(jsonSchema.indexes); // indexes should remain unsorted } + if (!jsonSchema.required) { + jsonSchema.required = [jsonSchema.primaryKey]; + } else if (!jsonSchema.required.includes(jsonSchema.primaryKey)) { + jsonSchema.required.push(jsonSchema.primaryKey); + } + return normalizedSchema; } /** @@ -293,18 +232,26 @@ function normalize(jsonSchema) { */ -var fillWithDefaultSettings = function fillWithDefaultSettings(schemaObj) { +function fillWithDefaultSettings(schemaObj) { schemaObj = (0, _util.clone)(schemaObj); // additionalProperties is always false schemaObj.additionalProperties = false; // fill with key-compression-state () - if (!schemaObj.hasOwnProperty('keyCompression')) schemaObj.keyCompression = false; // indexes must be array + if (!schemaObj.hasOwnProperty('keyCompression')) { + schemaObj.keyCompression = false; + } // indexes must be array + schemaObj.indexes = schemaObj.indexes || []; // required must be array schemaObj.required = schemaObj.required || []; // encrypted must be array - schemaObj.encrypted = schemaObj.encrypted || []; // add _rev + schemaObj.encrypted = schemaObj.encrypted || []; + /** + * TODO we should not need to added the internal fields to the schema. + * Better remove the before validation. + */ + // add _rev schemaObj.properties._rev = { type: 'string', @@ -313,13 +260,15 @@ var fillWithDefaultSettings = function fillWithDefaultSettings(schemaObj) { schemaObj.properties._attachments = { type: 'object' + }; // add deleted flag + + schemaObj.properties._deleted = { + type: 'boolean' }; // version is 0 by default schemaObj.version = schemaObj.version || 0; return schemaObj; -}; - -exports.fillWithDefaultSettings = fillWithDefaultSettings; +} function createRxSchema(jsonSchema) { var runPreCreateHooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; diff --git a/dist/lib/rx-storage-helper.js b/dist/lib/rx-storage-helper.js new file mode 100644 index 00000000000..887760035d7 --- /dev/null +++ b/dist/lib/rx-storage-helper.js @@ -0,0 +1,394 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getAllDocuments = getAllDocuments; +exports.getSingleDocument = getSingleDocument; +exports.countAllUndeleted = countAllUndeleted; +exports.getBatch = getBatch; +exports.writeSingle = writeSingle; +exports.writeSingleLocal = writeSingleLocal; +exports.findLocalDocument = findLocalDocument; +exports.getNewestSequence = getNewestSequence; +exports.storageChangeEventToRxChangeEvent = storageChangeEventToRxChangeEvent; +exports.INTERNAL_STORAGE_NAME = void 0; + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _hooks = require("./hooks"); + +var _overwritable = require("./overwritable"); + +var _rxError = require("./rx-error"); + +/** + * Helper functions for accessing the RxStorage instances. + */ +var INTERNAL_STORAGE_NAME = '_rxdb_internal'; +/** + * returns all NON-LOCAL documents + * TODO this is pouchdb specific should not be needed + */ + +exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; + +function getAllDocuments(_x) { + return _getAllDocuments.apply(this, arguments); +} + +function _getAllDocuments() { + _getAllDocuments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(storageInstance) { + var getAllQueryPrepared, queryResult, allDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + getAllQueryPrepared = storageInstance.prepareQuery({ + selector: {} + }); + _context.next = 3; + return storageInstance.query(getAllQueryPrepared); + + case 3: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _getAllDocuments.apply(this, arguments); +} + +function getSingleDocument(_x2, _x3) { + return _getSingleDocument.apply(this, arguments); +} +/** + * get the number of all undeleted documents + */ + + +function _getSingleDocument() { + _getSingleDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(storageInstance, documentId) { + var results, doc; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return storageInstance.findDocumentsById([documentId], false); + + case 2: + results = _context2.sent; + doc = results.get(documentId); + + if (!doc) { + _context2.next = 8; + break; + } + + return _context2.abrupt("return", doc); + + case 8: + return _context2.abrupt("return", null); + + case 9: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _getSingleDocument.apply(this, arguments); +} + +function countAllUndeleted(_x4) { + return _countAllUndeleted.apply(this, arguments); +} +/** + * get a batch of documents from the storage-instance + */ + + +function _countAllUndeleted() { + _countAllUndeleted = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(storageInstance) { + var docs; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getAllDocuments(storageInstance); + + case 2: + docs = _context3.sent; + return _context3.abrupt("return", docs.length); + + case 4: + case "end": + return _context3.stop(); + } + } + }, _callee3); + })); + return _countAllUndeleted.apply(this, arguments); +} + +function getBatch(_x5, _x6) { + return _getBatch.apply(this, arguments); +} +/** + * Writes a single document, + * throws RxStorageBulkWriteError on failure + */ + + +function _getBatch() { + _getBatch = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(storageInstance, limit) { + var preparedQuery, result; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (!(limit <= 1)) { + _context4.next = 2; + break; + } + + throw (0, _rxError.newRxError)('P1', { + limit: limit + }); + + case 2: + preparedQuery = storageInstance.prepareQuery({ + selector: {}, + limit: limit + }); + _context4.next = 5; + return storageInstance.query(preparedQuery); + + case 5: + result = _context4.sent; + return _context4.abrupt("return", result.documents); + + case 7: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + return _getBatch.apply(this, arguments); +} + +function writeSingle(_x7, _x8) { + return _writeSingle.apply(this, arguments); +} +/** + * Writes a single local document, + * throws RxStorageBulkWriteError on failure + */ + + +function _writeSingle() { + _writeSingle = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(instance, writeRow) { + var writeResult, error, ret; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return instance.bulkWrite([writeRow]); + + case 2: + writeResult = _context5.sent; + + if (!(writeResult.error.size > 0)) { + _context5.next = 8; + break; + } + + error = writeResult.error.values().next().value; + throw error; + + case 8: + ret = writeResult.success.values().next().value; + return _context5.abrupt("return", ret); + + case 10: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + return _writeSingle.apply(this, arguments); +} + +function writeSingleLocal(_x9, _x10) { + return _writeSingleLocal.apply(this, arguments); +} + +function _writeSingleLocal() { + _writeSingleLocal = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(instance, writeRow) { + var writeResult, error, ret; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return instance.bulkWrite([writeRow]); + + case 2: + writeResult = _context6.sent; + + if (!(writeResult.error.size > 0)) { + _context6.next = 8; + break; + } + + error = writeResult.error.values().next().value; + throw error; + + case 8: + ret = writeResult.success.values().next().value; + return _context6.abrupt("return", ret); + + case 10: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + return _writeSingleLocal.apply(this, arguments); +} + +function findLocalDocument(_x11, _x12) { + return _findLocalDocument.apply(this, arguments); +} + +function _findLocalDocument() { + _findLocalDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(instance, id) { + var docList, doc; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return instance.findLocalDocumentsById([id]); + + case 2: + docList = _context7.sent; + doc = docList.get(id); + + if (doc) { + _context7.next = 8; + break; + } + + return _context7.abrupt("return", null); + + case 8: + return _context7.abrupt("return", doc); + + case 9: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + return _findLocalDocument.apply(this, arguments); +} + +function getNewestSequence(_x13) { + return _getNewestSequence.apply(this, arguments); +} + +function _getNewestSequence() { + _getNewestSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(storageInstance) { + var changesResult; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return storageInstance.getChangedDocuments({ + order: 'desc', + limit: 1, + startSequence: 0 + }); + + case 2: + changesResult = _context8.sent; + return _context8.abrupt("return", changesResult.lastSequence); + + case 4: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + return _getNewestSequence.apply(this, arguments); +} + +function storageChangeEventToRxChangeEvent(isLocal, rxStorageChangeEvent, rxDatabase, rxCollection) { + var documentData; + + if (rxStorageChangeEvent.change.operation !== 'DELETE') { + if (!rxCollection) { + documentData = rxStorageChangeEvent.change.doc; + } else { + var hookParams = { + collection: rxCollection, + doc: rxStorageChangeEvent.change.doc + }; + (0, _hooks.runPluginHooks)('postReadFromInstance', hookParams); + documentData = hookParams.doc; + documentData = rxCollection._crypter.decrypt(documentData); + } + } + + var previousDocumentData; + + if (rxStorageChangeEvent.change.operation !== 'INSERT') { + if (!rxCollection) { + previousDocumentData = rxStorageChangeEvent.change.previous; + } else { + var _hookParams = { + collection: rxCollection, + doc: rxStorageChangeEvent.change.previous + }; + (0, _hooks.runPluginHooks)('postReadFromInstance', _hookParams); + previousDocumentData = _hookParams.doc; + previousDocumentData = rxCollection._crypter.decrypt(previousDocumentData); + } + } + + var ret = { + eventId: rxStorageChangeEvent.eventId, + documentId: rxStorageChangeEvent.documentId, + databaseToken: rxDatabase.token, + collectionName: rxCollection ? rxCollection.name : undefined, + startTime: rxStorageChangeEvent.startTime, + endTime: rxStorageChangeEvent.endTime, + isLocal: isLocal, + operation: rxStorageChangeEvent.change.operation, + documentData: _overwritable.overwritable.deepFreezeWhenDevMode(documentData), + previousDocumentData: _overwritable.overwritable.deepFreezeWhenDevMode(previousDocumentData) + }; + return ret; +} + +//# sourceMappingURL=rx-storage-helper.js.map \ No newline at end of file diff --git a/dist/lib/rx-storage-pouchdb.js b/dist/lib/rx-storage-pouchdb.js deleted file mode 100644 index 54d4c70ff88..00000000000 --- a/dist/lib/rx-storage-pouchdb.js +++ /dev/null @@ -1,289 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.primarySwapPouchDbQuerySelector = primarySwapPouchDbQuerySelector; -exports.getPouchLocation = getPouchLocation; -exports.getRxStoragePouchDb = getRxStoragePouchDb; -exports.RxStoragePouchDbClass = void 0; - -var _pouchdbSelectorCore = require("pouchdb-selector-core"); - -var _util = require("./util"); - -var _hooks = require("./hooks"); - -var _pouchDb = require("./pouch-db"); - -var _rxError = require("./rx-error"); - -var RxStoragePouchDbClass = /*#__PURE__*/function () { - function RxStoragePouchDbClass(adapter) { - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.name = 'pouchdb'; - this.adapter = adapter; - this.pouchSettings = pouchSettings; - } - - var _proto = RxStoragePouchDbClass.prototype; - - _proto.getSortComparator = function getSortComparator(primaryKey, query) { - var _ref; - - var sortOptions = query.sort ? query.sort : [(_ref = {}, _ref[primaryKey] = 'asc', _ref)]; - var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); - var inMemoryFields = Object.keys(query.selector); - - var fun = function fun(a, b) { - // TODO use createFieldSorter - // TODO make a performance test - var rows = [a, b].map(function (doc) { - // swap primary to _id - var cloned = (0, _util.flatClone)(doc); - var primaryValue = cloned[primaryKey]; - delete cloned[primaryKey]; - cloned._id = primaryValue; - return { - doc: cloned - }; - }); - var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, { - selector: massagedSelector, - sort: sortOptions - }, inMemoryFields); - - if (sortedRows[0].doc._id === rows[0].doc._id) { - return -1; - } else { - return 1; - } - }; - - return fun; - } - /** - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ - ; - - _proto.getQueryMatcher = function getQueryMatcher(primaryKey, query) { - var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); - - var fun = function fun(doc) { - // swap primary to _id - var cloned = (0, _util.flatClone)(doc); - var primaryValue = cloned[primaryKey]; - delete cloned[primaryKey]; - cloned._id = primaryValue; - var row = { - doc: cloned - }; - var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { - selector: massagedSelector - }, Object.keys(query.selector)); - return rowsMatched && rowsMatched.length === 1; - }; - - return fun; - }; - - _proto.createStorageInstance = function createStorageInstance(databaseName, collectionName, schemaVersion) { - var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - - if (!options.pouchSettings) { - options.pouchSettings = {}; - } - - var pouchLocation = getPouchLocation(databaseName, collectionName, schemaVersion); - var pouchDbParameters = { - location: pouchLocation, - adapter: (0, _util.adapterObject)(this.adapter), - settings: options.pouchSettings - }; - var pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); - (0, _hooks.runPluginHooks)('preCreatePouchDb', pouchDbParameters); - return new _pouchDb.PouchDB(pouchDbParameters.location, pouchDBOptions); - }; - - _proto.createInternalStorageInstance = function createInternalStorageInstance(databaseName, _options) { - var storageInstance = this.createStorageInstance(databaseName, '_rxdb_internal', 0, { - pouchSettings: { - // no compaction because this only stores local documents - auto_compaction: false, - revs_limit: 1 - } - }); - return Promise.resolve(storageInstance); - } - /** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ - ; - - _proto.prepareQuery = function prepareQuery(rxQuery, mutateableQuery) { - var primPath = rxQuery.collection.schema.primaryPath; - var query = mutateableQuery; - /** - * because sort wont work on unused keys we have to workaround - * so we add the key to the selector if necessary - * @link https://github.com/nolanlawson/pouchdb-find/issues/204 - */ - - if (query.sort) { - query.sort.forEach(function (sortPart) { - var key = Object.keys(sortPart)[0]; - var comparisonOperators = ['$gt', '$gte', '$lt', '$lte']; - var keyUsed = query.selector[key] && Object.keys(query.selector[key]).some(function (op) { - return comparisonOperators.includes(op); - }) || false; - - if (!keyUsed) { - var schemaObj = rxQuery.collection.schema.getSchemaByObjectPath(key); - - if (!schemaObj) { - throw (0, _rxError.newRxError)('QU5', { - key: key - }); - } - - if (!query.selector[key]) { - query.selector[key] = {}; - } - - switch (schemaObj.type) { - case 'number': - case 'integer': - // TODO change back to -Infinity when issue resolved - // @link https://github.com/pouchdb/pouchdb/issues/6454 - // -Infinity does not work since pouchdb 6.2.0 - query.selector[key].$gt = -9999999999999999999999999999; - break; - - case 'string': - /** - * strings need an empty string, see - * @link https://github.com/pubkey/rxdb/issues/585 - */ - if (typeof query.selector[key] !== 'string') { - query.selector[key].$gt = ''; - } - - break; - - default: - query.selector[key].$gt = null; - break; - } - } - }); - } // regex does not work over the primary key - // TODO move this to dev mode - - - if (query.selector[primPath] && query.selector[primPath].$regex) { - throw (0, _rxError.newRxError)('QU4', { - path: primPath, - query: rxQuery.mangoQuery - }); - } // primary-swap sorting - - - if (query.sort) { - var sortArray = query.sort.map(function (part) { - var _newPart; - - var key = Object.keys(part)[0]; - var direction = Object.values(part)[0]; - var useKey = key === primPath ? '_id' : key; - var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); - return newPart; - }); - query.sort = sortArray; - } // strip empty selectors - - - Object.entries(query.selector).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - - if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { - delete query.selector[k]; - } - }); - - if (primPath !== '_id') { - query.selector = primarySwapPouchDbQuerySelector(query.selector, primPath); - } - - return query; - }; - - return RxStoragePouchDbClass; -}(); -/** - * Runs a primary swap with transform all custom primaryKey occurences - * into '_id' - * @recursive - */ - - -exports.RxStoragePouchDbClass = RxStoragePouchDbClass; - -function primarySwapPouchDbQuerySelector(selector, primaryKey) { - if (Array.isArray(selector)) { - return selector.map(function (item) { - return primarySwapPouchDbQuerySelector(item, primaryKey); - }); - } else if (typeof selector === 'object') { - var ret = {}; - Object.entries(selector).forEach(function (_ref3) { - var k = _ref3[0], - v = _ref3[1]; - - if (k === primaryKey) { - ret._id = v; - } else { - if (k.startsWith('$')) { - ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); - } else { - ret[k] = v; - } - } - }); - return ret; - } else { - return selector; - } -} -/** - * returns the pouchdb-database-name - */ - - -function getPouchLocation(dbName, collectionName, schemaVersion) { - var prefix = dbName + '-rxdb-' + schemaVersion + '-'; - - if (!collectionName.includes('/')) { - return prefix + collectionName; - } else { - // if collectionName is a path, we have to prefix the last part only - var split = collectionName.split('/'); - var last = split.pop(); - var ret = split.join('/'); - ret += '/' + prefix + last; - return ret; - } -} - -function getRxStoragePouchDb(adapter, pouchSettings) { - if (!adapter) { - throw new Error('adapter missing'); - } - - return new RxStoragePouchDbClass(adapter, pouchSettings); -} - -//# sourceMappingURL=rx-storage-pouchdb.js.map \ No newline at end of file diff --git a/dist/lib/rx-storate.interface.js b/dist/lib/rx-storate.interface.js deleted file mode 100644 index ead89cecfb7..00000000000 --- a/dist/lib/rx-storate.interface.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; - -//# sourceMappingURL=rx-storate.interface.js.map \ No newline at end of file diff --git a/dist/lib/types/index.d.js b/dist/lib/types/index.d.js index 27b247a039a..de57aa4e1bc 100644 --- a/dist/lib/types/index.d.js +++ b/dist/lib/types/index.d.js @@ -121,6 +121,58 @@ Object.keys(_rxSchema).forEach(function (key) { }); }); +var _rxStorage = require("./rx-storage"); + +Object.keys(_rxStorage).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rxStorage[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rxStorage[key]; + } + }); +}); + +var _rxStorage2 = require("./rx-storage.interface"); + +Object.keys(_rxStorage2).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rxStorage2[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rxStorage2[key]; + } + }); +}); + +var _rxChangeEvent = require("./rx-change-event"); + +Object.keys(_rxChangeEvent).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rxChangeEvent[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rxChangeEvent[key]; + } + }); +}); + +var _util = require("./util"); + +Object.keys(_util).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _util[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _util[key]; + } + }); +}); + var _replication = require("./plugins/replication"); Object.keys(_replication).forEach(function (key) { diff --git a/dist/lib/types/rx-change-event.d.js b/dist/lib/types/rx-change-event.d.js new file mode 100644 index 00000000000..e4c52c49a8c --- /dev/null +++ b/dist/lib/types/rx-change-event.d.js @@ -0,0 +1,3 @@ +"use strict"; + +//# sourceMappingURL=rx-change-event.d.js.map \ No newline at end of file diff --git a/dist/lib/types/rx-storage.d.js b/dist/lib/types/rx-storage.d.js new file mode 100644 index 00000000000..64e4cbfe27b --- /dev/null +++ b/dist/lib/types/rx-storage.d.js @@ -0,0 +1,3 @@ +"use strict"; + +//# sourceMappingURL=rx-storage.d.js.map \ No newline at end of file diff --git a/dist/lib/types/rx-storage.interface.d.js b/dist/lib/types/rx-storage.interface.d.js new file mode 100644 index 00000000000..c82273a8da5 --- /dev/null +++ b/dist/lib/types/rx-storage.interface.d.js @@ -0,0 +1,3 @@ +"use strict"; + +//# sourceMappingURL=rx-storage.interface.d.js.map \ No newline at end of file diff --git a/dist/lib/util.js b/dist/lib/util.js index 824b5fc38d1..943339674f2 100644 --- a/dist/lib/util.js +++ b/dist/lib/util.js @@ -8,7 +8,6 @@ Object.defineProperty(exports, "__esModule", { exports.pluginMissing = pluginMissing; exports.fastUnsecureHash = fastUnsecureHash; exports.hash = hash; -exports.generateId = generateId; exports.now = now; exports.nextTick = nextTick; exports.promiseWait = promiseWait; @@ -22,6 +21,7 @@ exports.ensureNotFalsy = ensureNotFalsy; exports.sortObject = sortObject; exports.stringifyFilter = stringifyFilter; exports.randomCouchString = randomCouchString; +exports.lastOfArray = lastOfArray; exports.shuffleArray = shuffleArray; exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; exports.adapterObject = adapterObject; @@ -31,9 +31,8 @@ exports.getHeightOfRevision = getHeightOfRevision; exports.createRevision = createRevision; exports.overwriteGetterForCaching = overwriteGetterForCaching; exports.isFolderPath = isFolderPath; -exports.blobBufferUtil = exports.LOCAL_PREFIX = exports.isElectronRenderer = exports.clone = exports.RXDB_HASH_SALT = void 0; - -var _randomToken = _interopRequireDefault(require("random-token")); +exports.getFromMapOrThrow = getFromMapOrThrow; +exports.blobBufferUtil = exports.isElectronRenderer = exports.clone = exports.RXDB_HASH_SALT = void 0; var _clone = _interopRequireDefault(require("clone")); @@ -45,11 +44,6 @@ var _pouchdbMd = require("pouchdb-md5"); var _pouchdbUtils = require("pouchdb-utils"); -/** - * this contains a mapping to basic dependencies - * which should be easy to change - */ - /** * Returns an error that indicates that a plugin is missing * We do not throw a RxError because this should not be handled @@ -111,14 +105,6 @@ function hash(msg) { return _sparkMd["default"].hash(RXDB_HASH_SALT + msg); } -/** - * generate a new _id as db-primary-key - */ - - -function generateId() { - return (0, _randomToken["default"])(10) + ':' + now(); -} /** * Returns the current unix time in milliseconds * Because the accuracy of getTime() in javascript is bad, @@ -282,7 +268,10 @@ function sortObject(obj) { function stringifyFilter(key, value) { - if (value instanceof RegExp) return value.toString(); + if (value instanceof RegExp) { + return value.toString(); + } + return value; } /** @@ -302,6 +291,10 @@ function randomCouchString() { return text; } + +function lastOfArray(ar) { + return ar[ar.length - 1]; +} /** * shuffle the given array */ @@ -418,18 +411,11 @@ function createRevision(docData, deterministic_revs) { }); return (0, _pouchdbMd.stringMd5)(JSON.stringify(docWithoutRev)); } -/** - * prefix of local pouchdb documents - */ - - -var LOCAL_PREFIX = '_local/'; /** * overwrites the getter with the actual value * Mostly used for caching stuff on the first run */ -exports.LOCAL_PREFIX = LOCAL_PREFIX; function overwriteGetterForCaching(obj, getterName, value) { Object.defineProperty(obj, getterName, { @@ -455,6 +441,16 @@ function isFolderPath(name) { } } +function getFromMapOrThrow(map, key) { + var val = map.get(key); + + if (!val) { + throw new Error('missing value from map ' + key); + } + + return val; +} + var blobBufferUtil = { /** * depending if we are on node or browser, @@ -484,6 +480,13 @@ var blobBufferUtil = { return blobBuffer; }, + isBlobBuffer: function isBlobBuffer(data) { + if (data instanceof Blob || Buffer.isBuffer(data)) { + return true; + } else { + return false; + } + }, toString: function toString(blobBuffer) { if (blobBuffer instanceof Buffer) { // node diff --git a/dist/rxdb.browserify.js b/dist/rxdb.browserify.js index 1fa972422ab..4d0542b2bc7 100644 --- a/dist/rxdb.browserify.js +++ b/dist/rxdb.browserify.js @@ -5,6 +5,8 @@ require("@babel/polyfill"); var RxDB = _interopRequireWildcard(require("./index.js")); +var RxDbPouchPlugin = _interopRequireWildcard(require("./plugins/pouchdb/index.js")); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } @@ -14,12 +16,12 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && * which produces a single file that can be embeded into the html * and used via window.RxDB */ -RxDB.addRxPlugin(require('pouchdb-adapter-idb')); -RxDB.addRxPlugin(require('pouchdb-adapter-http')); +RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb')); +RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http')); window['RxDB'] = RxDB; -},{"./index.js":8,"@babel/polyfill":57,"pouchdb-adapter-http":647,"pouchdb-adapter-idb":648}],2:[function(require,module,exports){ +},{"./index.js":8,"./plugins/pouchdb/index.js":32,"@babel/polyfill":59,"pouchdb-adapter-http":647,"pouchdb-adapter-idb":648}],2:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -28,6 +30,8 @@ Object.defineProperty(exports, "__esModule", { exports.createChangeEventBuffer = createChangeEventBuffer; exports.ChangeEventBuffer = void 0; +var _operators = require("rxjs/operators"); + /** * a buffer-cache which holds the last X changeEvents of the collection */ @@ -45,7 +49,9 @@ var ChangeEventBuffer = /*#__PURE__*/function () { this.eventCounterMap = new WeakMap(); this.buffer = []; this.collection = collection; - this.subs.push(this.collection.$.subscribe(function (cE) { + this.subs.push(this.collection.$.pipe((0, _operators.filter)(function (cE) { + return !cE.isLocal; + })).subscribe(function (cE) { return _this._handleChangeEvent(cE); })); } @@ -53,7 +59,6 @@ var ChangeEventBuffer = /*#__PURE__*/function () { var _proto = ChangeEventBuffer.prototype; _proto._handleChangeEvent = function _handleChangeEvent(changeEvent) { - // console.log('changeEventBuffer()._handleChangeEvent()'); this.counter++; this.buffer.push(changeEvent); this.eventCounterMap.set(changeEvent, this.counter); @@ -132,6 +137,7 @@ var ChangeEventBuffer = /*#__PURE__*/function () { /** * use this to check if a change has already been handled * @returns true if change with revision exists + * TODO only used in the in-memory plugin, we should move it there. * */ ; @@ -143,7 +149,10 @@ var ChangeEventBuffer = /*#__PURE__*/function () { while (t > 0) { t--; var cE = this.buffer[t]; - if (cE.documentData && cE.documentData._rev === revision) return true; + + if (cE.documentData && cE.documentData._rev === revision) { + return true; + } } return false; @@ -165,7 +174,7 @@ function createChangeEventBuffer(collection) { } -},{}],3:[function(require,module,exports){ +},{"rxjs/operators":908}],3:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -173,19 +182,17 @@ Object.defineProperty(exports, "__esModule", { }); var _exportNames = { addRxPlugin: true, - PouchDB: true, - validateCouchDBString: true, - getBatch: true, - countAllUndeleted: true, - getNewestSequence: true, createRxDatabase: true, removeRxDatabase: true, - checkAdapter: true, isRxDatabase: true, dbCount: true, _collectionNamePrimary: true, isRxCollection: true, - _createRxCollection: true, + RxCollectionBase: true, + createRxCollection: true, + _handleFromStorageInstance: true, + _handleToStorageInstance: true, + fillObjectDataBeforeInsert: true, isRxDocument: true, getDocumentOrmPrototype: true, getDocumentPrototype: true, @@ -197,9 +204,16 @@ var _exportNames = { normalize: true, getFinalFields: true, getPreviousVersions: true, - RxChangeEvent: true, - getRxStoragePouchDb: true, - getPouchLocation: true, + getPseudoSchemaForVersion: true, + getSchemaByObjectPath: true, + findLocalDocument: true, + getSingleDocument: true, + getNewestSequence: true, + getAllDocuments: true, + writeSingleLocal: true, + writeSingle: true, + countAllUndeleted: true, + getBatch: true, _clearHook: true, createCrypter: true }; @@ -209,88 +223,76 @@ Object.defineProperty(exports, "addRxPlugin", { return _plugin.addRxPlugin; } }); -Object.defineProperty(exports, "PouchDB", { - enumerable: true, - get: function get() { - return _pouchDb.PouchDB; - } -}); -Object.defineProperty(exports, "validateCouchDBString", { - enumerable: true, - get: function get() { - return _pouchDb.validateCouchDBString; - } -}); -Object.defineProperty(exports, "getBatch", { +Object.defineProperty(exports, "createRxDatabase", { enumerable: true, get: function get() { - return _pouchDb.getBatch; + return _rxDatabase.createRxDatabase; } }); -Object.defineProperty(exports, "countAllUndeleted", { +Object.defineProperty(exports, "removeRxDatabase", { enumerable: true, get: function get() { - return _pouchDb.countAllUndeleted; + return _rxDatabase.removeRxDatabase; } }); -Object.defineProperty(exports, "getNewestSequence", { +Object.defineProperty(exports, "isRxDatabase", { enumerable: true, get: function get() { - return _pouchDb.getNewestSequence; + return _rxDatabase.isRxDatabase; } }); -Object.defineProperty(exports, "createRxDatabase", { +Object.defineProperty(exports, "dbCount", { enumerable: true, get: function get() { - return _rxDatabase.createRxDatabase; + return _rxDatabase.dbCount; } }); -Object.defineProperty(exports, "removeRxDatabase", { +Object.defineProperty(exports, "_collectionNamePrimary", { enumerable: true, get: function get() { - return _rxDatabase.removeRxDatabase; + return _rxDatabase._collectionNamePrimary; } }); -Object.defineProperty(exports, "checkAdapter", { +Object.defineProperty(exports, "isRxCollection", { enumerable: true, get: function get() { - return _rxDatabase.checkAdapter; + return _rxCollection.isRxCollection; } }); -Object.defineProperty(exports, "isRxDatabase", { +Object.defineProperty(exports, "RxCollectionBase", { enumerable: true, get: function get() { - return _rxDatabase.isInstanceOf; + return _rxCollection.RxCollectionBase; } }); -Object.defineProperty(exports, "dbCount", { +Object.defineProperty(exports, "createRxCollection", { enumerable: true, get: function get() { - return _rxDatabase.dbCount; + return _rxCollection.createRxCollection; } }); -Object.defineProperty(exports, "_collectionNamePrimary", { +Object.defineProperty(exports, "_handleFromStorageInstance", { enumerable: true, get: function get() { - return _rxDatabase._collectionNamePrimary; + return _rxCollectionHelper._handleFromStorageInstance; } }); -Object.defineProperty(exports, "isRxCollection", { +Object.defineProperty(exports, "_handleToStorageInstance", { enumerable: true, get: function get() { - return _rxCollection.isInstanceOf; + return _rxCollectionHelper._handleToStorageInstance; } }); -Object.defineProperty(exports, "_createRxCollection", { +Object.defineProperty(exports, "fillObjectDataBeforeInsert", { enumerable: true, get: function get() { - return _rxCollection.create; + return _rxCollectionHelper.fillObjectDataBeforeInsert; } }); Object.defineProperty(exports, "isRxDocument", { enumerable: true, get: function get() { - return _rxDocument.isInstanceOf; + return _rxDocument.isRxDocument; } }); Object.defineProperty(exports, "getDocumentOrmPrototype", { @@ -353,22 +355,64 @@ Object.defineProperty(exports, "getPreviousVersions", { return _rxSchema.getPreviousVersions; } }); -Object.defineProperty(exports, "RxChangeEvent", { +Object.defineProperty(exports, "getPseudoSchemaForVersion", { + enumerable: true, + get: function get() { + return _rxSchemaHelper.getPseudoSchemaForVersion; + } +}); +Object.defineProperty(exports, "getSchemaByObjectPath", { + enumerable: true, + get: function get() { + return _rxSchemaHelper.getSchemaByObjectPath; + } +}); +Object.defineProperty(exports, "findLocalDocument", { + enumerable: true, + get: function get() { + return _rxStorageHelper.findLocalDocument; + } +}); +Object.defineProperty(exports, "getSingleDocument", { + enumerable: true, + get: function get() { + return _rxStorageHelper.getSingleDocument; + } +}); +Object.defineProperty(exports, "getNewestSequence", { + enumerable: true, + get: function get() { + return _rxStorageHelper.getNewestSequence; + } +}); +Object.defineProperty(exports, "getAllDocuments", { enumerable: true, get: function get() { - return _rxChangeEvent.RxChangeEvent; + return _rxStorageHelper.getAllDocuments; } }); -Object.defineProperty(exports, "getRxStoragePouchDb", { +Object.defineProperty(exports, "writeSingleLocal", { enumerable: true, get: function get() { - return _rxStoragePouchdb.getRxStoragePouchDb; + return _rxStorageHelper.writeSingleLocal; } }); -Object.defineProperty(exports, "getPouchLocation", { +Object.defineProperty(exports, "writeSingle", { enumerable: true, get: function get() { - return _rxStoragePouchdb.getPouchLocation; + return _rxStorageHelper.writeSingle; + } +}); +Object.defineProperty(exports, "countAllUndeleted", { + enumerable: true, + get: function get() { + return _rxStorageHelper.countAllUndeleted; + } +}); +Object.defineProperty(exports, "getBatch", { + enumerable: true, + get: function get() { + return _rxStorageHelper.getBatch; } }); Object.defineProperty(exports, "_clearHook", { @@ -392,18 +436,16 @@ require("./types/modules/mocha.parallel.d"); require("./types/modules/modifiyjs.d"); -require("./types/modules/pouchdb-selector-core.d"); - require("./types/modules/random-token.d"); var _plugin = require("./plugin"); -var _pouchDb = require("./pouch-db"); - var _rxDatabase = require("./rx-database"); var _rxCollection = require("./rx-collection"); +var _rxCollectionHelper = require("./rx-collection-helper"); + var _rxDocument = require("./rx-document"); var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); @@ -412,9 +454,9 @@ var _rxQuery = require("./rx-query"); var _rxSchema = require("./rx-schema"); -var _rxChangeEvent = require("./rx-change-event"); +var _rxSchemaHelper = require("./rx-schema-helper"); -var _rxStoragePouchdb = require("./rx-storage-pouchdb"); +var _rxStorageHelper = require("./rx-storage-helper"); var _hooks = require("./hooks"); @@ -449,7 +491,7 @@ Object.keys(_util).forEach(function (key) { }); -},{"./crypter":4,"./hooks":7,"./plugin":10,"./pouch-db":37,"./query-cache":38,"./rx-change-event":39,"./rx-collection":41,"./rx-database":43,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-query":47,"./rx-schema":48,"./rx-storage-pouchdb":49,"./types/modules/crypto-js.d":50,"./types/modules/graphql-client.d":51,"./types/modules/mocha.parallel.d":52,"./types/modules/modifiyjs.d":53,"./types/modules/pouchdb-selector-core.d":54,"./types/modules/random-token.d":55,"./util":56}],4:[function(require,module,exports){ +},{"./crypter":4,"./hooks":7,"./plugin":10,"./query-cache":41,"./rx-collection":44,"./rx-collection-helper":43,"./rx-database":45,"./rx-document":47,"./rx-document-prototype-merge":46,"./rx-query":49,"./rx-schema":51,"./rx-schema-helper":50,"./rx-storage-helper":52,"./types/modules/crypto-js.d":53,"./types/modules/graphql-client.d":54,"./types/modules/mocha.parallel.d":55,"./types/modules/modifiyjs.d":56,"./types/modules/random-token.d":57,"./util":58}],4:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -466,6 +508,9 @@ var _util = require("./util"); /** * handle the en/decryption of documents-data + * TODO atm we have the crypter inside of rxdb core. + * Instead all should be moved to the encryption plugin + * and work via plugin hooks. */ var Crypter = /*#__PURE__*/function () { function Crypter(password, schema) { @@ -473,37 +518,44 @@ var Crypter = /*#__PURE__*/function () { this.schema = schema; } /** - * encrypt and stringify data + * encrypt a given string. * @overwritten by plugin (optional) */ var _proto = Crypter.prototype; - _proto._encryptValue = function _encryptValue(_value) { + _proto._encryptString = function _encryptString(_value) { throw (0, _util.pluginMissing)('encryption'); } /** - * decrypt and json-parse an encrypted value + * decrypt a given string. * @overwritten by plugin (optional) */ ; - _proto._decryptValue = function _decryptValue(_value) { + _proto._decryptString = function _decryptString(_value) { throw (0, _util.pluginMissing)('encryption'); }; _proto.encrypt = function encrypt(obj) { var _this = this; - if (!this.password) return obj; + if (!this.password) { + return obj; + } + obj = (0, _util.clone)(obj); this.schema.encryptedPaths.forEach(function (path) { var value = _objectPath["default"].get(obj, path); - if (typeof value === 'undefined') return; + if (typeof value === 'undefined') { + return; + } + + var stringValue = JSON.stringify(value); - var encrypted = _this._encryptValue(value); + var encrypted = _this._encryptString(stringValue); _objectPath["default"].set(obj, path, encrypted); }); @@ -518,11 +570,15 @@ var Crypter = /*#__PURE__*/function () { this.schema.encryptedPaths.forEach(function (path) { var value = _objectPath["default"].get(obj, path); - if (typeof value === 'undefined') return; + if (typeof value === 'undefined') { + return; + } + + var decrypted = _this2._decryptString(value); - var decrypted = _this2._decryptValue(value); + var decryptedParsed = JSON.parse(decrypted); - _objectPath["default"].set(obj, path, decrypted); + _objectPath["default"].set(obj, path, decryptedParsed); }); return obj; }; @@ -537,7 +593,7 @@ function createCrypter(password, schema) { } -},{"./util":56,"@babel/runtime/helpers/interopRequireDefault":65,"object-path":630}],5:[function(require,module,exports){ +},{"./util":58,"@babel/runtime/helpers/interopRequireDefault":67,"object-path":629}],5:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -589,6 +645,10 @@ exports.RXQUERY_QUERY_PARAMS_CACHE = void 0; var _eventReduceJs = require("event-reduce-js"); +var _hooks = require("./hooks"); + +var _rxChangeEvent = require("./rx-change-event"); + function getSortFieldsOfQuery(primaryKey, query) { if (!query.sort || query.sort.length === 0) { return [primaryKey]; @@ -604,16 +664,51 @@ exports.RXQUERY_QUERY_PARAMS_CACHE = RXQUERY_QUERY_PARAMS_CACHE; function getQueryParams(rxQuery) { if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) { - var storage = rxQuery.collection.database.storage; + var collection = rxQuery.collection; var queryJson = rxQuery.toJSON(); - var primaryKey = rxQuery.collection.schema.primaryPath; + var primaryKey = collection.schema.primaryPath; + /** + * Create a custom sort comparator + * that uses the hooks to ensure + * we send for example compressed documents to be sorted by compressed queries. + */ + + var sortComparator = collection.storageInstance.getSortComparator(queryJson); + + var useSortComparator = function useSortComparator(docA, docB) { + var sortComparatorData = { + docA: docA, + docB: docB, + rxQuery: rxQuery + }; + (0, _hooks.runPluginHooks)('preSortComparator', sortComparatorData); + return sortComparator(sortComparatorData.docA, sortComparatorData.docB); + }; + /** + * Create a custom query matcher + * that uses the hooks to ensure + * we send for example compressed documents to match compressed queries. + */ + + + var queryMatcher = collection.storageInstance.getQueryMatcher(queryJson); + + var useQueryMatcher = function useQueryMatcher(doc) { + var queryMatcherData = { + doc: doc, + rxQuery: rxQuery + }; + (0, _hooks.runPluginHooks)('preQueryMatcher', queryMatcherData); + return queryMatcher(queryMatcherData.doc); + }; + var ret = { primaryKey: rxQuery.collection.schema.primaryPath, skip: queryJson.skip, limit: queryJson.limit, sortFields: getSortFieldsOfQuery(primaryKey, queryJson), - sortComparator: storage.getSortComparator(primaryKey, queryJson), - queryMatcher: storage.getQueryMatcher(primaryKey, queryJson) + sortComparator: useSortComparator, + queryMatcher: useQueryMatcher }; RXQUERY_QUERY_PARAMS_CACHE.set(rxQuery, ret); return ret; @@ -636,7 +731,7 @@ function calculateNewResults(rxQuery, rxChangeEvents) { var previousResultsMap = rxQuery._resultsDataMap; var changed = false; var foundNonOptimizeable = rxChangeEvents.find(function (cE) { - var eventReduceEvent = cE.toEventReduceChangeEvent(); + var eventReduceEvent = (0, _rxChangeEvent.rxChangeEventToEventReduceChangeEvent)(cE); var actionName = (0, _eventReduceJs.calculateActionName)({ queryParams: queryParams, changeEvent: eventReduceEvent, @@ -667,7 +762,7 @@ function calculateNewResults(rxQuery, rxChangeEvents) { } -},{"event-reduce-js":532}],7:[function(require,module,exports){ +},{"./hooks":7,"./rx-change-event":42,"event-reduce-js":534}],7:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -725,6 +820,34 @@ var HOOKS = { createRxSchema: [], preCreateRxQuery: [], createRxQuery: [], + + /** + * Runs before a document is send to the query matcher. + */ + preQueryMatcher: [], + + /** + * Runs before a document is send to the sortComparator. + */ + preSortComparator: [], + + /** + * Runs before a query is send to the + * prepareQuery function of the storage engine. + */ + prePrepareQuery: [], + + /** + * Runs before the document data is send to the + * bulkWrite of the storage instance + */ + preWriteToStorageInstance: [], + + /** + * Runs after the document data is ready from + * the storage instance. + */ + postReadFromInstance: [], createRxDocument: [], /** @@ -734,15 +857,12 @@ var HOOKS = { postCreateRxDocument: [], /** - * runs before a pouchdb-instance is created - * gets pouchParameters as attribute so you can manipulate them - * { - * location: string, - * adapter: any, - * settings: object - * } + * Runs before a RxStorageInstance is created + * gets the params of createStorageInstance() + * as attribute so you can manipulate them. + * Notice that you have to clone stuff before mutating the inputs. */ - preCreatePouchDb: [], + preCreateRxStorageInstance: [], /** * runs on the document-data before the document is migrated @@ -828,11 +948,7 @@ var _encryption = require("./plugins/encryption"); var _update = require("./plugins/update"); -var _watchForChanges = require("./plugins/watch-for-changes"); - -var _replication = require("./plugins/replication"); - -var _adapterCheck = require("./plugins/adapter-check"); +var _replicationCouchdb = require("./plugins/replication-couchdb"); var _jsonDump = require("./plugins/json-dump"); @@ -844,6 +960,19 @@ var _localDocuments = require("./plugins/local-documents"); var _queryBuilder = require("./plugins/query-builder"); +var _pouchdb = require("./plugins/pouchdb"); + +Object.keys(_pouchdb).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _pouchdb[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _pouchdb[key]; + } + }); +}); + /** * this is the default rxdb-export * It has a batteries-included guarantee. @@ -857,9 +986,7 @@ var _queryBuilder = require("./plugins/query-builder"); (0, _core.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); (0, _core.addRxPlugin)(_encryption.RxDBEncryptionPlugin); (0, _core.addRxPlugin)(_update.RxDBUpdatePlugin); -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); -(0, _core.addRxPlugin)(_replication.RxDBReplicationPlugin); -(0, _core.addRxPlugin)(_adapterCheck.RxDBAdapterCheckPlugin); +(0, _core.addRxPlugin)(_replicationCouchdb.RxDBReplicationCouchDBPlugin); (0, _core.addRxPlugin)(_jsonDump.RxDBJsonDumpPlugin); (0, _core.addRxPlugin)(_inMemory.RxDBInMemoryPlugin); (0, _core.addRxPlugin)(_attachments.RxDBAttachmentsPlugin); @@ -867,7 +994,7 @@ var _queryBuilder = require("./plugins/query-builder"); (0, _core.addRxPlugin)(_queryBuilder.RxDBQueryBuilderPlugin); // re-export things from core -},{"./core":3,"./plugins/adapter-check":11,"./plugins/attachments":12,"./plugins/dev-mode":19,"./plugins/encryption":21,"./plugins/in-memory":22,"./plugins/json-dump":23,"./plugins/key-compression":24,"./plugins/leader-election":25,"./plugins/local-documents":26,"./plugins/migration":28,"./plugins/query-builder":30,"./plugins/replication":33,"./plugins/update":34,"./plugins/validate":35,"./plugins/watch-for-changes":36}],9:[function(require,module,exports){ +},{"./core":3,"./plugins/attachments":11,"./plugins/dev-mode":19,"./plugins/encryption":21,"./plugins/in-memory":22,"./plugins/json-dump":23,"./plugins/key-compression":24,"./plugins/leader-election":25,"./plugins/local-documents":26,"./plugins/migration":28,"./plugins/pouchdb":32,"./plugins/query-builder":35,"./plugins/replication-couchdb":38,"./plugins/update":39,"./plugins/validate":40}],9:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -890,6 +1017,16 @@ var overwritable = { return false; }, + /** + * Deep freezes and object when in dev-mode. + * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode. + * Also we can ensure the readonly state via typescript + * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ + deepFreezeWhenDevMode: function deepFreezeWhenDevMode(obj) { + return obj; + }, + /** * validates if a password can be used * @overwritten by plugin (optional) @@ -899,20 +1036,6 @@ var overwritable = { throw (0, _util.pluginMissing)('encryption'); }, - /** - * creates a key-compressor for the given schema - */ - createKeyCompressor: function createKeyCompressor(_rxSchema) { - throw (0, _util.pluginMissing)('key-compression'); - }, - - /** - * checks if the given adapter can be used - */ - checkAdapter: function checkAdapter(_adapter) { - throw (0, _util.pluginMissing)('adapter-check'); - }, - /** * overwritte to map error-codes to text-messages */ @@ -923,7 +1046,7 @@ var overwritable = { exports.overwritable = overwritable; -},{"./util":56}],10:[function(require,module,exports){ +},{"./util":58}],10:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -943,12 +1066,12 @@ var _rxCollection = require("./rx-collection"); var _rxDatabase = require("./rx-database"); -var _pouchDb = require("./pouch-db"); - var _overwritable = require("./overwritable"); var _hooks = require("./hooks"); +var _rxError = require("./rx-error"); + /** * this handles how plugins are added to rxdb * basically it changes the internal prototypes @@ -967,6 +1090,10 @@ var PROTOTYPES = { RxDatabase: _rxDatabase.RxDatabaseBase.prototype }; var ADDED_PLUGINS = new Set(); +/** + * Add a plugin to the RxDB library. + * Plugins are added globally and cannot be removed. + */ function addRxPlugin(plugin) { (0, _hooks.runPluginHooks)('preAddRxPlugin', { @@ -979,19 +1106,21 @@ function addRxPlugin(plugin) { } else { ADDED_PLUGINS.add(plugin); } + /** + * Since version 10.0.0 we decoupled pouchdb from + * the rxdb core. Therefore pouchdb plugins must be added + * with the addPouchPlugin() method of the pouchdb plugin. + */ - if (!plugin.rxdb) { - // pouchdb-plugin - if (typeof plugin === 'object' && plugin["default"]) plugin = plugin["default"]; - - _pouchDb.PouchDB.plugin(plugin); - return; - } + if (!plugin.rxdb) { + throw (0, _rxError.newRxTypeError)('PL1', { + plugin: plugin + }); + } // prototype-overwrites - var rxPlugin = plugin; // prototype-overwrites - if (rxPlugin.prototypes) { + if (plugin.prototypes) { Object.entries(plugin.prototypes).forEach(function (_ref) { var name = _ref[0], fun = _ref[1]; @@ -1000,12 +1129,12 @@ function addRxPlugin(plugin) { } // overwritable-overwrites - if (rxPlugin.overwritable) { + if (plugin.overwritable) { Object.assign(_overwritable.overwritable, plugin.overwritable); } // extend-hooks - if (rxPlugin.hooks) { + if (plugin.hooks) { Object.entries(plugin.hooks).forEach(function (_ref2) { var name = _ref2[0], fun = _ref2[1]; @@ -1015,101 +1144,8 @@ function addRxPlugin(plugin) { } -},{"./crypter":4,"./hooks":7,"./overwritable":9,"./pouch-db":37,"./rx-collection":41,"./rx-database":43,"./rx-document":45,"./rx-query":47,"./rx-schema":48}],11:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.checkAdapter = checkAdapter; -exports.RxDBAdapterCheckPlugin = exports.overwritable = exports.prototypes = exports.rxdb = exports.POUCHDB_LOCATION = void 0; - -var _pouchDb = require("../pouch-db"); - -var _util = require("../util"); - -/** - * this plugin adds the checkAdapter-function to rxdb - * you can use it to check if the given adapter is working in the current environmet - */ - -/** - * The same pouchdb-location is used on each run - * To ensure when this is run multiple times, - * there will not be many created databases - */ -var POUCHDB_LOCATION = 'rxdb-adapter-check'; -exports.POUCHDB_LOCATION = POUCHDB_LOCATION; - -function checkAdapter(adapter) { - // id of the document which is stored and removed to ensure everything works - var _id = POUCHDB_LOCATION + '-' + (0, _util.generateId)(); - - var pouch; - - try { - pouch = new _pouchDb.PouchDB(POUCHDB_LOCATION, (0, _util.adapterObject)(adapter), { - auto_compaction: true, - revs_limit: 1 - }); - } catch (err) { - return Promise.resolve(false); - } - - var recoveredDoc; - return pouch.info() // ensure that we wait until db is useable - // ensure write works - .then(function () { - return pouch.put({ - _id: _id, - value: { - ok: true, - time: new Date().getTime() - } - }); - }) // ensure read works - .then(function () { - return pouch.get(_id); - }).then(function (doc) { - return recoveredDoc = doc; - }) // ensure remove works - .then(function () { - return pouch.remove(recoveredDoc); - }).then(function () { - return true; - }).then(function () { - if (recoveredDoc && recoveredDoc.value && recoveredDoc.value.ok) return true;else return false; - })["catch"](function () { - return false; - }); - /** - * NOTICE: - * Do not remove the pouchdb-instance after the test - * The problem is that when this function is call in parallel, - * for example when you restore the tabs from a browser-session and open - * the same website multiple times at the same time, - * calling destroy would possibly crash the other call - */ -} - -var rxdb = true; -exports.rxdb = rxdb; -var prototypes = {}; -exports.prototypes = prototypes; -var overwritable = { - checkAdapter: checkAdapter -}; -exports.overwritable = overwritable; -var RxDBAdapterCheckPlugin = { - name: 'adapter-check', - rxdb: rxdb, - prototypes: prototypes, - overwritable: overwritable -}; -exports.RxDBAdapterCheckPlugin = RxDBAdapterCheckPlugin; - - -},{"../pouch-db":37,"../util":56}],12:[function(require,module,exports){ +},{"./crypter":4,"./hooks":7,"./overwritable":9,"./rx-collection":44,"./rx-database":45,"./rx-document":47,"./rx-error":48,"./rx-query":49,"./rx-schema":51}],11:[function(require,module,exports){ +(function (Buffer){(function (){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -1117,7 +1153,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromPouchDocument = fromPouchDocument; +exports.fromStorageInstanceResult = fromStorageInstanceResult; exports.putAttachment = putAttachment; exports.getAttachment = getAttachment; exports.allAttachments = allAttachments; @@ -1131,13 +1167,11 @@ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/ var _operators = require("rxjs/operators"); -var _rxChangeEvent = require("./../rx-change-event"); - var _util = require("./../util"); var _rxError = require("../rx-error"); -var _pouchDb = require("../pouch-db"); +var _rxStorageHelper = require("../rx-storage-helper"); function ensureSchemaSupportsAttachments(doc) { var schemaJson = doc.collection.schema.jsonSchema; @@ -1149,17 +1183,6 @@ function ensureSchemaSupportsAttachments(doc) { } } -function resyncRxDocument(doc) { - var startTime = (0, _util.now)(); - return doc.collection.pouch.get(doc.primary).then(function (docDataFromPouch) { - var data = doc.collection._handleFromPouch(docDataFromPouch); - - var endTime = (0, _util.now)(); - var changeEvent = (0, _rxChangeEvent.createUpdateEvent)(doc.collection, data, null, startTime, endTime, doc); - doc.$emit(changeEvent); - }); -} - var _assignMethodsToAttachment = function _assignMethodsToAttachment(attachment) { Object.entries(attachment.doc.collection.attachments).forEach(function (_ref) { var funName = _ref[0], @@ -1183,43 +1206,122 @@ var RxAttachment = /*#__PURE__*/function () { id = _ref2.id, type = _ref2.type, length = _ref2.length, - digest = _ref2.digest, - rev = _ref2.rev; + digest = _ref2.digest; this.doc = doc; this.id = id; this.type = type; this.length = length; this.digest = digest; - this.rev = rev; _assignMethodsToAttachment(this); } var _proto = RxAttachment.prototype; - _proto.remove = function remove() { - var _this = this; + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var _this = this; - return this.doc.collection.pouch.removeAttachment(this.doc.primary, this.id, this.doc._data._rev).then(function () { - return resyncRxDocument(_this.doc); - }); - } + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + this.doc._atomicQueue = this.doc._atomicQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var docWriteData, writeResult, newData; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + docWriteData = (0, _util.flatClone)(_this.doc._data); + docWriteData._attachments = (0, _util.flatClone)(docWriteData._attachments); + delete docWriteData._attachments[_this.id]; + _context.next = 5; + return (0, _rxStorageHelper.writeSingle)(_this.doc.collection.storageInstance, { + previous: _this.doc._data, + document: docWriteData + }); + + case 5: + writeResult = _context.sent; + newData = (0, _util.flatClone)(_this.doc._data); + newData._rev = writeResult._rev; + newData._attachments = writeResult._attachments; + + _this.doc._dataSync$.next(newData); + + case 10: + case "end": + return _context.stop(); + } + } + }, _callee); + }))); + return _context2.abrupt("return", this.doc._atomicQueue); + + case 2: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function remove() { + return _remove.apply(this, arguments); + } + + return remove; + }() /** * returns the data for the attachment */ ; - _proto.getData = function getData() { - var _this2 = this; + _proto.getData = + /*#__PURE__*/ + function () { + var _getData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var plainData, dataString, ret; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.doc.collection.storageInstance.getAttachmentData(this.doc.primary, this.id); - return this.doc.collection.pouch.getAttachment(this.doc.primary, this.id).then(function (data) { - if (shouldEncrypt(_this2.doc.collection.schema)) { - return _util.blobBufferUtil.toString(data).then(function (dataString) { - return _util.blobBufferUtil.createBlobBuffer(_this2.doc.collection._crypter._decryptValue(dataString), _this2.type); - }); - } else return data; - }); - }; + case 2: + plainData = _context3.sent; + + if (!shouldEncrypt(this.doc.collection.schema)) { + _context3.next = 11; + break; + } + + _context3.next = 6; + return _util.blobBufferUtil.toString(plainData); + + case 6: + dataString = _context3.sent; + ret = _util.blobBufferUtil.createBlobBuffer(this.doc.collection._crypter._decryptString(dataString), this.type); + return _context3.abrupt("return", ret); + + case 11: + return _context3.abrupt("return", plainData); + + case 12: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function getData() { + return _getData.apply(this, arguments); + } + + return getData; + }(); _proto.getStringData = function getStringData() { return this.getData().then(function (bufferBlob) { @@ -1232,14 +1334,13 @@ var RxAttachment = /*#__PURE__*/function () { exports.RxAttachment = RxAttachment; -function fromPouchDocument(id, pouchDocAttachment, rxDocument) { +function fromStorageInstanceResult(id, attachmentData, rxDocument) { return new RxAttachment({ doc: rxDocument, id: id, - type: pouchDocAttachment.content_type, - length: pouchDocAttachment.length, - digest: pouchDocAttachment.digest, - rev: pouchDocAttachment.revpos + type: attachmentData.type, + length: attachmentData.length, + digest: attachmentData.digest }); } @@ -1256,83 +1357,110 @@ function putAttachment(_x) { function _putAttachment() { - _putAttachment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(_ref3) { - var _this5 = this; + _putAttachment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(_ref4) { + var _this4 = this; var id, data, - _ref3$type, + _ref4$type, type, skipIfSame, - blobBuffer, - _args2 = arguments; + dataString, + encrypted, + _args5 = arguments; - return _regenerator["default"].wrap(function _callee2$(_context2) { + return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context5.prev = _context5.next) { case 0: - id = _ref3.id, data = _ref3.data, _ref3$type = _ref3.type, type = _ref3$type === void 0 ? 'text/plain' : _ref3$type; - skipIfSame = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : false; + id = _ref4.id, data = _ref4.data, _ref4$type = _ref4.type, type = _ref4$type === void 0 ? 'text/plain' : _ref4$type; + skipIfSame = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : true; ensureSchemaSupportsAttachments(this); + /** + * Then encryption plugin is only able to encrypt strings, + * so unpack as string first. + */ - if (shouldEncrypt(this.collection.schema)) { - data = this.collection._crypter._encryptValue(data); + if (!shouldEncrypt(this.collection.schema)) { + _context5.next = 9; + break; } - blobBuffer = _util.blobBufferUtil.createBlobBuffer(data, type); - this._atomicQueue = this._atomicQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { - var currentMeta, newHash; - return _regenerator["default"].wrap(function _callee$(_context) { + _context5.next = 6; + return _util.blobBufferUtil.toString(data); + + case 6: + dataString = _context5.sent; + encrypted = this.collection._crypter._encryptString(dataString); + data = _util.blobBufferUtil.createBlobBuffer(encrypted, 'text/plain'); + + case 9: + this._atomicQueue = this._atomicQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var currentMeta, newHash, docWriteData, useData, writeResult, attachmentData, attachment, newData; + return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { - switch (_context.prev = _context.next) { + switch (_context4.prev = _context4.next) { case 0: - if (!(skipIfSame && _this5._data._attachments && _this5._data._attachments[id])) { - _context.next = 7; + if (!(skipIfSame && _this4._data._attachments && _this4._data._attachments[id])) { + _context4.next = 7; break; } - currentMeta = _this5._data._attachments[id]; - _context.next = 4; - return (0, _pouchDb.pouchAttachmentBinaryHash)(data); + currentMeta = _this4._data._attachments[id]; + _context4.next = 4; + return _this4.collection.database.storage.hash(data); case 4: - newHash = _context.sent; + newHash = _context4.sent; - if (!(currentMeta.content_type === type && currentMeta.digest === newHash)) { - _context.next = 7; + if (!(currentMeta.type === type && currentMeta.digest === newHash)) { + _context4.next = 7; break; } - return _context.abrupt("return", _this5.getAttachment(id)); + return _context4.abrupt("return", _this4.getAttachment(id)); case 7: - return _context.abrupt("return", _this5.collection.pouch.putAttachment(_this5.primary, id, _this5._data._rev, blobBuffer, type).then(function () { - return _this5.collection.pouch.get(_this5.primary); - }).then(function (docData) { - var attachmentData = docData._attachments[id]; - var attachment = fromPouchDocument(id, attachmentData, _this5); - _this5._data._rev = docData._rev; - _this5._data._attachments = docData._attachments; - return resyncRxDocument(_this5).then(function () { - return attachment; - }); - })); - - case 8: + docWriteData = (0, _util.flatClone)(_this4._data); + docWriteData._attachments = (0, _util.flatClone)(docWriteData._attachments); + useData = typeof data === 'string' ? Buffer.from(data) : data; + docWriteData._attachments[id] = { + type: type, + data: useData + }; + _context4.next = 13; + return (0, _rxStorageHelper.writeSingle)(_this4.collection.storageInstance, { + previous: _this4._data, + document: docWriteData + }); + + case 13: + writeResult = _context4.sent; + attachmentData = writeResult._attachments[id]; + attachment = fromStorageInstanceResult(id, attachmentData, _this4); + newData = (0, _util.flatClone)(_this4._data); + newData._rev = writeResult._rev; + newData._attachments = writeResult._attachments; + + _this4._dataSync$.next(newData); + + return _context4.abrupt("return", attachment); + + case 21: case "end": - return _context.stop(); + return _context4.stop(); } } - }, _callee); + }, _callee4); }))); - return _context2.abrupt("return", this._atomicQueue); + return _context5.abrupt("return", this._atomicQueue); - case 7: + case 11: case "end": - return _context2.stop(); + return _context5.stop(); } } - }, _callee2, this); + }, _callee5, this); })); return _putAttachment.apply(this, arguments); } @@ -1344,7 +1472,7 @@ function getAttachment(id) { if (!docData._attachments || !docData._attachments[id]) return null; var attachmentData = docData._attachments[id]; - var attachment = fromPouchDocument(id, attachmentData, this); + var attachment = fromStorageInstanceResult(id, attachmentData, this); return attachment; } /** @@ -1353,16 +1481,19 @@ function getAttachment(id) { function allAttachments() { - var _this3 = this; + var _this2 = this; ensureSchemaSupportsAttachments(this); var docData = this._dataSync$.getValue(); // if there are no attachments, the field is missing - if (!docData._attachments) return []; + if (!docData._attachments) { + return []; + } + return Object.keys(docData._attachments).map(function (id) { - return fromPouchDocument(id, docData._attachments[id], _this3); + return fromStorageInstanceResult(id, docData._attachments[id], _this2); }); } @@ -1371,71 +1502,66 @@ function preMigrateDocument(_x2) { } function _preMigrateDocument() { - _preMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(data) { + _preMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(data) { var attachments, mustDecrypt, newAttachments; - return _regenerator["default"].wrap(function _callee4$(_context4) { + return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context7.prev = _context7.next) { case 0: attachments = data.docData._attachments; if (!attachments) { - _context4.next = 7; + _context7.next = 7; break; } mustDecrypt = !!shouldEncrypt(data.oldCollection.schema); newAttachments = {}; - _context4.next = 6; + _context7.next = 6; return Promise.all(Object.keys(attachments).map( /*#__PURE__*/function () { - var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(attachmentId) { + var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(attachmentId) { var attachment, docPrimary, rawAttachmentData; - return _regenerator["default"].wrap(function _callee3$(_context3) { + return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context6.prev = _context6.next) { case 0: attachment = attachments[attachmentId]; docPrimary = data.docData[data.oldCollection.schema.primaryPath]; - _context3.next = 4; - return data.oldCollection.pouchdb.getAttachment(docPrimary, attachmentId); + _context6.next = 4; + return data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId); case 4: - rawAttachmentData = _context3.sent; + rawAttachmentData = _context6.sent; if (!mustDecrypt) { - _context3.next = 9; + _context6.next = 9; break; } - _context3.next = 8; + _context6.next = 8; return _util.blobBufferUtil.toString(rawAttachmentData).then(function (dataString) { - return _util.blobBufferUtil.createBlobBuffer(data.oldCollection._crypter._decryptValue(dataString), attachment.content_type); + return _util.blobBufferUtil.createBlobBuffer(data.oldCollection._crypter._decryptString(dataString), attachment.type); }); case 8: - rawAttachmentData = _context3.sent; + rawAttachmentData = _context6.sent; case 9: newAttachments[attachmentId] = { - digest: attachment.digest, - length: attachment.length, - revpos: attachment.revpos, - content_type: attachment.content_type, - stub: false, - // set this to false because now we have the full data + type: attachment.type, data: rawAttachmentData }; case 10: case "end": - return _context3.stop(); + return _context6.stop(); } } - }, _callee3); + }, _callee6); })); return function (_x4) { - return _ref6.apply(this, arguments); + return _ref7.apply(this, arguments); }; }())); @@ -1448,10 +1574,10 @@ function _preMigrateDocument() { case 7: case "end": - return _context4.stop(); + return _context7.stop(); } } - }, _callee4); + }, _callee7); })); return _preMigrateDocument.apply(this, arguments); } @@ -1461,19 +1587,19 @@ function postMigrateDocument(_x3) { } function _postMigrateDocument() { - _postMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(action) { - return _regenerator["default"].wrap(function _callee5$(_context5) { + _postMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(_action) { + return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { - switch (_context5.prev = _context5.next) { + switch (_context8.prev = _context8.next) { case 0: - return _context5.abrupt("return"); + return _context8.abrupt("return"); case 1: case "end": - return _context5.stop(); + return _context8.stop(); } } - }, _callee5); + }, _callee8); })); return _postMigrateDocument.apply(this, arguments); } @@ -1487,18 +1613,21 @@ var prototypes = { proto.allAttachments = allAttachments; Object.defineProperty(proto, 'allAttachments$', { get: function allAttachments$() { - var _this4 = this; + var _this3 = this; return this._dataSync$.pipe((0, _operators.map)(function (data) { - if (!data['_attachments']) return {}; + if (!data['_attachments']) { + return {}; + } + return data['_attachments']; }), (0, _operators.map)(function (attachmentsData) { return Object.entries(attachmentsData); }), (0, _operators.map)(function (entries) { - return entries.map(function (_ref4) { - var id = _ref4[0], - attachmentData = _ref4[1]; - return fromPouchDocument(id, attachmentData, _this4); + return entries.map(function (_ref5) { + var id = _ref5[0], + attachmentData = _ref5[1]; + return fromStorageInstanceResult(id, attachmentData, _this3); }); })); } @@ -1523,7 +1652,8 @@ var RxDBAttachmentsPlugin = { exports.RxDBAttachmentsPlugin = RxDBAttachmentsPlugin; -},{"../pouch-db":37,"../rx-error":46,"./../rx-change-event":39,"./../util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"rxjs/operators":908}],13:[function(require,module,exports){ +}).call(this)}).call(this,require("buffer").Buffer) +},{"../rx-error":48,"../rx-storage-helper":52,"./../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"buffer":170,"rxjs/operators":908}],12:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -1575,7 +1705,53 @@ function checkMigrationStrategies(schema, migrationStrategies) { } -},{"../../rx-error":46,"../../rx-schema":48}],14:[function(require,module,exports){ +},{"../../rx-error":48,"../../rx-schema":51}],13:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validateDatabaseName = validateDatabaseName; + +var _rxError = require("../../rx-error"); + +var _util = require("../../util"); + +var validCouchDBStringRegexStr = '^[a-z][_$a-z0-9]*$'; +var validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr); +/** + * Validates that a given string is ok to be used with couchdb-collection-names. + * We only allow these strings as database- or collectionnames because it ensures + * that you later do not get in troubble when you want to use the database together witch couchdb. + * + * @link https://wiki.apache.org/couchdb/HTTP_database_API + * @throws {Error} + */ + +function validateDatabaseName(name) { + if (typeof name !== 'string' || name.length === 0) { + throw (0, _rxError.newRxTypeError)('UT1', { + name: name + }); + } // do not check, if foldername is given + + + if ((0, _util.isFolderPath)(name)) { + return true; + } + + if (!name.match(validCouchDBStringRegex)) { + throw (0, _rxError.newRxError)('UT2', { + regex: validCouchDBStringRegexStr, + givenName: name + }); + } + + return true; +} + + +},{"../../rx-error":48,"../../util":58}],14:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -1628,7 +1804,7 @@ function checkOrmMethods(statics) { } -},{"../../rx-error":46,"./entity-properties":17}],15:[function(require,module,exports){ +},{"../../rx-error":48,"./entity-properties":17}],15:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -1668,7 +1844,7 @@ function checkQuery(args) { } -},{"../../rx-error":46}],16:[function(require,module,exports){ +},{"../../rx-error":48}],16:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -1700,8 +1876,9 @@ var _entityProperties = require("./entity-properties"); * @throws {Error} */ function checkFieldNameRegex(fieldName) { - if (fieldName === '') return; - if (fieldName === '_id') return; + if (fieldName === '') return; // TODO why is the fieldname allowed to be empty string? + + if (fieldName === '_deleted') return; if (['properties', 'language'].includes(fieldName)) { throw (0, _rxError.newRxError)('SC23', { @@ -1796,7 +1973,7 @@ function validateFieldsDeep(jsonSchema) { if (!isNested) { // check underscore fields if (fieldName.charAt(0) === '_') { - if (fieldName === '_id' && schemaObj.primary) { + if (fieldName === '_deleted') { return; } @@ -1849,6 +2026,12 @@ function getSchemaPropertyRealPath(shortPath) { function checkSchema(jsonSchema) { + if (!jsonSchema.primaryKey) { + throw (0, _rxError.newRxError)('SC30', { + schema: jsonSchema + }); + } + if (!jsonSchema.hasOwnProperty('properties')) { throw (0, _rxError.newRxError)('SC29', { schema: jsonSchema @@ -1870,20 +2053,11 @@ function checkSchema(jsonSchema) { } validateFieldsDeep(jsonSchema); - var primaryPath; Object.keys(jsonSchema.properties).forEach(function (key) { var value = jsonSchema.properties[key]; // check primary - if (value.primary) { - if (primaryPath) { - throw (0, _rxError.newRxError)('SC12', { - value: value - }); - } - - primaryPath = key; - - if (value.index) { + if (key === jsonSchema.primaryKey) { + if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) { throw (0, _rxError.newRxError)('SC13', { value: value }); @@ -1895,7 +2069,7 @@ function checkSchema(jsonSchema) { }); } - if (value.encrypted) { + if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) { throw (0, _rxError.newRxError)('SC15', { value: value }); @@ -2071,7 +2245,7 @@ function checkSchema(jsonSchema) { } -},{"../../rx-error":46,"../../util":56,"./entity-properties":17,"@babel/runtime/helpers/interopRequireDefault":65,"object-path":630}],17:[function(require,module,exports){ +},{"../../rx-error":48,"../../util":58,"./entity-properties":17,"@babel/runtime/helpers/interopRequireDefault":67,"object-path":629}],17:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -2144,7 +2318,7 @@ function rxDocumentProperties() { } -},{"../../rx-collection":41,"../../rx-database":43,"../../rx-document":45}],18:[function(require,module,exports){ +},{"../../rx-collection":44,"../../rx-database":45,"../../rx-document":47}],18:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -2163,6 +2337,9 @@ var ERROR_MESSAGES = { UT2: "collection- and database-names must match the regex\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\'", UT3: 'replication-direction must either be push or pull or both. But not none', UT4: 'given leveldown is no valid adapter', + // plugins + PL1: 'Given plugin is not RxDB plugin. Pouchdb plugins must be added via addPouchPlugin()', + PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.', // pouch-db.js P1: 'PouchDB.getBatch: limit must be > 2', // rx-query @@ -2188,19 +2365,19 @@ var ERROR_MESSAGES = { MQ8: 'Can\'t mix sort syntaxes. Use either array or object', // rx-database DB1: 'RxDocument.prepare(): another instance on this adapter has a different password', - DB2: 'RxDatabase.collection(): collection-names cannot start with underscore _', - DB3: 'RxDatabase.collection(): collection already exists. use myDatabase.[collectionName] to get it', - DB4: 'RxDatabase.collection(): schema is missing', - DB5: 'RxDatabase.collection(): collection-name not allowed', - DB6: 'RxDatabase.collection(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', - DB7: 'RxDatabase.collection(): schema encrypted but no password given', + DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _', + DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it', + DB4: 'RxDatabase.addCollections(): schema is missing', + DB5: 'RxDatabase.addCollections(): collection-name not allowed', + DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', + DB7: 'RxDatabase.addCollections(): schema encrypted but no password given', DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\n' + 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional', DB9: 'RxDatabase.create(): Adapter not added. Use RxDB.plugin(require(\'pouchdb-adapter-[adaptername]\');', DB10: 'RxDatabase.create(): To use leveldown-adapters, you have to add the leveldb-plugin. Use RxDB.plugin(require(\'pouchdb-adapter-leveldb\'));', DB11: 'RxDatabase.create(): Invalid db-name, folder-paths must not have an ending slash', // rx-collection COL1: 'RxDocument.insert() You cannot insert an existing document', - COL2: 'RxCollection.insert() do not provide ._id when it is not the primary key', + // removed in 10.0.0 - COL2: 'RxCollection.insert() do not provide ._id when it is not the primary key', COL3: 'RxCollection.upsert() does not work without primary', COL4: 'RxCollection.atomicUpsert() does not work without primary', COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)', @@ -2230,7 +2407,7 @@ var ERROR_MESSAGES = { DOC9: 'final fields cannot be modified', DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected', DOC11: 'RxDocument.save(): cant save deleted document', - DOC12: 'RxDocument.save(): error', + // removed in 10.0.0 DOC12: 'RxDocument.save(): error', DOC13: 'RxDocument.remove(): Document is already deleted', DOC14: 'RxDocument.destroy() does not exist', DOC15: 'query cannot be an array', @@ -2247,8 +2424,8 @@ var ERROR_MESSAGES = { EN2: 'validatePassword: min-length of password not complied', // plugins/json-dump.js JD1: 'You must create the collections before you can import their data', - JD2: 'RxCollection.importDump(): the imported json relies on a different schema', - JD3: 'RxCollection.importDump(): json.passwordHash does not match the own', + JD2: 'RxCollection.importJSON(): the imported json relies on a different schema', + JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own', // plugins/leader-election.js // plugins/local-documents.js LD1: 'RxDocument.allAttachments$ cant use attachments on local documents', @@ -2260,10 +2437,10 @@ var ERROR_MESSAGES = { LD7: 'Local document already exists', // plugins/replication.js RC1: 'Replication: already added', - RC2: 'RxCollection.sync() query must be from the same RxCollection', - RC3: 'RxCollection.sync() Do not use a collection\'s pouchdb as remote, use the collection instead', - RC4: 'RxReplicationState.awaitInitialReplication() cannot await inital replication when live: true', - RC5: 'RxReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance', + RC2: 'RxCollection.syncCouchDB() query must be from the same RxCollection', + RC3: 'RxCollection.syncCouchDB() Do not use a collection\'s pouchdb as remote, use the collection instead', + RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication when live: true', + RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance', // plugins/dev-mode/check-schema.js SC1: 'fieldnames do not match the regex', SC2: 'SchemaCheck: name \'item\' reserved for array-fields', @@ -2274,7 +2451,7 @@ var ERROR_MESSAGES = { SC8: 'SchemaCheck: first level-fields cannot start with underscore _', SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically', SC11: 'SchemaCheck: schema needs a number >=0 as version', - SC12: 'SchemaCheck: primary can only be defined once', + // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once', SC13: 'SchemaCheck: primary is always index, do not declare it as index', SC14: 'SchemaCheck: primary is always unique, do not declare it as index', SC15: 'SchemaCheck: primary cannot be encrypted', @@ -2292,17 +2469,25 @@ var ERROR_MESSAGES = { SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level', SC28: 'SchemaCheck: encrypted fields is not defined in the schema', SC29: 'SchemaCheck: missing object key \'properties\'', + SC30: 'SchemaCheck: primaryKey is required', // plugins/dev-mode DEV1: 'dev-mode added multiple times, ' + 'this is likely because you have mixed up the import from the the plugins/core and the full RxDB', // plugins/validate.js VD1: 'Sub-schema not found, does the schemaPath exists in your schema?', VD2: 'object does not match schema', // plugins/in-memory.js - IM1: 'InMemory: Memory-Adapter must be added. Use RxDB.plugin(require(\'pouchdb-adapter-memory\'));', + IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\'pouchdb-adapter-memory\'));', IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead', // plugins/server.js - S1: 'You cannot create collections after calling RxDatabase.server()' // plugins/replication-graphql.js + S1: 'You cannot create collections after calling RxDatabase.server()', + // plugins/replication-graphql.js + /** + * Should never be thrown, use this for + * null checks etc. so you do not have to increase the + * build size with error message strings. + */ + SNH: 'This should never happen' }; exports.ERROR_MESSAGES = ERROR_MESSAGES; @@ -2314,8 +2499,10 @@ Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { + deepFreezeWhenDevMode: true, RxDBDevModePlugin: true }; +exports.deepFreezeWhenDevMode = deepFreezeWhenDevMode; exports.RxDBDevModePlugin = void 0; var _errorMessages = require("./error-messages"); @@ -2344,6 +2531,38 @@ var _checkQuery = require("./check-query"); var _rxError = require("../../rx-error"); +var _checkNames = require("./check-names"); + +Object.keys(_checkNames).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _checkNames[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _checkNames[key]; + } + }); +}); + +var deepFreeze = require('deep-freeze'); +/** + * Deep freezes and object when in dev-mode. + * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode. + * Also we can ensure the readonly state via typescript + * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ + + +function deepFreezeWhenDevMode(obj) { + // direct return if falsy + if (!obj) { + return obj; + } + + return deepFreeze(obj); +} + var DEV_MODE_PLUGIN_NAME = 'dev-mode'; var RxDBDevModePlugin = { name: DEV_MODE_PLUGIN_NAME, @@ -2352,6 +2571,7 @@ var RxDBDevModePlugin = { isDevMode: function isDevMode() { return true; }, + deepFreezeWhenDevMode: deepFreezeWhenDevMode, tunnelErrorMessage: function tunnelErrorMessage(code) { if (!_errorMessages.ERROR_MESSAGES[code]) { console.error('RxDB: Error-Code not known: ' + code); @@ -2412,7 +2632,7 @@ var RxDBDevModePlugin = { exports.RxDBDevModePlugin = RxDBDevModePlugin; -},{"../../rx-error":46,"./check-migration-strategies":13,"./check-orm":14,"./check-query":15,"./check-schema":16,"./error-messages":18,"./unallowed-properties":20}],20:[function(require,module,exports){ +},{"../../rx-error":48,"./check-migration-strategies":12,"./check-names":13,"./check-orm":14,"./check-query":15,"./check-schema":16,"./error-messages":18,"./unallowed-properties":20,"deep-freeze":498}],20:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -2425,10 +2645,10 @@ var _rxError = require("../../rx-error"); var _entityProperties = require("./entity-properties"); -var _pouchDb = require("../../pouch-db"); - var _util = require("../../util"); +var _checkNames = require("./check-names"); + /** * if the name of a collection * clashes with a property of RxDatabase, @@ -2443,12 +2663,7 @@ function ensureCollectionNameValid(args) { } function ensureDatabaseNameIsValid(args) { - /** - * Not all strings can be used as couchdb collection name - * So we only allow couchdb-valid string as databse name - * which solves some strange bugs. - */ - (0, _pouchDb.validateCouchDBString)(args.name); + (0, _checkNames.validateDatabaseName)(args.name); /** * The server-plugin has problems when a path with and ending slash is given * So we do not allow this. @@ -2465,7 +2680,7 @@ function ensureDatabaseNameIsValid(args) { } -},{"../../pouch-db":37,"../../rx-error":46,"../../util":56,"./entity-properties":17}],21:[function(require,module,exports){ +},{"../../rx-error":48,"../../util":58,"./check-names":13,"./entity-properties":17}],21:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -2478,6 +2693,10 @@ exports.decrypt = decrypt; exports.storePasswordHashIntoDatabase = storePasswordHashIntoDatabase; exports.RxDBEncryptionPlugin = exports.overwritable = exports.prototypes = exports.rxdb = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + var _aes = _interopRequireDefault(require("crypto-js/aes")); var cryptoEnc = _interopRequireWildcard(require("crypto-js/enc-utf8")); @@ -2486,6 +2705,8 @@ var _rxError = require("../rx-error"); var _util = require("../util"); +var _rxStorageHelper = require("../rx-storage-helper"); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } @@ -2509,13 +2730,13 @@ function decrypt(cipherText, password) { return decrypted.toString(cryptoEnc); } -var _encryptValue = function _encryptValue(value) { - return encrypt(JSON.stringify(value), this.password); +var _encryptString = function _encryptString(value) { + return encrypt(value, this.password); }; -var _decryptValue = function _decryptValue(encryptedValue) { +var _decryptString = function _decryptString(encryptedValue) { var decrypted = decrypt(encryptedValue, this.password); - return JSON.parse(decrypted); + return decrypted; }; /** @@ -2523,40 +2744,77 @@ var _decryptValue = function _decryptValue(encryptedValue) { * to ensure there is/was no other instance with a different password * which would cause strange side effects when both instances save into the same db */ -function storePasswordHashIntoDatabase(rxDatabase) { - if (!rxDatabase.password) { - return Promise.resolve(false); - } +function storePasswordHashIntoDatabase(_x) { + return _storePasswordHashIntoDatabase.apply(this, arguments); +} - var pwHash = (0, _util.hash)(rxDatabase.password); - return rxDatabase.internalStore.get(_util.LOCAL_PREFIX + 'pwHash')["catch"](function () { - return null; - }).then(function (pwHashDoc) { - /** - * if pwHash was not saved, we save it, - * this operation might throw because another instance runs save at the same time, - */ - if (!pwHashDoc) { - return rxDatabase.internalStore.put({ - _id: _util.LOCAL_PREFIX + 'pwHash', - value: pwHash - })["catch"](function () { - return null; - }).then(function () { - return true; - }); - } else if (pwHash !== pwHashDoc.value) { - // different hash was already set by other instance - return rxDatabase.destroy().then(function () { - throw (0, _rxError.newRxError)('DB1', { - passwordHash: (0, _util.hash)(rxDatabase.password), - existingPasswordHash: pwHashDoc.value - }); - }); - } +function _storePasswordHashIntoDatabase() { + _storePasswordHashIntoDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(rxDatabase) { + var pwHash, pwHashDocumentId, pwHashDoc, docData; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (rxDatabase.password) { + _context.next = 2; + break; + } - return true; - }); + return _context.abrupt("return", Promise.resolve(false)); + + case 2: + pwHash = (0, _util.hash)(rxDatabase.password); + pwHashDocumentId = 'pwHash'; + _context.next = 6; + return (0, _rxStorageHelper.findLocalDocument)(rxDatabase.localDocumentsStore, pwHashDocumentId); + + case 6: + pwHashDoc = _context.sent; + + if (pwHashDoc) { + _context.next = 14; + break; + } + + docData = { + _id: pwHashDocumentId, + value: pwHash, + _attachments: {} + }; + _context.next = 11; + return rxDatabase.localDocumentsStore.bulkWrite([{ + document: docData + }]); + + case 11: + return _context.abrupt("return", true); + + case 14: + if (!(pwHash !== pwHashDoc.value)) { + _context.next = 20; + break; + } + + _context.next = 17; + return rxDatabase.destroy(); + + case 17: + throw (0, _rxError.newRxError)('DB1', { + passwordHash: (0, _util.hash)(rxDatabase.password), + existingPasswordHash: pwHashDoc.value + }); + + case 20: + return _context.abrupt("return", true); + + case 21: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _storePasswordHashIntoDatabase.apply(this, arguments); } var rxdb = true; @@ -2566,8 +2824,8 @@ var prototypes = { * set crypto-functions for the Crypter.prototype */ Crypter: function Crypter(proto) { - proto._encryptValue = _encryptValue; - proto._decryptValue = _decryptValue; + proto._encryptString = _encryptString; + proto._decryptString = _decryptString; } }; exports.prototypes = prototypes; @@ -2602,7 +2860,7 @@ var RxDBEncryptionPlugin = { exports.RxDBEncryptionPlugin = RxDBEncryptionPlugin; -},{"../rx-error":46,"../util":56,"@babel/runtime/helpers/interopRequireDefault":65,"crypto-js/aes":485,"crypto-js/enc-utf8":489}],22:[function(require,module,exports){ +},{"../rx-error":48,"../rx-storage-helper":52,"../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"crypto-js/aes":486,"crypto-js/enc-utf8":490}],22:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -2614,9 +2872,14 @@ exports.replicateExistingDocuments = replicateExistingDocuments; exports.setIndexes = setIndexes; exports.streamChangedDocuments = streamChangedDocuments; exports.applyChangedDocumentToPouch = applyChangedDocumentToPouch; -exports.spawnInMemory = spawnInMemory; +exports.inMemory = inMemory; +exports.prepareInMemoryRxCollection = prepareInMemoryRxCollection; exports.RxDBInMemoryPlugin = exports.prototypes = exports.rxdb = exports.InMemoryRxCollection = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); @@ -2629,7 +2892,7 @@ var _rxCollection = require("../rx-collection"); var _util = require("../util"); -var _core = require("../core"); +var _pouchdb = require("../plugins/pouchdb"); var _crypter = require("../crypter"); @@ -2637,13 +2900,11 @@ var _changeEventBuffer = require("../change-event-buffer"); var _rxSchema = require("../rx-schema"); -var _pouchDb = require("../pouch-db"); - var _rxError = require("../rx-error"); -var _rxStoragePouchdb = require("../rx-storage-pouchdb"); +var _rxChangeEvent = require("../rx-change-event"); -var _watchForChanges = require("../plugins/watch-for-changes"); +var _rxCollectionHelper = require("../rx-collection-helper"); /** * This plugin adds RxCollection.inMemory() @@ -2651,8 +2912,6 @@ var _watchForChanges = require("../plugins/watch-for-changes"); * So you can do faster queries and also query over encrypted fields. * Writes will still run on the original collection */ -// add the watch-for-changes-plugin -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); var collectionCacheMap = new WeakMap(); var collectionPromiseCacheMap = new WeakMap(); var BULK_DOC_OPTIONS = { @@ -2665,20 +2924,18 @@ var BULK_DOC_OPTIONS_FALSE = { var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { (0, _inheritsLoose2["default"])(InMemoryRxCollection, _RxCollectionBase); - function InMemoryRxCollection(parentCollection) { + function InMemoryRxCollection(parentCollection, pouchSettings) { var _this; - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _this = _RxCollectionBase.call(this, parentCollection.database, parentCollection.name, toCleanSchema(parentCollection.schema), pouchSettings, // pouchSettings {}, parentCollection._methods) || this; _this._eventCounter = 0; + _this.parentCollection = parentCollection; + _this.pouchSettings = pouchSettings; _this._isInMemory = true; - _this._parentCollection = parentCollection; - - _this._parentCollection.onDestroy.then(function () { + parentCollection.onDestroy.then(function () { return _this.destroy(); }); - _this._crypter = (0, _crypter.createCrypter)(_this.database.password, _this.schema); _this._changeStreams = []; /** @@ -2689,9 +2946,10 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _this.onDestroy.then(function () { _this._changeStreams.forEach(function (stream) { return stream.cancel(); - }); + }); // delete all data - _this.pouch.destroy(); + + _this.storageInstance.internals.pouch.destroy(); }); // add orm functions and options from parent @@ -2705,8 +2963,6 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { } }); }); - var storage = (0, _rxStoragePouchdb.getRxStoragePouchDb)('memory'); - _this.pouch = storage.createStorageInstance('rxdb-in-memory', (0, _util.randomCouchString)(10), 0); _this._observable$ = new _rxjs.Subject(); _this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)((0, _assertThisInitialized2["default"])(_this)); var parentProto = Object.getPrototypeOf(parentCollection); @@ -2722,7 +2978,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _proto.prepareChild = function prepareChild() { var _this2 = this; - return setIndexes(this.schema, this.pouch).then(function () { + return setIndexes(this.schema, this.storageInstance.internals.pouch).then(function () { _this2._subs.push(_this2._observable$.subscribe(function (cE) { // when data changes, send it to RxDocument in docCache var doc = _this2._docCache.get(cE.documentId); @@ -2731,23 +2987,13 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { })); }) // initial sync parent's docs to own .then(function () { - return replicateExistingDocuments(_this2._parentCollection, _this2); + return replicateExistingDocuments(_this2.parentCollection, _this2); }).then(function () { - /** - * call watchForChanges() on both sides, - * to ensure none-rxdb-changes like replication - * will fire into the change-event-stream - */ - _this2._parentCollection.watchForChanges(); - - _this2.watchForChanges(); /** * create an ongoing replications between both sides */ - - var thisToParentSub = streamChangedDocuments(_this2).pipe((0, _operators.mergeMap)(function (doc) { - return applyChangedDocumentToPouch(_this2._parentCollection, doc).then(function () { + return applyChangedDocumentToPouch(_this2.parentCollection, doc).then(function () { return doc['_rev']; }); })).subscribe(function (changeRev) { @@ -2758,7 +3004,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _this2._subs.push(thisToParentSub); - var parentToThisSub = streamChangedDocuments(_this2._parentCollection).subscribe(function (doc) { + var parentToThisSub = streamChangedDocuments(_this2.parentCollection).subscribe(function (doc) { return applyChangedDocumentToPouch(_this2, doc); }); @@ -2774,7 +3020,10 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { _proto.awaitPersistence = function awaitPersistence() { var _this3 = this; - if (this._nonPersistentRevisions.size === 0) return Promise.resolve(); + if (this._nonPersistentRevisions.size === 0) { + return Promise.resolve(); + } + return (0, _rxjs.firstValueFrom)(this._nonPersistentRevisionsSubject.pipe((0, _operators.filter)(function () { return _this3._nonPersistentRevisions.size === 0; }))); @@ -2797,7 +3046,9 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { }; _proto.$emit = function $emit(changeEvent) { - if (this._changeEventBuffer.hasChangeWithRevision(changeEvent.documentData && changeEvent.documentData._rev)) { + var doc = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + + if (this._changeEventBuffer.hasChangeWithRevision(doc && doc._rev)) { return; } @@ -2808,7 +3059,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { if (this._eventCounter === 10) { this._eventCounter = 0; - this.pouch.compact(); + this.storageInstance.internals.pouch.compact(); } } /** @@ -2818,7 +3069,7 @@ var InMemoryRxCollection = /*#__PURE__*/function (_RxCollectionBase) { */ ; - _proto.sync = function sync() { + _proto.syncCouchDB = function syncCouchDB() { throw (0, _rxError.newRxError)('IM2'); }; @@ -2837,7 +3088,6 @@ exports.InMemoryRxCollection = InMemoryRxCollection; function toCleanSchema(rxSchema) { var newSchemaJson = (0, _util.clone)(rxSchema.jsonSchema); newSchemaJson.keyCompression = false; - delete newSchemaJson.properties._id; delete newSchemaJson.properties._rev; delete newSchemaJson.properties._attachments; @@ -2860,7 +3110,8 @@ function toCleanSchema(rxSchema) { function replicateExistingDocuments(fromCollection, toCollection) { - return fromCollection.pouch.allDocs({ + var pouch = fromCollection.storageInstance.internals.pouch; + return pouch.allDocs({ attachments: false, include_docs: true }).then(function (allRows) { @@ -2870,14 +3121,15 @@ function replicateExistingDocuments(fromCollection, toCollection) { return !doc.language; }) // do not replicate design-docs .map(function (doc) { - return fromCollection._handleFromPouch(doc); + return (0, _rxCollectionHelper._handleFromStorageInstance)(fromCollection, doc); }) // swap back primary because keyCompression:false .map(function (doc) { - return fromCollection.schema.swapPrimaryToId(doc); + var primaryKey = fromCollection.schema.primaryPath; + return (0, _pouchdb.pouchSwapPrimaryToId)(primaryKey, doc); }); if (docs.length === 0) return Promise.resolve([]); // nothing to replicate else { - return toCollection.pouch.bulkDocs({ + return toCollection.storageInstance.internals.pouch.bulkDocs({ docs: docs }, BULK_DOC_OPTIONS_FALSE).then(function () { return docs; @@ -2915,8 +3167,12 @@ function streamChangedDocuments(rxCollection) { var prevFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (_i) { return true; }; - if (!rxCollection._doNotEmitSet) rxCollection._doNotEmitSet = new Set(); - var observable = (0, _rxjs.fromEvent)(rxCollection.pouch.changes({ + + if (!rxCollection._doNotEmitSet) { + rxCollection._doNotEmitSet = new Set(); + } + + var observable = (0, _rxjs.fromEvent)(rxCollection.storageInstance.internals.pouch.changes({ since: 'now', live: true, include_docs: true @@ -2933,11 +3189,19 @@ function streamChangedDocuments(rxCollection) { (0, _operators.filter)(function (change) { // changes on the doNotEmit-list shell not be fired var emitFlag = change.id + ':' + change.doc._rev; - if (rxCollection._doNotEmitSet.has(emitFlag)) return false;else return true; + + if (rxCollection._doNotEmitSet.has(emitFlag)) { + return false; + } else { + return true; + } }), (0, _operators.filter)(function (change) { return prevFilter(change); }), (0, _operators.map)(function (change) { - return rxCollection._handleFromPouch(change.doc); + return (0, _rxCollectionHelper._handleFromStorageInstance)(rxCollection, change.doc); + }), (0, _operators.map)(function (d) { + var primaryKey = rxCollection.schema.primaryPath; + return (0, _pouchdb.pouchSwapIdToPrimary)(primaryKey, d); })); return observable; } @@ -2948,17 +3212,20 @@ function streamChangedDocuments(rxCollection) { function applyChangedDocumentToPouch(rxCollection, docData) { - if (!rxCollection._doNotEmitSet) rxCollection._doNotEmitSet = new Set(); - - var transformedDoc = rxCollection._handleToPouch(docData); + if (!rxCollection._doNotEmitSet) { + rxCollection._doNotEmitSet = new Set(); + } - return rxCollection.pouch.get(transformedDoc._id).then(function (oldDoc) { + var primaryKey = rxCollection.schema.primaryPath; + var transformedDoc = (0, _rxCollectionHelper._handleToStorageInstance)(rxCollection, docData); + transformedDoc = (0, _pouchdb.pouchSwapPrimaryToId)(primaryKey, transformedDoc); + return rxCollection.storageInstance.internals.pouch.get(transformedDoc._id).then(function (oldDoc) { return transformedDoc._rev = oldDoc._rev; })["catch"](function () { // doc not found, do not use a revision delete transformedDoc._rev; }).then(function () { - return rxCollection.pouch.bulkDocs({ + return rxCollection.storageInstance.internals.pouch.bulkDocs({ docs: [transformedDoc] }, BULK_DOC_OPTIONS); }).then(function (bulkRet) { @@ -2984,36 +3251,105 @@ var INIT_DONE = false; * called in the proto of RxCollection */ -function spawnInMemory() { - var _this5 = this; +function inMemory() { + return _inMemory.apply(this, arguments); +} - if (!INIT_DONE) { - INIT_DONE = true; // ensure memory-adapter is added +function _inMemory() { + _inMemory = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var _this5 = this; - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.memory) throw (0, _rxError.newRxError)('IM1'); - } + var col, preparePromise; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (INIT_DONE) { + _context.next = 4; + break; + } - if (collectionCacheMap.has(this)) { - // already exists for this collection -> wait until synced - return collectionPromiseCacheMap.get(this).then(function () { - return collectionCacheMap.get(_this5); - }); - } + INIT_DONE = true; // ensure memory-adapter is added - var col = new InMemoryRxCollection(this); - var preparePromise = col.prepareChild(); - collectionCacheMap.set(this, col); - collectionPromiseCacheMap.set(this, preparePromise); - return preparePromise.then(function () { - return col; - }); + if (!(!_pouchdb.PouchDB.adapters || !_pouchdb.PouchDB.adapters.memory)) { + _context.next = 4; + break; + } + + throw (0, _rxError.newRxError)('IM1'); + + case 4: + if (!collectionCacheMap.has(this)) { + _context.next = 6; + break; + } + + return _context.abrupt("return", collectionPromiseCacheMap.get(this).then(function () { + return collectionCacheMap.get(_this5); + })); + + case 6: + col = new InMemoryRxCollection(this); + _context.next = 9; + return prepareInMemoryRxCollection(col); + + case 9: + preparePromise = col.prepareChild(); + collectionCacheMap.set(this, col); + collectionPromiseCacheMap.set(this, preparePromise); + return _context.abrupt("return", preparePromise.then(function () { + return col; + })); + + case 13: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + return _inMemory.apply(this, arguments); +} + +function prepareInMemoryRxCollection(_x) { + return _prepareInMemoryRxCollection.apply(this, arguments); +} + +function _prepareInMemoryRxCollection() { + _prepareInMemoryRxCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(instance) { + var memoryStorage; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + memoryStorage = (0, _pouchdb.getRxStoragePouch)('memory', {}); + _context2.next = 3; + return memoryStorage.createStorageInstance({ + databaseName: 'rxdb-in-memory', + collectionName: (0, _util.randomCouchString)(10), + schema: instance.schema.jsonSchema, + options: instance.pouchSettings + }); + + case 3: + instance.storageInstance = _context2.sent; + instance.pouch = instance.storageInstance.internals.pouch; + + case 5: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _prepareInMemoryRxCollection.apply(this, arguments); } var rxdb = true; exports.rxdb = rxdb; var prototypes = { RxCollection: function RxCollection(proto) { - proto.inMemory = spawnInMemory; + proto.inMemory = inMemory; } }; exports.prototypes = prototypes; @@ -3025,7 +3361,7 @@ var RxDBInMemoryPlugin = { exports.RxDBInMemoryPlugin = RxDBInMemoryPlugin; -},{"../change-event-buffer":2,"../core":3,"../crypter":4,"../plugins/watch-for-changes":36,"../pouch-db":37,"../rx-collection":41,"../rx-error":46,"../rx-schema":48,"../rx-storage-pouchdb":49,"../util":56,"@babel/runtime/helpers/assertThisInitialized":59,"@babel/runtime/helpers/inheritsLoose":64,"@babel/runtime/helpers/interopRequireDefault":65,"rxjs":684,"rxjs/operators":908}],23:[function(require,module,exports){ +},{"../change-event-buffer":2,"../crypter":4,"../plugins/pouchdb":32,"../rx-change-event":42,"../rx-collection":44,"../rx-collection-helper":43,"../rx-error":48,"../rx-schema":51,"../util":58,"@babel/runtime/helpers/assertThisInitialized":61,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/inheritsLoose":66,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"rxjs":684,"rxjs/operators":908}],23:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -3039,7 +3375,7 @@ var _rxQuery = require("../rx-query"); var _rxError = require("../rx-error"); -var _rxChangeEvent = require("../rx-change-event"); +var _rxCollectionHelper = require("../rx-collection-helper"); /** * this plugin adds the json export/import capabilities to RxDB @@ -3070,7 +3406,7 @@ function dumpRxDatabase() { return _this.collections[colName]; }); return Promise.all(useCollections.map(function (col) { - return col.dump(decrypted); + return col.exportJSON(decrypted); })).then(function (cols) { json.collections = cols; return json; @@ -3097,7 +3433,7 @@ var importDumpRxDatabase = function importDumpRxDatabase(dump) { } return Promise.all(dump.collections.map(function (colDump) { - return _this2.collections[colDump.name].importDump(colDump); + return _this2.collections[colDump.name].importJSON(colDump); })); }; @@ -3118,7 +3454,7 @@ var dumpRxCollection = function dumpRxCollection() { } var query = (0, _rxQuery.createRxQuery)('find', (0, _rxQuery._getDefaultQuery)(this), this); - return this._pouchFind(query, undefined, encrypted).then(function (docs) { + return this._queryStorageInstance(query, undefined, encrypted).then(function (docs) { json.docs = docs.map(function (docData) { delete docData._rev; delete docData._attachments; @@ -3153,23 +3489,17 @@ function importDumpRxCollection(exportedJSON) { }) // validate schema .map(function (doc) { return _this3.schema.validate(doc); - }) // transform - .map(function (doc) { - return _this3._handleToPouch(doc); }); var startTime; return this.database.lockedRun( // write to disc function () { startTime = (0, _util.now)(); - return _this3.pouch.bulkDocs(docs); - }).then(function () { - var endTime = (0, _util.now)(); - docs.forEach(function (doc) { - // emit change events - var emitEvent = (0, _rxChangeEvent.createInsertEvent)(_this3, doc, startTime, endTime); - - _this3.$emit(emitEvent); + var writeMe = docs.map(function (doc) { + return { + document: (0, _rxCollectionHelper._handleToStorageInstance)(_this3, doc) + }; }); + return _this3.storageInstance.bulkWrite(writeMe); }); } @@ -3177,12 +3507,12 @@ var rxdb = true; exports.rxdb = rxdb; var prototypes = { RxDatabase: function RxDatabase(proto) { - proto.dump = dumpRxDatabase; - proto.importDump = importDumpRxDatabase; + proto.exportJSON = dumpRxDatabase; + proto.importJSON = importDumpRxDatabase; }, RxCollection: function RxCollection(proto) { - proto.dump = dumpRxCollection; - proto.importDump = importDumpRxCollection; + proto.exportJSON = dumpRxCollection; + proto.importJSON = importDumpRxCollection; } }; exports.prototypes = prototypes; @@ -3197,113 +3527,151 @@ var RxDBJsonDumpPlugin = { exports.RxDBJsonDumpPlugin = RxDBJsonDumpPlugin; -},{"../rx-change-event":39,"../rx-error":46,"../rx-query":47,"../util":56}],24:[function(require,module,exports){ +},{"../rx-collection-helper":43,"../rx-error":48,"../rx-query":49,"../util":58}],24:[function(require,module,exports){ "use strict"; -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); - Object.defineProperty(exports, "__esModule", { value: true }); -exports.create = create; -exports.RxDBKeyCompressionPlugin = exports.overwritable = exports.prototypes = exports.rxdb = exports.KeyCompressor = void 0; - -var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); +exports.createCompressionState = createCompressionState; +exports.getCompressionStateByStorageInstance = getCompressionStateByStorageInstance; +exports.RxDBKeyCompressionPlugin = exports.overwritable = exports.prototypes = exports.rxdb = void 0; var _jsonschemaKeyCompression = require("jsonschema-key-compression"); -var _util = require("../util"); - /** * this plugin adds the keycompression-capabilities to rxdb * if you dont use this, ensure that you set disableKeyComression to false in your schema */ -var KeyCompressor = /*#__PURE__*/function () { - function KeyCompressor(schema) { - this.schema = schema; - } - /** - * @overwrites itself on the first call - */ - - var _proto = KeyCompressor.prototype; +/** + * Cache the compression table and the compressed schema + * by the storage instance for better performance. + */ +var COMPRESSION_STATE_BY_COLLECTION = new WeakMap(); +function createCompressionState(schema) { + var primaryPath = schema.primaryKey; + var table = (0, _jsonschemaKeyCompression.createCompressionTable)(schema, _jsonschemaKeyCompression.DEFAULT_COMPRESSION_FLAG, [ /** - * compress the keys of an object via the compression-table + * Do not compress the primary path + * to make it easier to debug errors. */ - _proto.compress = function compress(obj) { - if (!this.schema.doKeyCompression()) { - return obj; - } else { - return (0, _jsonschemaKeyCompression.compressObject)(this.table, obj); - } - }; - - _proto.decompress = function decompress(compressedObject) { - if (!this.schema.doKeyCompression()) { - return compressedObject; - } else { - return (0, _jsonschemaKeyCompression.decompressObject)(this.table, compressedObject); - } - } + primaryPath, '_rev', '_attachments', '_deleted']); + var compressedSchema = (0, _jsonschemaKeyCompression.createCompressedJsonSchema)(table, schema); /** - * get the full compressed-key-path of a object-path + * the key compression module does not know about indexes + * in the schema, so we have to also compress them here. */ - ; - _proto.transformKey = function transformKey(objectPath) { - return (0, _jsonschemaKeyCompression.compressedPath)(this.table, objectPath); // > '|a.|b' + if (schema.indexes) { + var newIndexes = schema.indexes.map(function (idx) { + if (Array.isArray(idx)) { + return idx.map(function (subIdx) { + return (0, _jsonschemaKeyCompression.compressedPath)(table, subIdx); + }); + } else { + return (0, _jsonschemaKeyCompression.compressedPath)(table, idx); + } + }); + compressedSchema.indexes = newIndexes; } - /** - * replace the keys of a query-obj with the compressed keys - * @return compressed queryJSON - */ - ; - _proto.compressQuery = function compressQuery(queryJSON) { - if (!this.schema.doKeyCompression()) { - return queryJSON; - } else { - return (0, _jsonschemaKeyCompression.compressQuery)(this.table, queryJSON); - } + return { + table: table, + schema: compressedSchema }; +} - (0, _createClass2["default"])(KeyCompressor, [{ - key: "table", - get: function get() { - var jsonSchema = this.schema.normalized; - var table = (0, _jsonschemaKeyCompression.createCompressionTable)(jsonSchema, _jsonschemaKeyCompression.DEFAULT_COMPRESSION_FLAG, [this.schema.primaryPath, '_rev', '_attachments']); - return (0, _util.overwriteGetterForCaching)(this, 'table', table); - } - }]); - return KeyCompressor; -}(); +function getCompressionStateByStorageInstance(collection) { + var state = COMPRESSION_STATE_BY_COLLECTION.get(collection); -exports.KeyCompressor = KeyCompressor; + if (!state) { + state = createCompressionState(collection.schema.jsonSchema); + COMPRESSION_STATE_BY_COLLECTION.set(collection, state); + } -function create(schema) { - return new KeyCompressor(schema); + return state; } var rxdb = true; exports.rxdb = rxdb; var prototypes = {}; exports.prototypes = prototypes; -var overwritable = { - createKeyCompressor: create -}; +var overwritable = {}; exports.overwritable = overwritable; var RxDBKeyCompressionPlugin = { name: 'key-compression', rxdb: rxdb, prototypes: prototypes, - overwritable: overwritable + overwritable: overwritable, + hooks: { + /** + * replace the keys of a query-obj with the compressed keys + * because the storage instance only know the compressed schema + * @return compressed queryJSON + */ + prePrepareQuery: function prePrepareQuery(input) { + var rxQuery = input.rxQuery; + var mangoQuery = input.mangoQuery; + + if (!rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var compressionState = getCompressionStateByStorageInstance(rxQuery.collection); + var compressedQuery = (0, _jsonschemaKeyCompression.compressQuery)(compressionState.table, mangoQuery); + input.mangoQuery = compressedQuery; + }, + preCreateRxStorageInstance: function preCreateRxStorageInstance(params) { + /** + * When key compression is used, + * the storage instance only knows about the compressed schema + */ + if (params.schema.keyCompression) { + var compressionState = createCompressionState(params.schema); + params.schema = compressionState.schema; + } + }, + preQueryMatcher: function preQueryMatcher(params) { + if (!params.rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.rxQuery.collection); + params.doc = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.doc); + }, + preSortComparator: function preSortComparator(params) { + if (!params.rxQuery.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.rxQuery.collection); + params.docA = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.docA); + params.docB = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.docB); + }, + preWriteToStorageInstance: function preWriteToStorageInstance(params) { + if (!params.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.collection); + params.doc = (0, _jsonschemaKeyCompression.compressObject)(state.table, params.doc); + }, + postReadFromInstance: function postReadFromInstance(params) { + if (!params.collection.schema.jsonSchema.keyCompression) { + return; + } + + var state = getCompressionStateByStorageInstance(params.collection); + params.doc = (0, _jsonschemaKeyCompression.decompressObject)(state.table, params.doc); + } + } }; exports.RxDBKeyCompressionPlugin = RxDBKeyCompressionPlugin; -},{"../util":56,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"jsonschema-key-compression":612}],25:[function(require,module,exports){ +},{"jsonschema-key-compression":612}],25:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -3418,7 +3786,7 @@ var RxDBLeaderElectionPlugin = { exports.RxDBLeaderElectionPlugin = RxDBLeaderElectionPlugin; -},{"broadcast-channel":112}],26:[function(require,module,exports){ +},{"broadcast-channel":113}],26:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -3426,7 +3794,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.RxDBLocalDocumentsPlugin = exports.overwritable = exports.prototypes = exports.rxdb = exports.RxLocalDocument = void 0; +exports.RxDBLocalDocumentsPlugin = exports.RxLocalDocument = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -3438,8 +3806,6 @@ var _objectPath = _interopRequireDefault(require("object-path")); var _rxDocument = require("../rx-document"); -var _rxChangeEvent = require("../rx-change-event"); - var _docCache = require("../doc-cache"); var _rxError = require("../rx-error"); @@ -3452,11 +3818,10 @@ var _rxCollection = require("../rx-collection"); var _operators = require("rxjs/operators"); -/** - * This plugin adds the local-documents-support - * Local documents behave equal then with pouchdb - * @link https://pouchdb.com/guides/local-documents.html - */ +var _rxStorageHelper = require("../rx-storage-helper"); + +var _overwritable = require("../overwritable"); + var DOC_CACHE_BY_PARENT = new WeakMap(); var _getDocCache = function _getDocCache(parent) { @@ -3477,7 +3842,10 @@ var _getChangeSub = function _getChangeSub(parent) { var docCache = _getDocCache(parent); var doc = docCache.get(cE.documentId); - if (doc) doc._handleChangeEvent(cE); + + if (doc) { + doc._handleChangeEvent(cE); + } }); parent._subs.push(sub); @@ -3507,25 +3875,19 @@ var RxLocalDocument = /*#__PURE__*/function (_RxDocumentParent) { exports.RxLocalDocument = RxLocalDocument; -var _getPouchByParent = function _getPouchByParent(parent) { - if ((0, _rxDatabase.isInstanceOf)(parent)) return parent.internalStore; // database - else return parent.pouch; // collection -}; +function _getKeyObjectStorageInstanceByParent(parent) { + if ((0, _rxDatabase.isRxDatabase)(parent)) { + return parent.localDocumentsStore; // database + } else { + return parent.localDocumentsStore; // collection + } +} var RxLocalDocumentPrototype = { - toPouchJson: function toPouchJson() { - var data = (0, _util.clone)(this._data); - data._id = _util.LOCAL_PREFIX + this.id; - }, - get isLocal() { return true; }, - get parentPouch() { - return _getPouchByParent(this.parent); - }, - // // overwrites // @@ -3536,9 +3898,9 @@ var RxLocalDocumentPrototype = { switch (changeEvent.operation) { case 'UPDATE': - var newData = (0, _util.clone)(changeEvent.documentData); + var newData = changeEvent.documentData; - this._dataSync$.next((0, _util.clone)(newData)); + this._dataSync$.next(newData); break; @@ -3548,7 +3910,7 @@ var RxLocalDocumentPrototype = { docCache["delete"](this.primary); - this._deleted$.next(true); + this._isDeleted$.next(true); break; } @@ -3577,7 +3939,9 @@ var RxLocalDocumentPrototype = { return this.parent.$emit(changeEvent); }, get: function get(objPath) { - if (!this._data) return undefined; + if (!this._data) { + return undefined; + } if (typeof objPath !== 'string') { throw (0, _rxError.newRxTypeError)('LD2', { @@ -3587,7 +3951,7 @@ var RxLocalDocumentPrototype = { var valueObj = _objectPath["default"].get(this._data, objPath); - valueObj = (0, _util.clone)(valueObj); + valueObj = _overwritable.overwritable.deepFreezeWhenDevMode(valueObj); return valueObj; }, get$: function get$(path) { @@ -3605,7 +3969,7 @@ var RxLocalDocumentPrototype = { set: function set(objPath, value) { if (!value) { // object path not set, overwrite whole data - var data = (0, _util.clone)(objPath); + var data = (0, _util.flatClone)(objPath); data._rev = this._data._rev; this._data = data; return this; @@ -3618,40 +3982,48 @@ var RxLocalDocumentPrototype = { }); } - if (Object.is(this.get(objPath), value)) return; + if (Object.is(this.get(objPath), value)) { + return; + } _objectPath["default"].set(this._data, objPath, value); return this; }, _saveData: function _saveData(newData) { - var _this2 = this; - var oldData = this._dataSync$.getValue(); - newData = (0, _util.clone)(newData); - newData._id = _util.LOCAL_PREFIX + this.id; - var startTime = (0, _util.now)(); - return this.parentPouch.put(newData).then(function (res) { - var endTime = (0, _util.now)(); - newData._rev = res.rev; - var changeEvent = new _rxChangeEvent.RxChangeEvent('UPDATE', _this2.id, (0, _util.clone)(newData), (0, _rxDatabase.isInstanceOf)(_this2.parent) ? _this2.parent.token : _this2.parent.database.token, (0, _rxCollection.isInstanceOf)(_this2.parent) ? _this2.parent.name : null, true, startTime, endTime, oldData, _this2); + var storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); + + newData._id = this.id; + return storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }]).then(function (res) { + var docResult = res.success.get(newData._id); + + if (!docResult) { + throw (0, _util.getFromMapOrThrow)(res.error, newData._id); + } - _this2.$emit(changeEvent); + newData._rev = docResult._rev; }); }, remove: function remove() { - var _this3 = this; - - var removeId = _util.LOCAL_PREFIX + this.id; - var startTime = (0, _util.now)(); - return this.parentPouch.remove(removeId, this._data._rev).then(function () { - _getDocCache(_this3.parent)["delete"](_this3.id); + var _this2 = this; - var endTime = (0, _util.now)(); - var changeEvent = new _rxChangeEvent.RxChangeEvent('DELETE', _this3.id, (0, _util.clone)(_this3._data), (0, _rxDatabase.isInstanceOf)(_this3.parent) ? _this3.parent.token : _this3.parent.database.token, (0, _rxCollection.isInstanceOf)(_this3.parent) ? _this3.parent.name : null, true, startTime, endTime, null, _this3); + var storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); - _this3.$emit(changeEvent); + var writeData = { + _id: this.id, + _deleted: true, + _attachments: {} + }; + return (0, _rxStorageHelper.writeSingleLocal)(storageInstance, { + previous: this._data, + document: writeData + }).then(function () { + _getDocCache(_this2.parent)["delete"](_this2.id); }); } }; @@ -3704,36 +4076,29 @@ RxLocalDocument.create = function (id, data, parent) { */ -function insertLocal(id, data) { - var _this4 = this; +function insertLocal(id, docData) { + var _this3 = this; - if ((0, _rxCollection.isInstanceOf)(this) && this._isInMemory) { - return this._parentCollection.insertLocal(id, data); + if ((0, _rxCollection.isRxCollection)(this) && this._isInMemory) { + return this.parentCollection.insertLocal(id, docData); } - data = (0, _util.clone)(data); return this.getLocal(id).then(function (existing) { if (existing) { throw (0, _rxError.newRxError)('LD7', { id: id, - data: data + data: docData }); } // create new one - var pouch = _getPouchByParent(_this4); - - var saveData = (0, _util.clone)(data); - saveData._id = _util.LOCAL_PREFIX + id; - var startTime = (0, _util.now)(); - return pouch.put(saveData).then(function (res) { - data._rev = res.rev; - var newDoc = RxLocalDocument.create(id, data, _this4); - var endTime = (0, _util.now)(); - var changeEvent = new _rxChangeEvent.RxChangeEvent('INSERT', id, (0, _util.clone)(data), (0, _rxDatabase.isInstanceOf)(_this4) ? _this4.token : _this4.database.token, (0, _rxCollection.isInstanceOf)(_this4) ? _this4.name : '', true, startTime, endTime, undefined, newDoc); - - _this4.$emit(changeEvent); - + docData = (0, _util.flatClone)(docData); + docData._id = id; + return (0, _rxStorageHelper.writeSingleLocal)(_getKeyObjectStorageInstanceByParent(_this3), { + document: docData + }).then(function (res) { + docData._rev = res._rev; + var newDoc = RxLocalDocument.create(id, docData, _this3); return newDoc; }); }); @@ -3745,16 +4110,16 @@ function insertLocal(id, data) { function upsertLocal(id, data) { - var _this5 = this; + var _this4 = this; - if ((0, _rxCollection.isInstanceOf)(this) && this._isInMemory) { + if ((0, _rxCollection.isRxCollection)(this) && this._isInMemory) { return this._parentCollection.upsertLocal(id, data); } return this.getLocal(id).then(function (existing) { if (!existing) { // create new one - var docPromise = _this5.insertLocal(id, data); + var docPromise = _this4.insertLocal(id, data); return docPromise; } else { @@ -3770,21 +4135,30 @@ function upsertLocal(id, data) { } function getLocal(id) { - var _this6 = this; + var _this5 = this; - if ((0, _rxCollection.isInstanceOf)(this) && this._isInMemory) return this._parentCollection.getLocal(id); + if ((0, _rxCollection.isRxCollection)(this) && this._isInMemory) { + return this.parentCollection.getLocal(id); + } - var pouch = _getPouchByParent(this); + var storageInstance = _getKeyObjectStorageInstanceByParent(this); var docCache = _getDocCache(this); // check in doc-cache var found = docCache.get(id); - if (found) return Promise.resolve(found); // if not found, check in pouch - return pouch.get(_util.LOCAL_PREFIX + id).then(function (docData) { - if (!docData) return null; - var doc = RxLocalDocument.create(id, docData, _this6); + if (found) { + return Promise.resolve(found); + } // if not found, check in storage instance + + + return (0, _rxStorageHelper.findLocalDocument)(storageInstance, id).then(function (docData) { + if (!docData) { + return null; + } + + var doc = RxLocalDocument.create(id, docData, _this5); return doc; })["catch"](function () { return null; @@ -3792,7 +4166,7 @@ function getLocal(id) { } function getLocal$(id) { - var _this7 = this; + var _this6 = this; return this.$.pipe((0, _operators.startWith)(null), (0, _operators.mergeMap)( /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(cE) { @@ -3812,7 +4186,7 @@ function getLocal$(id) { case 4: _context.next = 6; - return _this7.getLocal(id); + return _this6.getLocal(id); case 6: doc = _context.sent; @@ -3839,7 +4213,7 @@ function getLocal$(id) { switch (_context2.prev = _context2.next) { case 0: if (!changeEventOrDoc.changeEvent) { - _context2.next = 17; + _context2.next = 12; break; } @@ -3855,40 +4229,27 @@ function getLocal$(id) { }); case 6: - if (!cE.rxDocument) { - _context2.next = 10; - break; - } - - _context2.t0 = cE.rxDocument; - _context2.next = 13; - break; - - case 10: - _context2.next = 12; - return _this7.getLocal(id); - - case 12: - _context2.t0 = _context2.sent; + _context2.next = 8; + return _this6.getLocal(id); - case 13: - doc = _context2.t0; + case 8: + doc = _context2.sent; return _context2.abrupt("return", { use: true, doc: doc }); - case 15: - _context2.next = 18; + case 10: + _context2.next = 13; break; - case 17: + case 12: return _context2.abrupt("return", { use: true, doc: changeEventOrDoc.doc }); - case 18: + case 13: case "end": return _context2.stop(); } @@ -3906,35 +4267,29 @@ function getLocal$(id) { })); } -var rxdb = true; -exports.rxdb = rxdb; -var prototypes = { - RxCollection: function RxCollection(proto) { - proto.insertLocal = insertLocal; - proto.upsertLocal = upsertLocal; - proto.getLocal = getLocal; - proto.getLocal$ = getLocal$; - }, - RxDatabase: function RxDatabase(proto) { - proto.insertLocal = insertLocal; - proto.upsertLocal = upsertLocal; - proto.getLocal = getLocal; - proto.getLocal$ = getLocal$; - } -}; -exports.prototypes = prototypes; -var overwritable = {}; -exports.overwritable = overwritable; var RxDBLocalDocumentsPlugin = { name: 'local-documents', - rxdb: rxdb, - prototypes: prototypes, - overwritable: overwritable + rxdb: true, + prototypes: { + RxCollection: function RxCollection(proto) { + proto.insertLocal = insertLocal; + proto.upsertLocal = upsertLocal; + proto.getLocal = getLocal; + proto.getLocal$ = getLocal$; + }, + RxDatabase: function RxDatabase(proto) { + proto.insertLocal = insertLocal; + proto.upsertLocal = upsertLocal; + proto.getLocal = getLocal; + proto.getLocal$ = getLocal$; + } + }, + overwritable: {} }; exports.RxDBLocalDocumentsPlugin = RxDBLocalDocumentsPlugin; -},{"../doc-cache":5,"../rx-change-event":39,"../rx-collection":41,"../rx-database":43,"../rx-document":45,"../rx-error":46,"../util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/inheritsLoose":64,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"object-path":630,"rxjs/operators":908}],27:[function(require,module,exports){ +},{"../doc-cache":5,"../overwritable":9,"../rx-collection":44,"../rx-database":45,"../rx-document":47,"../rx-error":48,"../rx-storage-helper":52,"../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/inheritsLoose":66,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"object-path":629,"rxjs/operators":908}],27:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -3956,30 +4311,32 @@ exports.migrateOldCollection = migrateOldCollection; exports.migratePromise = migratePromise; exports.DataMigrator = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + var _rxjs = require("rxjs"); var _deepEqual = _interopRequireDefault(require("deep-equal")); -var _pouchDb = require("../../pouch-db"); - var _util = require("../../util"); var _rxSchema = require("../../rx-schema"); var _rxError = require("../../rx-error"); -var _overwritable = require("../../overwritable"); - var _hooks = require("../../hooks"); var _crypter = require("../../crypter"); -var _rxCollectionHelper = require("../../rx-collection-helper"); - var _migrationState = require("./migration-state"); var _operators = require("rxjs/operators"); +var _rxStorageHelper = require("../../rx-storage-helper"); + +var _rxCollectionHelper = require("../../rx-collection-helper"); + /** * The DataMigrator handles the documents from collections with older schemas * and transforms/saves them into the newest collection @@ -3987,7 +4344,7 @@ var _operators = require("rxjs/operators"); /** * TODO this should be completely rewritten because: - * - The current implemetation does not use pouchdb'S bulkDocs which is much faster + * - The current implemetation does not use bulkDocs which is much faster * - This could have been done in much less code which would be easier to uderstand * */ @@ -4040,6 +4397,8 @@ var DataMigrator = /*#__PURE__*/function () { * TODO this is a side-effect which might throw * We did this because it is not possible to create new Observer(async(...)) * @link https://github.com/ReactiveX/rxjs/issues/4074 + * In the future the whole migration plugin should be rewritten without rxjs + * so we do not have this problem. */ (function () { @@ -4047,7 +4406,7 @@ var DataMigrator = /*#__PURE__*/function () { return _getOldCollections(_this).then(function (ret) { oldCols = ret; var countAll = Promise.all(oldCols.map(function (oldCol) { - return (0, _pouchDb.countAllUndeleted)(oldCol.pouchdb); + return (0, _rxStorageHelper.countAllUndeleted)(oldCol.storageInstance); })); return countAll; }).then(function (countAll) { @@ -4128,51 +4487,102 @@ var DataMigrator = /*#__PURE__*/function () { exports.DataMigrator = DataMigrator; -function createOldCollection(version, schemaObj, dataMigrator) { - var database = dataMigrator.newestCollection.database; - var schema = (0, _rxSchema.createRxSchema)(schemaObj, false); - var ret = { - version: version, - dataMigrator: dataMigrator, - newestCollection: dataMigrator.newestCollection, - database: database, - schema: (0, _rxSchema.createRxSchema)(schemaObj, false), - pouchdb: database._spawnPouchDB(dataMigrator.newestCollection.name, version, dataMigrator.newestCollection.pouchSettings), - _crypter: (0, _crypter.createCrypter)(database.password, schema) - }; - - if (schema.doKeyCompression()) { - ret._keyCompressor = _overwritable.overwritable.createKeyCompressor(schema); - } - - return ret; +function createOldCollection(_x, _x2, _x3) { + return _createOldCollection.apply(this, arguments); } /** - * get an array with OldCollection-instances from all existing old pouchdb-instance + * get an array with OldCollection-instances from all existing old storage-instances */ -function _getOldCollections(dataMigrator) { - return Promise.all((0, _rxSchema.getPreviousVersions)(dataMigrator.currentSchema.jsonSchema).map(function (v) { - return dataMigrator.database.internalStore.get(dataMigrator.name + '-' + v); - }).map(function (fun) { - return fun["catch"](function () { - return null; - }); - }) // auto-catch so Promise.all continues - ).then(function (oldColDocs) { - return oldColDocs.filter(function (colDoc) { - return colDoc !== null; - }).map(function (colDoc) { - return createOldCollection(colDoc.schema.version, colDoc.schema, dataMigrator); - }); - }); +function _createOldCollection() { + _createOldCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(version, schemaObj, dataMigrator) { + var database, schema, storageInstanceCreationParams, storageInstance, ret; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + database = dataMigrator.newestCollection.database; + schema = (0, _rxSchema.createRxSchema)(schemaObj, false); + storageInstanceCreationParams = { + databaseName: database.name, + collectionName: dataMigrator.newestCollection.name, + schema: schemaObj, + options: dataMigrator.newestCollection.instanceCreationOptions + }; + _context.next = 5; + return database.storage.createStorageInstance(storageInstanceCreationParams); + + case 5: + storageInstance = _context.sent; + ret = { + version: version, + dataMigrator: dataMigrator, + newestCollection: dataMigrator.newestCollection, + database: database, + schema: (0, _rxSchema.createRxSchema)(schemaObj, false), + storageInstance: storageInstance, + _crypter: (0, _crypter.createCrypter)(database.password, schema) + }; + return _context.abrupt("return", ret); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _createOldCollection.apply(this, arguments); +} + +function _getOldCollections(_x4) { + return _getOldCollections2.apply(this, arguments); } /** * returns true if a migration is needed */ +function _getOldCollections2() { + _getOldCollections2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(dataMigrator) { + var oldColDocs; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all((0, _rxSchema.getPreviousVersions)(dataMigrator.currentSchema.jsonSchema).map(function (v) { + return (0, _rxStorageHelper.getSingleDocument)(dataMigrator.database.internalStore, dataMigrator.name + '-' + v); + }).map(function (fun) { + return fun["catch"](function () { + return null; + }); + }) // auto-catch so Promise.all continues + ); + + case 2: + oldColDocs = _context2.sent; + return _context2.abrupt("return", Promise.all(oldColDocs.map(function (colDoc) { + if (!colDoc) { + return null; + } + + return createOldCollection(colDoc.schema.version, colDoc.schema, dataMigrator); + }).filter(function (colDoc) { + return colDoc !== null; + }))); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _getOldCollections2.apply(this, arguments); +} + function mustMigrate(dataMigrator) { if (dataMigrator.currentSchema.version === 0) { return Promise.resolve(false); @@ -4198,9 +4608,11 @@ function runStrategyIfNotNull(oldCollection, version, docOrNull) { } function getBatchOfOldCollection(oldCollection, batchSize) { - return (0, _pouchDb.getBatch)(oldCollection.pouchdb, batchSize).then(function (docs) { + return (0, _rxStorageHelper.getBatch)(oldCollection.storageInstance, batchSize).then(function (docs) { return docs.map(function (doc) { - return (0, _rxCollectionHelper._handleFromPouch)(oldCollection, doc); + doc = (0, _util.flatClone)(doc); + doc = (0, _rxCollectionHelper._handleFromStorageInstance)(oldCollection, doc); + return doc; }); }); } @@ -4238,7 +4650,10 @@ function migrateDocumentData(oldCollection, docData) { } return currentPromise.then(function (doc) { - if (doc === null) return Promise.resolve(null); // check final schema + if (doc === null) { + return Promise.resolve(null); + } // check final schema + try { oldCollection.newestCollection.schema.validate(doc); @@ -4325,17 +4740,16 @@ function _migrateDocument(oldCollection, docData) { * notice that this data also contains the attachments data */ var attachmentsBefore = migrated._attachments; - - var saveData = oldCollection.newestCollection._handleToPouch(migrated); - + var saveData = (0, _rxCollectionHelper._handleToStorageInstance)(oldCollection.newestCollection, migrated); saveData._attachments = attachmentsBefore; - return oldCollection.newestCollection.pouch.bulkDocs([saveData], { - /** - * We need new_edits: false - * because we provide the _rev by our own - */ - new_edits: false - }).then(function () { + /** + * We need to add as revision + * because we provide the _rev by our own + * to have deterministic revisions in case the migration + * runs on multiple nodes which must lead to the equal storage state. + */ + + return oldCollection.newestCollection.storageInstance.bulkAddRevisions([saveData]).then(function () { action.res = saveData; action.type = 'success'; return (0, _hooks.runAsyncPluginHooks)('postMigrateDocument', action); @@ -4348,236 +4762,2604 @@ function _migrateDocument(oldCollection, docData) { */ action.type = 'deleted'; } - }).then(function () { - // remove from old collection - return oldCollection.pouchdb.remove((0, _rxCollectionHelper._handleToPouch)(oldCollection, docData))["catch"](function () {}); + }) // remove the migrated document from the old collection + .then(function () { + var writeDeleted = (0, _util.flatClone)(docData); + writeDeleted._deleted = true; + return oldCollection.storageInstance.bulkWrite([{ + previous: (0, _rxCollectionHelper._handleToStorageInstance)(oldCollection, docData), + document: (0, _rxCollectionHelper._handleToStorageInstance)(oldCollection, writeDeleted) + }]); }).then(function () { return action; }); } -/** - * deletes this.pouchdb and removes it from the database.collectionsCollection - */ +/** + * deletes this.storageInstance and removes it from the database.collectionsCollection + */ + + +function deleteOldCollection(oldCollection) { + return oldCollection.storageInstance.remove().then(function () { + return oldCollection.database.removeCollectionDoc(oldCollection.dataMigrator.name, oldCollection.schema); + }); +} +/** + * runs the migration on all documents and deletes the storage instance afterwards + */ + + +function migrateOldCollection(oldCollection) { + var batchSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + if (oldCollection._migrate) { + // already running + throw (0, _rxError.newRxError)('DM3'); + } + + oldCollection._migrate = true; + var observer = new _rxjs.Subject(); + /** + * TODO this is a side-effect which might throw + * @see DataMigrator.migrate() + */ + + (function () { + var error; + + var allBatchesDone = function allBatchesDone() { + // remove this oldCollection + return deleteOldCollection(oldCollection).then(function () { + return observer.complete(); + }); + }; + + var handleOneBatch = function handleOneBatch() { + return getBatchOfOldCollection(oldCollection, batchSize).then(function (batch) { + if (batch.length === 0) { + allBatchesDone(); + return false; + } else { + return Promise.all(batch.map(function (doc) { + return _migrateDocument(oldCollection, doc).then(function (action) { + return observer.next(action); + }); + }))["catch"](function (e) { + return error = e; + }).then(function () { + return true; + }); + } + }).then(function (next) { + if (!next) return; + if (error) observer.error(error);else handleOneBatch(); + }); + }; + + handleOneBatch(); + })(); + + return observer.asObservable(); +} + +function migratePromise(oldCollection, batchSize) { + if (!oldCollection._migratePromise) { + oldCollection._migratePromise = new Promise(function (res, rej) { + var state$ = migrateOldCollection(oldCollection, batchSize); + state$.subscribe(null, rej, res); + }); + } + + return oldCollection._migratePromise; +} + + +},{"../../crypter":4,"../../hooks":7,"../../rx-collection-helper":43,"../../rx-error":48,"../../rx-schema":51,"../../rx-storage-helper":52,"../../util":58,"./migration-state":29,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"deep-equal":497,"rxjs":684,"rxjs/operators":908}],28:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "_getOldCollections", { + enumerable: true, + get: function get() { + return _dataMigrator._getOldCollections; + } +}); +Object.defineProperty(exports, "getBatchOfOldCollection", { + enumerable: true, + get: function get() { + return _dataMigrator.getBatchOfOldCollection; + } +}); +Object.defineProperty(exports, "migrateDocumentData", { + enumerable: true, + get: function get() { + return _dataMigrator.migrateDocumentData; + } +}); +Object.defineProperty(exports, "_migrateDocument", { + enumerable: true, + get: function get() { + return _dataMigrator._migrateDocument; + } +}); +Object.defineProperty(exports, "deleteOldCollection", { + enumerable: true, + get: function get() { + return _dataMigrator.deleteOldCollection; + } +}); +Object.defineProperty(exports, "migrateOldCollection", { + enumerable: true, + get: function get() { + return _dataMigrator.migrateOldCollection; + } +}); +Object.defineProperty(exports, "migratePromise", { + enumerable: true, + get: function get() { + return _dataMigrator.migratePromise; + } +}); +Object.defineProperty(exports, "DataMigrator", { + enumerable: true, + get: function get() { + return _dataMigrator.DataMigrator; + } +}); +exports.RxDBMigrationPlugin = exports.DATA_MIGRATOR_BY_COLLECTION = void 0; + +var _rxjs = require("rxjs"); + +var _operators = require("rxjs/operators"); + +var _dataMigrator = require("./data-migrator"); + +var _migrationState = require("./migration-state"); + +var DATA_MIGRATOR_BY_COLLECTION = new WeakMap(); +exports.DATA_MIGRATOR_BY_COLLECTION = DATA_MIGRATOR_BY_COLLECTION; +var RxDBMigrationPlugin = { + name: 'migration', + rxdb: true, + hooks: { + preDestroyRxDatabase: _migrationState.onDatabaseDestroy + }, + prototypes: { + RxDatabase: function RxDatabase(proto) { + proto.migrationStates = function () { + return (0, _migrationState.getMigrationStateByDatabase)(this).pipe((0, _operators.switchMap)(function (list) { + return (0, _rxjs.combineLatest)(list); + }), (0, _operators.shareReplay)({ + bufferSize: 1, + refCount: true + })); + }; + }, + RxCollection: function RxCollection(proto) { + proto.getDataMigrator = function () { + if (!DATA_MIGRATOR_BY_COLLECTION.has(this)) { + DATA_MIGRATOR_BY_COLLECTION.set(this, (0, _dataMigrator.createDataMigrator)(this.asRxCollection, this.migrationStrategies)); + } + + return DATA_MIGRATOR_BY_COLLECTION.get(this); + }; + + proto.migrationNeeded = function () { + return (0, _dataMigrator.mustMigrate)(this.getDataMigrator()); + }; + } + } +}; // used in tests + +exports.RxDBMigrationPlugin = RxDBMigrationPlugin; + + +},{"./data-migrator":27,"./migration-state":29,"rxjs":684,"rxjs/operators":908}],29:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getMigrationStateByDatabase = getMigrationStateByDatabase; +exports.onDatabaseDestroy = onDatabaseDestroy; +exports.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = void 0; + +var _rxjs = require("rxjs"); + +var _util = require("../../util"); + +var DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap(); +exports.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE; + +function getMigrationStateByDatabase(database) { + if (!DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.has(database)) { + DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.set(database, new _rxjs.BehaviorSubject([])); + } + + var subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database); + return (0, _util.ensureNotFalsy)(subject); +} +/** + * Complete on database destroy + * so people do not have to unsubscribe + */ + + +function onDatabaseDestroy(database) { + var subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database); + + if (subject) { + subject.complete(); + } +} + + +},{"../../util":58,"rxjs":684}],30:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.checkAdapter = checkAdapter; +exports.POUCHDB_LOCATION = void 0; + +var _pouchDb = require("./pouch-db"); + +var _util = require("../../util"); + +/** + * this plugin adds the checkAdapter-function to rxdb + * you can use it to check if the given adapter is working in the current environmet + */ + +/** + * The same pouchdb-location is used on each run + * To ensure when this is run multiple times, + * there will not be many created databases + */ +var POUCHDB_LOCATION = 'rxdb-adapter-check'; +exports.POUCHDB_LOCATION = POUCHDB_LOCATION; + +function checkAdapter(adapter) { + // id of the document which is stored and removed to ensure everything works + var _id = POUCHDB_LOCATION + '-' + (0, _util.randomCouchString)(12); + + var pouch; + + try { + pouch = new _pouchDb.PouchDB(POUCHDB_LOCATION, (0, _util.adapterObject)(adapter), { + auto_compaction: true, + revs_limit: 1 + }); + } catch (err) { + return Promise.resolve(false); + } + + var recoveredDoc; + return pouch.info() // ensure that we wait until db is useable + // ensure write works + .then(function () { + return pouch.put({ + _id: _id, + value: { + ok: true, + time: new Date().getTime() + } + }); + }) // ensure read works + .then(function () { + return pouch.get(_id); + }).then(function (doc) { + return recoveredDoc = doc; + }) // ensure remove works + .then(function () { + return pouch.remove(recoveredDoc); + }).then(function () { + return true; + }).then(function () { + if (recoveredDoc && recoveredDoc.value && recoveredDoc.value.ok) return true;else return false; + })["catch"](function () { + return false; + }); + /** + * NOTICE: + * Do not remove the pouchdb-instance after the test + * The problem is that when this function is call in parallel, + * for example when you restore the tabs from a browser-session and open + * the same website multiple times at the same time, + * calling destroy would possibly crash the other call + */ +} + + +},{"../../util":58,"./pouch-db":33}],31:[function(require,module,exports){ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getCustomEventEmitterByPouch = getCustomEventEmitterByPouch; +exports.addCustomEventsPluginToPouch = addCustomEventsPluginToPouch; +exports.EVENT_EMITTER_BY_POUCH_INSTANCE = void 0; + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); + +var _rxjs = require("rxjs"); + +var _util = require("../../util"); + +var _rxError = require("../../rx-error"); + +var _obliviousSet = require("oblivious-set"); + +/* + * Instead of listening to pouch.changes, + * we overwrite pouchdbs bulkDocs() + * and create our own event stream, this will work more reliable + * and has less strange behaviors. + * Also we can better define what data we need for our events. + * @link http://jsbin.com/pagebi/1/edit?js,output + * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273 + */ +// ensure only added once +var addedToPouch = false; +var EVENT_EMITTER_BY_POUCH_INSTANCE = new Map(); +exports.EVENT_EMITTER_BY_POUCH_INSTANCE = EVENT_EMITTER_BY_POUCH_INSTANCE; + +function getCustomEventEmitterByPouch(pouch) { + var key = [pouch.name, pouch.adapter].join('|'); + var emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key); + + if (!emitter) { + emitter = { + subject: new _rxjs.Subject(), + obliviousSet: new _obliviousSet.ObliviousSet(60 * 1000) + }; + EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter); + } + + return emitter; +} + +var i = 0; + +function addCustomEventsPluginToPouch() { + if (addedToPouch) { + return; + } + + addedToPouch = true; + var oldBulkDocs = _pouchdbCore["default"].prototype.bulkDocs; + + var newBulkDocs = /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(body, options, callback) { + var _this = this; + + var startTime, t, docs, previousDocs, ids, viaChanges, previousDocsResult, deeperOptions; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + startTime = (0, _util.now)(); + t = i++; // normalize input + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (!options) { + options = {}; + } + + if (Array.isArray(body)) { + docs = body; + } else if (body === undefined) { + docs = []; + } else { + docs = body.docs; + + if (body.hasOwnProperty('new_edits')) { + options.new_edits = body.new_edits; + } + } + + if (!(docs.length === 0)) { + _context2.next = 7; + break; + } + + throw (0, _rxError.newRxError)('SNH', { + args: { + body: body, + options: options + } + }); + + case 7: + /** + * If new_edits=false we have to first find the current state + * of the document and can later check if the state was changed + * because a new revision was written and we have to emit an event. + */ + previousDocs = new Map(); + + if (!(options.hasOwnProperty('new_edits') && options.new_edits === false)) { + _context2.next = 18; + break; + } + + ids = docs.map(function (doc) { + return doc._id; + }); + /** + * Pouchdb does not return deleted documents via allDocs() + * So have to do use our hack with getting the newest revisions from the + * changes. + */ + + _context2.next = 12; + return this.changes({ + live: false, + since: 0, + doc_ids: ids, + style: 'all_docs' + }); + + case 12: + viaChanges = _context2.sent; + _context2.next = 15; + return Promise.all(viaChanges.results.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(result) { + var firstDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.get(result.id, { + rev: result.changes[0].rev, + deleted: 'ok', + revs: options.set_new_edit_as_latest_revision ? true : false, + style: 'all_docs' + }); + + case 2: + firstDoc = _context.sent; + return _context.abrupt("return", firstDoc); + + case 4: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }())); + + case 15: + previousDocsResult = _context2.sent; + previousDocsResult.forEach(function (doc) { + return previousDocs.set(doc._id, doc); + }); + + if (options.set_new_edit_as_latest_revision) { + docs.forEach(function (doc) { + var id = doc._id; + var previous = previousDocs.get(id); + + if (previous) { + var splittedRev = doc._rev.split('-'); + + var revHeight = parseInt(splittedRev[0], 10); + var revLabel = splittedRev[1]; + doc._revisions = { + start: revHeight, + ids: previous._revisions.ids + }; + + doc._revisions.ids.unshift(revLabel); + + delete previous._revisions; + } + }); + } + + case 18: + /** + * pouchdb calls this function again with transformed input. + * This would lead to duplicate events. So we marks the deeper calls via the options + * parameter and do not emit events if it is set. + */ + deeperOptions = (0, _util.flatClone)(options); + deeperOptions.isDeeper = true; + return _context2.abrupt("return", oldBulkDocs.call(this, docs, deeperOptions, function (err, result) { + if (err) { + if (callback) { + callback(err); + } else { + throw err; + } + } else { + if (!options.isDeeper) { + var endTime = (0, _util.now)(); + var emitData = { + emitId: t, + writeDocs: docs, + writeOptions: options, + writeResult: result, + previousDocs: previousDocs, + startTime: startTime, + endTime: endTime + }; + var emitter = getCustomEventEmitterByPouch(_this); + emitter.subject.next(emitData); + } + + if (callback) { + callback(null, result); + } else { + return result; + } + } + })); + + case 21: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function newBulkDocs(_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; + }(); + + _pouchdbCore["default"].plugin({ + bulkDocs: newBulkDocs + }); +} + + +},{"../../rx-error":48,"../../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"oblivious-set":634,"pouchdb-core":655,"rxjs":684}],32:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _pouchDb = require("./pouch-db"); + +Object.keys(_pouchDb).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _pouchDb[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _pouchDb[key]; + } + }); +}); + +var _rxStoragePouchdb = require("./rx-storage-pouchdb"); + +Object.keys(_rxStoragePouchdb).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rxStoragePouchdb[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rxStoragePouchdb[key]; + } + }); +}); + +var _adapterCheck = require("./adapter-check"); + +Object.keys(_adapterCheck).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _adapterCheck[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _adapterCheck[key]; + } + }); +}); + +var _customEventsPlugin = require("./custom-events-plugin"); + +Object.keys(_customEventsPlugin).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _customEventsPlugin[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _customEventsPlugin[key]; + } + }); +}); + + +},{"./adapter-check":30,"./custom-events-plugin":31,"./pouch-db":33,"./rx-storage-pouchdb":34}],33:[function(require,module,exports){ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isLevelDown = isLevelDown; +exports.pouchReplicationFunction = pouchReplicationFunction; +exports.isInstanceOf = isInstanceOf; +exports.addPouchPlugin = addPouchPlugin; +exports.PouchDB = void 0; + +var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); + +var _pouchdbFind = _interopRequireDefault(require("pouchdb-find")); + +var _rxError = require("../../rx-error"); + +var _customEventsPlugin = require("./custom-events-plugin"); + +/** + * this handles the pouchdb-instance + * to easy add modules and manipulate things + * Adapters can be found here: + * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules + */ +// pouchdb-find + +/* +// comment in to debug +const pouchdbDebug = require('pouchdb-debug'); +PouchDB.plugin(pouchdbDebug); +PouchDB.debug.enable('*'); +*/ +// TODO we can delete most of these functions in the file because it was migrated to rx-storage-pouchdb +addPouchPlugin(_pouchdbFind["default"]); +(0, _customEventsPlugin.addCustomEventsPluginToPouch)(); +/** + * check if the given module is a leveldown-adapter + * throws if not + */ + +function isLevelDown(adapter) { + if (!adapter || typeof adapter.super_ !== 'function') { + throw (0, _rxError.newRxError)('UT4', { + adapter: adapter + }); + } +} +/** + * get the correct function-name for pouchdb-replication + */ + + +function pouchReplicationFunction(pouch, _ref) { + var _ref$pull = _ref.pull, + pull = _ref$pull === void 0 ? true : _ref$pull, + _ref$push = _ref.push, + push = _ref$push === void 0 ? true : _ref$push; + if (pull && push) return pouch.sync.bind(pouch); + if (!pull && push) return pouch.replicate.to.bind(pouch); + if (pull && !push) return pouch.replicate.from.bind(pouch); + + if (!pull && !push) { + throw (0, _rxError.newRxError)('UT3', { + pull: pull, + push: push + }); + } +} + +function isInstanceOf(obj) { + return obj instanceof _pouchdbCore["default"]; +} +/** + * Add a pouchdb plugin to the pouchdb library. + */ + + +function addPouchPlugin(plugin) { + if (plugin.rxdb) { + throw (0, _rxError.newRxTypeError)('PL2', { + plugin: plugin + }); + } + /** + * Pouchdb has confusing typings and modules. + * So we monkeypatch the plugin to use the default property + * when it was imported or packaged this way. + */ + + + if (typeof plugin === 'object' && plugin["default"]) { + plugin = plugin["default"]; + } + + _pouchdbCore["default"].plugin(plugin); +} + +var PouchDB = _pouchdbCore["default"]; +exports.PouchDB = PouchDB; + + +},{"../../rx-error":48,"./custom-events-plugin":31,"@babel/runtime/helpers/interopRequireDefault":67,"pouchdb-core":655,"pouchdb-find":658}],34:[function(require,module,exports){ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.writeAttachmentsToAttachments = writeAttachmentsToAttachments; +exports.checkPouchAdapter = checkPouchAdapter; +exports.pouchHash = pouchHash; +exports.pouchSwapIdToPrimary = pouchSwapIdToPrimary; +exports.pouchDocumentDataToRxDocumentData = pouchDocumentDataToRxDocumentData; +exports.rxDocumentDataToPouchDocumentData = rxDocumentDataToPouchDocumentData; +exports.pouchSwapPrimaryToId = pouchSwapPrimaryToId; +exports.pouchStripLocalFlagFromPrimary = pouchStripLocalFlagFromPrimary; +exports.getEventKey = getEventKey; +exports.pouchChangeRowToChangeEvent = pouchChangeRowToChangeEvent; +exports.pouchChangeRowToChangeStreamEvent = pouchChangeRowToChangeStreamEvent; +exports.primarySwapPouchDbQuerySelector = primarySwapPouchDbQuerySelector; +exports.createIndexesOnPouch = createIndexesOnPouch; +exports.getPouchLocation = getPouchLocation; +exports.getRxStoragePouch = getRxStoragePouch; +exports.RxStoragePouch = exports.RxStorageInstancePouch = exports.RxStorageKeyObjectInstancePouch = exports.OPEN_POUCHDB_STORAGE_INSTANCES = exports.POUCHDB_DESIGN_PREFIX = exports.POUCHDB_LOCAL_PREFIX = void 0; + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _pouchdbSelectorCore = require("pouchdb-selector-core"); + +var _pouchdbMd = require("pouchdb-md5"); + +var _util = require("../../util"); + +var _pouchDb = require("./pouch-db"); + +var _rxError = require("../../rx-error"); + +var _rxjs = require("rxjs"); + +var _rxSchemaHelper = require("../../rx-schema-helper"); + +var _customEventsPlugin = require("./custom-events-plugin"); + +/** + * prefix of local pouchdb documents + */ +var POUCHDB_LOCAL_PREFIX = '_local/'; +/** + * Pouchdb stores indexes as design documents, + * we have to filter them out and not return the + * design documents to the outside. + */ + +exports.POUCHDB_LOCAL_PREFIX = POUCHDB_LOCAL_PREFIX; +var POUCHDB_DESIGN_PREFIX = '_design/'; +exports.POUCHDB_DESIGN_PREFIX = POUCHDB_DESIGN_PREFIX; + +/** + * Used to check in tests if all instances have been cleaned up. + */ +var OPEN_POUCHDB_STORAGE_INSTANCES = new Set(); +exports.OPEN_POUCHDB_STORAGE_INSTANCES = OPEN_POUCHDB_STORAGE_INSTANCES; + +var RxStorageKeyObjectInstancePouch = /*#__PURE__*/function () { + function RxStorageKeyObjectInstancePouch(databaseName, collectionName, internals, options) { + this.changes$ = new _rxjs.Subject(); + this.databaseName = databaseName; + this.collectionName = collectionName; + this.internals = internals; + this.options = options; + OPEN_POUCHDB_STORAGE_INSTANCES.add(this); + } + + var _proto = RxStorageKeyObjectInstancePouch.prototype; + + _proto.close = function close() { + OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); // TODO this did not work because a closed pouchdb cannot be recreated in the same process run + // await this.internals.pouch.close(); + + return Promise.resolve(); + }; + + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.internals.pouch.destroy(); + + case 2: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function remove() { + return _remove.apply(this, arguments); + } + + return remove; + }(); + + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(documentWrites) { + var _this = this; + + var writeRowById, insertDocs, startTime, pouchResult, endTime, ret; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + writeRowById = new Map(); + insertDocs = documentWrites.map(function (writeRow) { + writeRowById.set(writeRow.document._id, writeRow); + var storeDocumentData = (0, _util.flatClone)(writeRow.document); + /** + * add local prefix + * Local documents always have _id as primary + */ + + storeDocumentData._id = POUCHDB_LOCAL_PREFIX + storeDocumentData._id; // if previous document exists, we have to send the previous revision to pouchdb. + + if (writeRow.previous) { + storeDocumentData._rev = writeRow.previous._rev; + } + + return storeDocumentData; + }); + startTime = (0, _util.now)(); + _context2.next = 5; + return this.internals.pouch.bulkDocs(insertDocs); + + case 5: + pouchResult = _context2.sent; + endTime = (0, _util.now)(); + ret = { + success: new Map(), + error: new Map() + }; + pouchResult.forEach(function (resultRow) { + resultRow.id = pouchStripLocalFlagFromPrimary(resultRow.id); + var writeRow = (0, _util.getFromMapOrThrow)(writeRowById, resultRow.id); + + if (resultRow.error) { + var err = { + isError: true, + status: 409, + documentId: resultRow.id, + writeRow: writeRow + }; + ret.error.set(resultRow.id, err); + } else { + var pushObj = (0, _util.flatClone)(writeRow.document); + pushObj._rev = resultRow.rev; // local document cannot have attachments + + pushObj._attachments = {}; + ret.success.set(resultRow.id, pushObj); + /** + * Emit a write event to the changestream. + * We do this here and not by observing the internal pouchdb changes + * because here we have the previous document data and do + * not have to fill previous with 'UNKNOWN'. + */ + + var event; + + if (!writeRow.previous) { + // was insert + event = { + operation: 'INSERT', + doc: pushObj, + id: resultRow.id, + previous: null + }; + } else if (writeRow.document._deleted) { + // was delete + // we need to add the new revision to the previous doc + // so that the eventkey is calculated correctly. + // Is this a hack? idk. + var previousDoc = (0, _util.flatClone)(writeRow.previous); + previousDoc._rev = resultRow.rev; + event = { + operation: 'DELETE', + doc: null, + id: resultRow.id, + previous: previousDoc + }; + } else { + // was update + event = { + operation: 'UPDATE', + doc: pushObj, + id: resultRow.id, + previous: writeRow.previous + }; + } + + if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) { + /** + * A deleted document was newly added to the storage engine, + * do not emit an event. + */ + } else { + var doc = event.operation === 'DELETE' ? event.previous : event.doc; + var eventId = getEventKey(true, doc._id, doc._rev ? doc._rev : ''); + var storageChangeEvent = { + eventId: eventId, + documentId: resultRow.id, + change: event, + startTime: startTime, + endTime: endTime + }; + + _this.changes$.next(storageChangeEvent); + } + } + }); + return _context2.abrupt("return", ret); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function bulkWrite(_x) { + return _bulkWrite.apply(this, arguments); + } + + return bulkWrite; + }(); + + _proto.findLocalDocumentsById = /*#__PURE__*/function () { + var _findLocalDocumentsById = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ids) { + var _this2 = this; + + var ret; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + ret = new Map(); + /** + * Pouchdb is not able to bulk-request local documents + * with the pouch.allDocs() method. + * so we need to get each by a single call. + * TODO create an issue at the pouchdb repo + */ + + _context4.next = 3; + return Promise.all(ids.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(id) { + var prefixedId, docData; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + prefixedId = POUCHDB_LOCAL_PREFIX + id; + _context3.prev = 1; + _context3.next = 4; + return _this2.internals.pouch.get(prefixedId); + + case 4: + docData = _context3.sent; + docData._id = id; + ret.set(id, docData); + _context3.next = 11; + break; + + case 9: + _context3.prev = 9; + _context3.t0 = _context3["catch"](1); + + case 11: + case "end": + return _context3.stop(); + } + } + }, _callee3, null, [[1, 9]]); + })); + + return function (_x3) { + return _ref.apply(this, arguments); + }; + }())); + + case 3: + return _context4.abrupt("return", ret); + + case 4: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + + function findLocalDocumentsById(_x2) { + return _findLocalDocumentsById.apply(this, arguments); + } + + return findLocalDocumentsById; + }(); + + _proto.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + + return RxStorageKeyObjectInstancePouch; +}(); + +exports.RxStorageKeyObjectInstancePouch = RxStorageKeyObjectInstancePouch; + +var RxStorageInstancePouch = /*#__PURE__*/function () { + function RxStorageInstancePouch(databaseName, collectionName, schema, internals, options) { + var _this3 = this; + + this.changes$ = new _rxjs.Subject(); + this.subs = []; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + OPEN_POUCHDB_STORAGE_INSTANCES.add(this); + /** + * Instead of listening to pouch.changes, + * we have overwritten pouchdbs bulkDocs() + * and create our own event stream, this will work more relyable + * and does not mix up with write events from other sources. + */ + + var emitter = (0, _customEventsPlugin.getCustomEventEmitterByPouch)(this.internals.pouch); + this.emittedEventIds = emitter.obliviousSet; + var eventSub = emitter.subject.subscribe( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(ev) { + var writeDocsById, writeMap; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + if (!(ev.writeOptions.hasOwnProperty('new_edits') && !ev.writeOptions.new_edits)) { + _context8.next = 4; + break; + } + + _context8.next = 3; + return Promise.all(ev.writeDocs.map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(writeDoc) { + var id, previousDoc, event; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + id = writeDoc._id; + writeDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeDoc); + _context5.next = 4; + return writeAttachmentsToAttachments(writeDoc._attachments); + + case 4: + writeDoc._attachments = _context5.sent; + previousDoc = ev.previousDocs.get(id); + + if (previousDoc) { + previousDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, previousDoc); + } + + if (!(previousDoc && (0, _util.getHeightOfRevision)(previousDoc._rev) > (0, _util.getHeightOfRevision)(writeDoc._rev))) { + _context5.next = 9; + break; + } + + return _context5.abrupt("return"); + + case 9: + if (!(!previousDoc && writeDoc._deleted)) { + _context5.next = 11; + break; + } + + return _context5.abrupt("return"); + + case 11: + if (!(previousDoc && previousDoc._deleted && writeDoc._deleted)) { + _context5.next = 13; + break; + } + + return _context5.abrupt("return"); + + case 13: + if (!(!previousDoc && !writeDoc._deleted)) { + _context5.next = 17; + break; + } + + // was insert + event = { + operation: 'INSERT', + doc: writeDoc, + id: id, + previous: null + }; + _context5.next = 27; + break; + + case 17: + if (!(writeDoc._deleted && previousDoc && !previousDoc._deleted)) { + _context5.next = 22; + break; + } + + // was delete + previousDoc._rev = writeDoc._rev; + event = { + operation: 'DELETE', + doc: null, + id: id, + previous: previousDoc + }; + _context5.next = 27; + break; + + case 22: + if (!previousDoc) { + _context5.next = 26; + break; + } + + // was update + event = { + operation: 'UPDATE', + doc: writeDoc, + id: id, + previous: previousDoc + }; + _context5.next = 27; + break; + + case 26: + throw (0, _rxError.newRxError)('SNH', { + args: { + writeDoc: writeDoc + } + }); + + case 27: + _this3.addEventToChangeStream(event, ev.startTime, ev.endTime); + + case 28: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + + return function (_x5) { + return _ref3.apply(this, arguments); + }; + }())); + + case 3: + return _context8.abrupt("return"); + + case 4: + if (ev.writeOptions.custom) { + _context8.next = 10; + break; + } + + writeDocsById = new Map(); + ev.writeDocs.forEach(function (writeDoc) { + return writeDocsById.set(writeDoc._id, writeDoc); + }); + _context8.next = 9; + return Promise.all(ev.writeResult.map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(resultRow) { + var id, writeDoc, event; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + id = resultRow.id; + + if (!(id.startsWith(POUCHDB_DESIGN_PREFIX) || id.startsWith(POUCHDB_LOCAL_PREFIX))) { + _context6.next = 3; + break; + } + + return _context6.abrupt("return"); + + case 3: + writeDoc = (0, _util.getFromMapOrThrow)(writeDocsById, resultRow.id); + _context6.next = 6; + return writeAttachmentsToAttachments(writeDoc._attachments); + + case 6: + writeDoc._attachments = _context6.sent; + event = pouchChangeRowToChangeEvent(_this3.schema.primaryKey, writeDoc); + + _this3.addEventToChangeStream(event); + + case 9: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + + return function (_x6) { + return _ref4.apply(this, arguments); + }; + }())); + + case 9: + return _context8.abrupt("return"); + + case 10: + writeMap = ev.writeOptions.custom.writeRowById; + _context8.next = 13; + return Promise.all(ev.writeResult.map( /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(resultRow) { + var id, writeRow, newDoc, event, previousDoc; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + if (!resultRow.error) { + _context7.next = 2; + break; + } + + return _context7.abrupt("return"); + + case 2: + id = resultRow.id; + writeRow = (0, _util.getFromMapOrThrow)(writeMap, id); + newDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeRow.document); + _context7.next = 7; + return writeAttachmentsToAttachments(newDoc._attachments); + + case 7: + newDoc._attachments = _context7.sent; + newDoc._rev = resultRow.rev; + + if (writeRow.previous) { + _context7.next = 13; + break; + } + + // was insert + event = { + operation: 'INSERT', + doc: newDoc, + id: id, + previous: null + }; + _context7.next = 23; + break; + + case 13: + if (!writeRow.document._deleted) { + _context7.next = 22; + break; + } + + // was delete + // we need to add the new revision to the previous doc + // so that the eventkey is calculated correctly. + // Is this a hack? idk. + previousDoc = pouchDocumentDataToRxDocumentData(_this3.schema.primaryKey, writeRow.previous); + _context7.next = 17; + return writeAttachmentsToAttachments(previousDoc._attachments); + + case 17: + previousDoc._attachments = _context7.sent; + previousDoc._rev = resultRow.rev; + event = { + operation: 'DELETE', + doc: null, + id: resultRow.id, + previous: previousDoc + }; + _context7.next = 23; + break; + + case 22: + // was update + event = { + operation: 'UPDATE', + doc: newDoc, + id: resultRow.id, + previous: writeRow.previous + }; + + case 23: + if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) { + /** + * A deleted document was newly added to the storage engine, + * do not emit an event. + */ + } else { + _this3.addEventToChangeStream(event, ev.startTime, ev.endTime); + } + + case 24: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + + return function (_x7) { + return _ref5.apply(this, arguments); + }; + }())); + + case 13: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }()); + this.subs.push(eventSub); + } + + var _proto2 = RxStorageInstancePouch.prototype; + + _proto2.addEventToChangeStream = function addEventToChangeStream(change, startTime, endTime) { + var doc = change.operation === 'DELETE' ? change.previous : change.doc; + var primaryKey = this.schema.primaryKey; + var primary = doc[primaryKey]; + var eventId = getEventKey(false, primary, doc._rev); + + if (this.emittedEventIds.has(eventId)) { + return; + } + + this.emittedEventIds.add(eventId); + var storageChangeEvent = { + eventId: eventId, + documentId: primary, + change: change, + startTime: startTime, + endTime: endTime + }; + this.changes$.next(storageChangeEvent); + }; + + _proto2.close = function close() { + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); // TODO this did not work because a closed pouchdb cannot be recreated in the same process run + // await this.internals.pouch.close(); + + return Promise.resolve(); + }; + + _proto2.remove = /*#__PURE__*/function () { + var _remove2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9() { + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return this.internals.pouch.destroy(); + + case 2: + case "end": + return _context9.stop(); + } + } + }, _callee9, this); + })); + + function remove() { + return _remove2.apply(this, arguments); + } + + return remove; + }(); + + _proto2.getSortComparator = function getSortComparator(query) { + var _ref6; + + var primaryKey = this.schema.primaryKey; + var sortOptions = query.sort ? query.sort : [(_ref6 = {}, _ref6[primaryKey] = 'asc', _ref6)]; + var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); + var inMemoryFields = Object.keys(query.selector); + + var fun = function fun(a, b) { + // TODO use createFieldSorter + // TODO make a performance test + var rows = [a, b].map(function (doc) { + // swap primary to _id + var cloned = (0, _util.flatClone)(doc); + var primaryValue = cloned[primaryKey]; + delete cloned[primaryKey]; + cloned._id = primaryValue; + return { + doc: cloned + }; + }); + var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, { + selector: massagedSelector, + sort: sortOptions + }, inMemoryFields); + + if (sortedRows[0].doc._id === rows[0].doc._id) { + return -1; + } else { + return 1; + } + }; + + return fun; + } + /** + * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js + */ + ; + + _proto2.getQueryMatcher = function getQueryMatcher(query) { + var primaryKey = this.schema.primaryKey; + var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); + + var fun = function fun(doc) { + var cloned = pouchSwapPrimaryToId(primaryKey, doc); + var row = { + doc: cloned + }; + var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { + selector: massagedSelector + }, Object.keys(query.selector)); + var ret = rowsMatched && rowsMatched.length === 1; + return ret; + }; + + return fun; + } + /** + * pouchdb has many bugs and strange behaviors + * this functions takes a normal mango query + * and transforms it to one that fits for pouchdb + */ + ; + + _proto2.prepareQuery = function prepareQuery(mutateableQuery) { + var _this4 = this; + + var primaryKey = this.schema.primaryKey; + var query = mutateableQuery; + /** + * because sort wont work on unused keys we have to workaround + * so we add the key to the selector if necessary + * @link https://github.com/nolanlawson/pouchdb-find/issues/204 + */ + + if (query.sort) { + query.sort.forEach(function (sortPart) { + var key = Object.keys(sortPart)[0]; + var comparisonOperators = ['$gt', '$gte', '$lt', '$lte']; + var keyUsed = query.selector[key] && Object.keys(query.selector[key]).some(function (op) { + return comparisonOperators.includes(op); + }) || false; + + if (!keyUsed) { + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(_this4.schema, key); + + if (!schemaObj) { + throw (0, _rxError.newRxError)('QU5', { + key: key + }); + } + + if (!query.selector[key]) { + query.selector[key] = {}; + } + + switch (schemaObj.type) { + case 'number': + case 'integer': + // TODO change back to -Infinity when issue resolved + // @link https://github.com/pouchdb/pouchdb/issues/6454 + // -Infinity does not work since pouchdb 6.2.0 + query.selector[key].$gt = -9999999999999999999999999999; + break; + + case 'string': + /** + * strings need an empty string, see + * @link https://github.com/pubkey/rxdb/issues/585 + */ + if (typeof query.selector[key] !== 'string') { + query.selector[key].$gt = ''; + } + + break; + + default: + query.selector[key].$gt = null; + break; + } + } + }); + } // regex does not work over the primary key + // TODO move this to dev mode + + + if (query.selector[primaryKey] && query.selector[primaryKey].$regex) { + throw (0, _rxError.newRxError)('QU4', { + path: primaryKey, + query: mutateableQuery + }); + } // primary-swap sorting + + + if (query.sort) { + var sortArray = query.sort.map(function (part) { + var _newPart; + + var key = Object.keys(part)[0]; + var direction = Object.values(part)[0]; + var useKey = key === primaryKey ? '_id' : key; + var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); + return newPart; + }); + query.sort = sortArray; + } // strip empty selectors + + + Object.entries(query.selector).forEach(function (_ref7) { + var k = _ref7[0], + v = _ref7[1]; + + if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { + delete query.selector[k]; + } + }); + query.selector = primarySwapPouchDbQuerySelector(query.selector, primaryKey); + return query; + }; + + _proto2.bulkAddRevisions = /*#__PURE__*/function () { + var _bulkAddRevisions = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(documents) { + var _this5 = this; + + var writeData; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + writeData = documents.map(function (doc) { + return pouchSwapPrimaryToId(_this5.schema.primaryKey, doc); + }); // we do not need the response here because pouchdb returns an empty array on new_edits: false + + _context10.next = 3; + return this.internals.pouch.bulkDocs(writeData, { + new_edits: false, + set_new_edit_as_latest_revision: true + }); + + case 3: + case "end": + return _context10.stop(); + } + } + }, _callee10, this); + })); + + function bulkAddRevisions(_x8) { + return _bulkAddRevisions.apply(this, arguments); + } + + return bulkAddRevisions; + }(); + + _proto2.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(documentWrites) { + var primaryKey, writeRowById, insertDocs, pouchResult, ret; + return _regenerator["default"].wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + primaryKey = this.schema.primaryKey; + writeRowById = new Map(); + insertDocs = documentWrites.map(function (writeData) { + var primary = writeData.document[primaryKey]; + writeRowById.set(primary, writeData); + var storeDocumentData = rxDocumentDataToPouchDocumentData(primaryKey, writeData.document); // if previous document exists, we have to send the previous revision to pouchdb. + + if (writeData.previous) { + storeDocumentData._rev = writeData.previous._rev; + } + + return storeDocumentData; + }); + _context12.next = 5; + return this.internals.pouch.bulkDocs(insertDocs, { + custom: { + writeRowById: writeRowById + } + }); + + case 5: + pouchResult = _context12.sent; + ret = { + success: new Map(), + error: new Map() + }; + _context12.next = 9; + return Promise.all(pouchResult.map( /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(resultRow) { + var writeRow, err, pushObj; + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + writeRow = (0, _util.getFromMapOrThrow)(writeRowById, resultRow.id); + + if (!resultRow.error) { + _context11.next = 6; + break; + } + + err = { + isError: true, + status: 409, + documentId: resultRow.id, + writeRow: writeRow + }; + ret.error.set(resultRow.id, err); + _context11.next = 18; + break; + + case 6: + pushObj = (0, _util.flatClone)(writeRow.document); + pushObj = pouchSwapIdToPrimary(primaryKey, pushObj); + pushObj._rev = resultRow.rev; // replace the inserted attachments with their diggest + + // replace the inserted attachments with their diggest + pushObj._attachments = {}; + + if (writeRow.document._attachments) { + _context11.next = 14; + break; + } + + writeRow.document._attachments = {}; + _context11.next = 17; + break; + + case 14: + _context11.next = 16; + return writeAttachmentsToAttachments(writeRow.document._attachments); + + case 16: + pushObj._attachments = _context11.sent; + + case 17: + ret.success.set(resultRow.id, pushObj); + + case 18: + case "end": + return _context11.stop(); + } + } + }, _callee11); + })); + + return function (_x10) { + return _ref8.apply(this, arguments); + }; + }())); + + case 9: + _context12.next = 11; + return (0, _util.promiseWait)(0).then(function () { + return (0, _util.promiseWait)(0); + }); + + case 11: + return _context12.abrupt("return", ret); + + case 12: + case "end": + return _context12.stop(); + } + } + }, _callee12, this); + })); + + function bulkWrite(_x9) { + return _bulkWrite2.apply(this, arguments); + } + + return bulkWrite; + }(); + + _proto2.query = /*#__PURE__*/function () { + var _query = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(preparedQuery) { + var primaryKey, findResult, ret; + return _regenerator["default"].wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + primaryKey = this.schema.primaryKey; + _context13.next = 3; + return this.internals.pouch.find(preparedQuery); + + case 3: + findResult = _context13.sent; + ret = { + documents: findResult.docs.map(function (pouchDoc) { + var useDoc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); + return useDoc; + }) + }; + return _context13.abrupt("return", ret); + + case 6: + case "end": + return _context13.stop(); + } + } + }, _callee13, this); + })); + + function query(_x11) { + return _query.apply(this, arguments); + } + + return query; + }(); + + _proto2.getAttachmentData = /*#__PURE__*/function () { + var _getAttachmentData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(documentId, attachmentId) { + var attachmentData; + return _regenerator["default"].wrap(function _callee14$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return this.internals.pouch.getAttachment(documentId, attachmentId); + + case 2: + attachmentData = _context14.sent; + return _context14.abrupt("return", attachmentData); + + case 4: + case "end": + return _context14.stop(); + } + } + }, _callee14, this); + })); + + function getAttachmentData(_x12, _x13) { + return _getAttachmentData.apply(this, arguments); + } + + return getAttachmentData; + }(); + + _proto2.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(ids, deleted) { + var _this6 = this; + + var primaryKey, viaChanges, retDocs, pouchResult, ret; + return _regenerator["default"].wrap(function _callee16$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + primaryKey = this.schema.primaryKey; + /** + * On deleted documents, pouchdb will only return the tombstone. + * So we have to get the properties directly for each document + * with the hack of getting the changes and then make one request per document + * with the latest revision. + * TODO create an issue at pouchdb on how to get the document data of deleted documents, + * when one past revision was written via new_edits=false + * @link https://stackoverflow.com/a/63516761/3443137 + */ + + if (!deleted) { + _context16.next = 9; + break; + } + + _context16.next = 4; + return this.internals.pouch.changes({ + live: false, + since: 0, + doc_ids: ids, + style: 'all_docs' + }); + + case 4: + viaChanges = _context16.sent; + retDocs = new Map(); + _context16.next = 8; + return Promise.all(viaChanges.results.map( /*#__PURE__*/function () { + var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(result) { + var firstDoc, useFirstDoc; + return _regenerator["default"].wrap(function _callee15$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + _context15.next = 2; + return _this6.internals.pouch.get(result.id, { + rev: result.changes[0].rev, + deleted: 'ok', + style: 'all_docs' + }); + + case 2: + firstDoc = _context15.sent; + useFirstDoc = pouchDocumentDataToRxDocumentData(primaryKey, firstDoc); + retDocs.set(result.id, useFirstDoc); + + case 5: + case "end": + return _context15.stop(); + } + } + }, _callee15); + })); + + return function (_x16) { + return _ref9.apply(this, arguments); + }; + }())); + + case 8: + return _context16.abrupt("return", retDocs); + + case 9: + _context16.next = 11; + return this.internals.pouch.allDocs({ + include_docs: true, + keys: ids + }); + + case 11: + pouchResult = _context16.sent; + ret = new Map(); + pouchResult.rows.filter(function (row) { + return !!row.doc; + }).forEach(function (row) { + var docData = row.doc; + docData = pouchDocumentDataToRxDocumentData(primaryKey, docData); + ret.set(row.id, docData); + }); + return _context16.abrupt("return", ret); + + case 15: + case "end": + return _context16.stop(); + } + } + }, _callee16, this); + })); + + function findDocumentsById(_x14, _x15) { + return _findDocumentsById.apply(this, arguments); + } + + return findDocumentsById; + }(); + + _proto2.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + + _proto2.getChangedDocuments = /*#__PURE__*/function () { + var _getChangedDocuments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(options) { + var pouchChangesOpts, pouchResults, changedDocuments, lastSequence; + return _regenerator["default"].wrap(function _callee17$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + pouchChangesOpts = { + live: false, + limit: options.limit, + include_docs: false, + since: options.startSequence, + descending: options.order === 'desc' ? true : false + }; + _context17.next = 3; + return this.internals.pouch.changes(pouchChangesOpts); + + case 3: + pouchResults = _context17.sent; + changedDocuments = pouchResults.results.filter(function (row) { + return !row.id.startsWith(POUCHDB_DESIGN_PREFIX); + }).map(function (row) { + return { + id: row.id, + sequence: row.seq + }; + }); + lastSequence = pouchResults.last_seq; + return _context17.abrupt("return", { + changedDocuments: changedDocuments, + lastSequence: lastSequence + }); + + case 7: + case "end": + return _context17.stop(); + } + } + }, _callee17, this); + })); + + function getChangedDocuments(_x17) { + return _getChangedDocuments.apply(this, arguments); + } + + return getChangedDocuments; + }(); + + return RxStorageInstancePouch; +}(); + +exports.RxStorageInstancePouch = RxStorageInstancePouch; + +var RxStoragePouch = /*#__PURE__*/function () { + function RxStoragePouch(adapter) { + var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.name = 'pouchdb'; + this.adapter = adapter; + this.pouchSettings = pouchSettings; + checkPouchAdapter(adapter); + } + /** + * create the same diggest as an attachment with that data + * would have created by pouchdb internally. + */ + + + var _proto3 = RxStoragePouch.prototype; + + _proto3.hash = function hash(data) { + return pouchHash(data); + }; + + _proto3.createPouch = /*#__PURE__*/function () { + var _createPouch = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18(location, options) { + var pouchDbParameters, pouchDBOptions, pouch; + return _regenerator["default"].wrap(function _callee18$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + pouchDbParameters = { + location: location, + adapter: (0, _util.adapterObject)(this.adapter), + settings: options + }; + pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); + pouch = new _pouchDb.PouchDB(pouchDbParameters.location, pouchDBOptions); + /** + * In the past we found some errors where the PouchDB is not directly useable + * so we we had to call .info() first to ensure it can be used. + * I commented this out for now to get faster database/collection creation. + * We might have to add this again if something fails. + */ + // await pouch.info(); + + return _context18.abrupt("return", pouch); + + case 4: + case "end": + return _context18.stop(); + } + } + }, _callee18, this); + })); + + function createPouch(_x18, _x19) { + return _createPouch.apply(this, arguments); + } + + return createPouch; + }(); + + _proto3.createStorageInstance = /*#__PURE__*/function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19(params) { + var pouchLocation, pouch; + return _regenerator["default"].wrap(function _callee19$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + pouchLocation = getPouchLocation(params.databaseName, params.collectionName, params.schema.version); + _context19.next = 3; + return this.createPouch(pouchLocation, params.options); + + case 3: + pouch = _context19.sent; + _context19.next = 6; + return createIndexesOnPouch(pouch, params.schema); + + case 6: + return _context19.abrupt("return", new RxStorageInstancePouch(params.databaseName, params.collectionName, params.schema, { + pouch: pouch + }, params.options)); + + case 7: + case "end": + return _context19.stop(); + } + } + }, _callee19, this); + })); + + function createStorageInstance(_x20) { + return _createStorageInstance.apply(this, arguments); + } + + return createStorageInstance; + }(); + + _proto3.createKeyObjectStorageInstance = /*#__PURE__*/function () { + var _createKeyObjectStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20(databaseName, collectionName, options) { + var useOptions, pouchLocation, pouch; + return _regenerator["default"].wrap(function _callee20$(_context20) { + while (1) { + switch (_context20.prev = _context20.next) { + case 0: + useOptions = (0, _util.flatClone)(options); // no compaction because this only stores local documents + + useOptions.auto_compaction = false; + useOptions.revs_limit = 1; + pouchLocation = getPouchLocation(databaseName, collectionName, 0); + _context20.next = 6; + return this.createPouch(pouchLocation, options); + + case 6: + pouch = _context20.sent; + return _context20.abrupt("return", new RxStorageKeyObjectInstancePouch(databaseName, collectionName, { + pouch: pouch + }, options)); + + case 8: + case "end": + return _context20.stop(); + } + } + }, _callee20, this); + })); + + function createKeyObjectStorageInstance(_x21, _x22, _x23) { + return _createKeyObjectStorageInstance.apply(this, arguments); + } + + return createKeyObjectStorageInstance; + }(); + + return RxStoragePouch; +}(); + +exports.RxStoragePouch = RxStoragePouch; + +function writeAttachmentsToAttachments(_x24) { + return _writeAttachmentsToAttachments.apply(this, arguments); +} +/** + * Checks if all is ok with the given adapter, + * else throws an error. + */ + + +function _writeAttachmentsToAttachments() { + _writeAttachmentsToAttachments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22(attachments) { + var ret; + return _regenerator["default"].wrap(function _callee22$(_context22) { + while (1) { + switch (_context22.prev = _context22.next) { + case 0: + if (attachments) { + _context22.next = 2; + break; + } + + return _context22.abrupt("return", {}); + + case 2: + ret = {}; + _context22.next = 5; + return Promise.all(Object.entries(attachments).map( /*#__PURE__*/function () { + var _ref14 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21(_ref13) { + var key, obj, asWrite, hash, asString, length; + return _regenerator["default"].wrap(function _callee21$(_context21) { + while (1) { + switch (_context21.prev = _context21.next) { + case 0: + key = _ref13[0], obj = _ref13[1]; + + if (obj.type) { + _context21.next = 3; + break; + } + + throw (0, _rxError.newRxError)('SNH', { + args: obj + }); + + case 3: + if (!obj.data) { + _context21.next = 15; + break; + } + + asWrite = obj; + _context21.next = 7; + return pouchHash(asWrite.data); + + case 7: + hash = _context21.sent; + _context21.next = 10; + return _util.blobBufferUtil.toString(asWrite.data); + + case 10: + asString = _context21.sent; + length = asString.length; + ret[key] = { + digest: hash, + length: length, + type: asWrite.type + }; + _context21.next = 16; + break; + + case 15: + ret[key] = obj; + + case 16: + case "end": + return _context21.stop(); + } + } + }, _callee21); + })); + + return function (_x27) { + return _ref14.apply(this, arguments); + }; + }())); + + case 5: + return _context22.abrupt("return", ret); + + case 6: + case "end": + return _context22.stop(); + } + } + }, _callee22); + })); + return _writeAttachmentsToAttachments.apply(this, arguments); +} + +function checkPouchAdapter(adapter) { + if (typeof adapter === 'string') { + // TODO make a function hasAdapter() + if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters[adapter]) { + throw (0, _rxError.newRxError)('DB9', { + adapter: adapter + }); + } + } else { + (0, _pouchDb.isLevelDown)(adapter); + + if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.leveldb) { + throw (0, _rxError.newRxError)('DB10', { + adapter: adapter + }); + } + } +} + +function pouchHash(data) { + return new Promise(function (res) { + (0, _pouchdbMd.binaryMd5)(data, function (digest) { + res('md5-' + digest); + }); + }); +} + +function pouchSwapIdToPrimary(primaryKey, docData) { + if (primaryKey === '_id' || docData[primaryKey]) { + return docData; + } + + docData = (0, _util.flatClone)(docData); + docData[primaryKey] = docData._id; + delete docData._id; + return docData; +} + +function pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc) { + var useDoc = pouchSwapIdToPrimary(primaryKey, pouchDoc); // always flat clone becaues we mutate the _attachments property. + + useDoc = (0, _util.flatClone)(useDoc); + delete useDoc._revisions; + useDoc._attachments = {}; + + if (pouchDoc._attachments) { + Object.entries(pouchDoc._attachments).forEach(function (_ref10) { + var key = _ref10[0], + value = _ref10[1]; + + if (value.data) { + useDoc._attachments[key] = { + data: value.data, + type: value.type + }; + } else { + useDoc._attachments[key] = { + digest: value.digest, + // TODO why do we need to access value.type? + type: value.type ? value.type : value.content_type, + length: value.length + }; + } + }); + } + + return useDoc; +} + +function rxDocumentDataToPouchDocumentData(primaryKey, doc) { + var pouchDoc = pouchSwapPrimaryToId(primaryKey, doc); // always flat clone becaues we mutate the _attachments property. + + pouchDoc = (0, _util.flatClone)(pouchDoc); + pouchDoc._attachments = {}; + + if (doc._attachments) { + Object.entries(doc._attachments).forEach(function (_ref11) { + var key = _ref11[0], + value = _ref11[1]; + var useValue = value; + + if (useValue.data) { + pouchDoc._attachments[key] = { + data: useValue.data, + content_type: useValue.type + }; + } else { + pouchDoc._attachments[key] = { + digest: useValue.digest, + content_type: useValue.type, + length: useValue.length, + stub: true + }; + } + }); + } + + return pouchDoc; +} +function pouchSwapPrimaryToId(primaryKey, docData) { + if (primaryKey === '_id') { + return docData; + } -function deleteOldCollection(oldCollection) { - return oldCollection.pouchdb.destroy().then(function () { - return oldCollection.database.removeCollectionDoc(oldCollection.dataMigrator.name, oldCollection.schema); + var ret = {}; + Object.entries(docData).forEach(function (entry) { + var newKey = entry[0] === primaryKey ? '_id' : entry[0]; + ret[newKey] = entry[1]; }); + return ret; } /** - * runs the migration on all documents and deletes the pouchdb afterwards + * in: '_local/foobar' + * out: 'foobar' */ -function migrateOldCollection(oldCollection) { - var batchSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; +function pouchStripLocalFlagFromPrimary(str) { + return str.substring(POUCHDB_LOCAL_PREFIX.length); +} - if (oldCollection._migrate) { - // already running - throw (0, _rxError.newRxError)('DM3'); +function getEventKey(isLocal, primary, revision) { + if (!primary) { + throw new Error('primary missing !!'); } - oldCollection._migrate = true; - var observer = new _rxjs.Subject(); - /** - * TODO this is a side-effect which might throw - * @see DataMigrator.migrate() - */ + var prefix = isLocal ? 'local' : 'non-local'; + var eventKey = prefix + '|' + primary + '|' + revision; + return eventKey; +} - (function () { - var error; +function pouchChangeRowToChangeEvent(primaryKey, pouchDoc) { + if (!pouchDoc) { + throw (0, _rxError.newRxError)('SNH', { + args: { + pouchDoc: pouchDoc + } + }); + } - var allBatchesDone = function allBatchesDone() { - // remove this oldCollection - return deleteOldCollection(oldCollection).then(function () { - return observer.complete(); - }); - }; + var id = pouchDoc._id; + var doc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); + var revHeight = (0, _util.getHeightOfRevision)(doc._rev); - var handleOneBatch = function handleOneBatch() { - return getBatchOfOldCollection(oldCollection, batchSize).then(function (batch) { - if (batch.length === 0) { - allBatchesDone(); - return false; - } else { - return Promise.all(batch.map(function (doc) { - return _migrateDocument(oldCollection, doc).then(function (action) { - return observer.next(action); - }); - }))["catch"](function (e) { - return error = e; - }).then(function () { - return true; - }); - } - }).then(function (next) { - if (!next) return; - if (error) observer.error(error);else handleOneBatch(); - }); + if (pouchDoc._deleted) { + return { + operation: 'DELETE', + id: id, + doc: null, + previous: doc }; - - handleOneBatch(); - })(); - - return observer.asObservable(); + } else if (revHeight === 1) { + return { + operation: 'INSERT', + id: id, + doc: doc, + previous: null + }; + } else { + return { + operation: 'UPDATE', + id: id, + doc: doc, + previous: 'UNKNOWN' + }; + } } -function migratePromise(oldCollection, batchSize) { - if (!oldCollection._migratePromise) { - oldCollection._migratePromise = new Promise(function (res, rej) { - var state$ = migrateOldCollection(oldCollection, batchSize); - state$.subscribe(null, rej, res); +function pouchChangeRowToChangeStreamEvent(primaryKey, pouchRow) { + var doc = pouchRow.doc; + + if (!doc) { + throw (0, _rxError.newRxError)('SNH', { + args: { + pouchRow: pouchRow + } }); } - return oldCollection._migratePromise; -} - - -},{"../../crypter":4,"../../hooks":7,"../../overwritable":9,"../../pouch-db":37,"../../rx-collection-helper":40,"../../rx-error":46,"../../rx-schema":48,"../../util":56,"./migration-state":29,"@babel/runtime/helpers/interopRequireDefault":65,"deep-equal":496,"rxjs":684,"rxjs/operators":908}],28:[function(require,module,exports){ -"use strict"; + var revHeight = (0, _util.getHeightOfRevision)(doc._rev); -Object.defineProperty(exports, "__esModule", { - value: true -}); -Object.defineProperty(exports, "_getOldCollections", { - enumerable: true, - get: function get() { - return _dataMigrator._getOldCollections; - } -}); -Object.defineProperty(exports, "getBatchOfOldCollection", { - enumerable: true, - get: function get() { - return _dataMigrator.getBatchOfOldCollection; - } -}); -Object.defineProperty(exports, "migrateDocumentData", { - enumerable: true, - get: function get() { - return _dataMigrator.migrateDocumentData; - } -}); -Object.defineProperty(exports, "_migrateDocument", { - enumerable: true, - get: function get() { - return _dataMigrator._migrateDocument; - } -}); -Object.defineProperty(exports, "deleteOldCollection", { - enumerable: true, - get: function get() { - return _dataMigrator.deleteOldCollection; - } -}); -Object.defineProperty(exports, "migrateOldCollection", { - enumerable: true, - get: function get() { - return _dataMigrator.migrateOldCollection; - } -}); -Object.defineProperty(exports, "migratePromise", { - enumerable: true, - get: function get() { - return _dataMigrator.migratePromise; - } -}); -Object.defineProperty(exports, "DataMigrator", { - enumerable: true, - get: function get() { - return _dataMigrator.DataMigrator; + if (pouchRow.deleted) { + var previousDoc = (0, _util.flatClone)(pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc)); + delete previousDoc._deleted; + var ev = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'DELETE', + doc: null, + previous: previousDoc + }; + return ev; + } else if (revHeight === 1) { + var _ev = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'INSERT', + doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), + previous: null + }; + return _ev; + } else { + var _ev2 = { + sequence: pouchRow.seq, + id: pouchRow.id, + operation: 'UPDATE', + doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), + previous: 'UNKNOWN' + }; + return _ev2; } -}); -exports.RxDBMigrationPlugin = exports.DATA_MIGRATOR_BY_COLLECTION = void 0; - -var _rxjs = require("rxjs"); +} +/** + * Runs a primary swap with transform all custom primaryKey occurences + * into '_id' + * @recursive + */ -var _operators = require("rxjs/operators"); -var _dataMigrator = require("./data-migrator"); +function primarySwapPouchDbQuerySelector(selector, primaryKey) { + if (primaryKey === '_id') { + return selector; + } -var _migrationState = require("./migration-state"); + if (Array.isArray(selector)) { + return selector.map(function (item) { + return primarySwapPouchDbQuerySelector(item, primaryKey); + }); + } else if (typeof selector === 'object') { + var ret = {}; + Object.entries(selector).forEach(function (_ref12) { + var k = _ref12[0], + v = _ref12[1]; -var DATA_MIGRATOR_BY_COLLECTION = new WeakMap(); -exports.DATA_MIGRATOR_BY_COLLECTION = DATA_MIGRATOR_BY_COLLECTION; -var RxDBMigrationPlugin = { - name: 'migration', - rxdb: true, - hooks: { - preDestroyRxDatabase: _migrationState.onDatabaseDestroy - }, - prototypes: { - RxDatabase: function RxDatabase(proto) { - proto.migrationStates = function () { - return (0, _migrationState.getMigrationStateByDatabase)(this).pipe((0, _operators.switchMap)(function (list) { - return (0, _rxjs.combineLatest)(list); - }), (0, _operators.shareReplay)({ - bufferSize: 1, - refCount: true - })); - }; - }, - RxCollection: function RxCollection(proto) { - proto.getDataMigrator = function () { - if (!DATA_MIGRATOR_BY_COLLECTION.has(this)) { - DATA_MIGRATOR_BY_COLLECTION.set(this, (0, _dataMigrator.createDataMigrator)(this.asRxCollection, this.migrationStrategies)); + if (k === primaryKey) { + ret._id = v; + } else { + if (k.startsWith('$')) { + ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); + } else { + ret[k] = v; } + } + }); + return ret; + } else { + return selector; + } +} +/** + * Creates the indexes of the schema inside of the pouchdb instance. + * Will skip indexes that already exist. + */ - return DATA_MIGRATOR_BY_COLLECTION.get(this); - }; - proto.migrationNeeded = function () { - return (0, _dataMigrator.mustMigrate)(this.getDataMigrator()); - }; - } - } -}; // used in tests +function createIndexesOnPouch(_x25, _x26) { + return _createIndexesOnPouch.apply(this, arguments); +} +/** + * returns the pouchdb-database-name + */ -exports.RxDBMigrationPlugin = RxDBMigrationPlugin; +function _createIndexesOnPouch() { + _createIndexesOnPouch = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee24(pouch, schema) { + var primaryKey, before, existingIndexes; + return _regenerator["default"].wrap(function _callee24$(_context24) { + while (1) { + switch (_context24.prev = _context24.next) { + case 0: + if (schema.indexes) { + _context24.next = 2; + break; + } -},{"./data-migrator":27,"./migration-state":29,"rxjs":684,"rxjs/operators":908}],29:[function(require,module,exports){ -"use strict"; + return _context24.abrupt("return"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getMigrationStateByDatabase = getMigrationStateByDatabase; -exports.onDatabaseDestroy = onDatabaseDestroy; -exports.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = void 0; + case 2: + primaryKey = schema.primaryKey; + _context24.next = 5; + return pouch.getIndexes(); + + case 5: + before = _context24.sent; + existingIndexes = new Set(before.indexes.map(function (idx) { + return idx.name; + })); + _context24.next = 9; + return Promise.all(schema.indexes.map( /*#__PURE__*/function () { + var _ref15 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23(indexMaybeArray) { + var indexArray, indexName; + return _regenerator["default"].wrap(function _callee23$(_context23) { + while (1) { + switch (_context23.prev = _context23.next) { + case 0: + indexArray = Array.isArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; + /** + * replace primary key with _id + * because that is the enforced primary key on pouchdb. + */ + + /** + * replace primary key with _id + * because that is the enforced primary key on pouchdb. + */ + indexArray = indexArray.map(function (key) { + if (key === primaryKey) { + return '_id'; + } else { + return key; + } + }); + indexName = 'idx-rxdb-index-' + indexArray.join(','); -var _rxjs = require("rxjs"); + if (!existingIndexes.has(indexName)) { + _context23.next = 5; + break; + } -var _util = require("../../util"); + return _context23.abrupt("return"); -var DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap(); -exports.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE; + case 5: + return _context23.abrupt("return", pouch.createIndex({ + name: indexName, + ddoc: indexName, + index: { + fields: indexArray + } + })); + + case 6: + case "end": + return _context23.stop(); + } + } + }, _callee23); + })); -function getMigrationStateByDatabase(database) { - if (!DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.has(database)) { - DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.set(database, new _rxjs.BehaviorSubject([])); - } + return function (_x28) { + return _ref15.apply(this, arguments); + }; + }())); - var subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database); - return (0, _util.ensureNotFalsy)(subject); + case 9: + case "end": + return _context24.stop(); + } + } + }, _callee24); + })); + return _createIndexesOnPouch.apply(this, arguments); } -/** - * Complete on database destroy - * so people do not have to unsubscribe - */ +function getPouchLocation(dbName, collectionName, schemaVersion) { + var prefix = dbName + '-rxdb-' + schemaVersion + '-'; -function onDatabaseDestroy(database) { - var subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database); + if (!collectionName.includes('/')) { + return prefix + collectionName; + } else { + // if collectionName is a path, we have to prefix the last part only + var split = collectionName.split('/'); + var last = split.pop(); + var ret = split.join('/'); + ret += '/' + prefix + last; + return ret; + } +} - if (subject) { - subject.complete(); +function getRxStoragePouch(adapter, pouchSettings) { + if (!adapter) { + throw new Error('adapter missing'); } + + var storage = new RxStoragePouch(adapter, pouchSettings); + return storage; } -},{"../../util":56,"rxjs":684}],30:[function(require,module,exports){ +},{"../../rx-error":48,"../../rx-schema-helper":50,"../../util":58,"./custom-events-plugin":31,"./pouch-db":33,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"pouchdb-md5":662,"pouchdb-selector-core":665,"rxjs":684}],35:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -4661,7 +7443,7 @@ var RxDBQueryBuilderPlugin = { exports.RxDBQueryBuilderPlugin = RxDBQueryBuilderPlugin; -},{"../../rx-query":47,"../../util":56,"./mquery/nosql-query-builder":32}],31:[function(require,module,exports){ +},{"../../rx-query":49,"../../util":58,"./mquery/nosql-query-builder":37}],36:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -4706,7 +7488,7 @@ function isObject(arg) { } -},{}],32:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -5260,7 +8042,7 @@ function createQueryBuilder(query) { } -},{"../../../rx-error":46,"./mquery-utils":31}],33:[function(require,module,exports){ +},{"../../../rx-error":48,"./mquery-utils":36}],38:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -5269,9 +8051,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.setPouchEventEmitter = setPouchEventEmitter; -exports.createRxReplicationState = createRxReplicationState; -exports.sync = sync; -exports.RxDBReplicationPlugin = exports.hooks = exports.prototypes = exports.rxdb = exports.RxReplicationStateBase = void 0; +exports.createRxCouchDBReplicationState = createRxCouchDBReplicationState; +exports.syncCouchDB = syncCouchDB; +exports.RxDBReplicationCouchDBPlugin = exports.hooks = exports.prototypes = exports.rxdb = exports.RxCouchDBReplicationStateBase = void 0; + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _pouchdbReplication = _interopRequireDefault(require("pouchdb-replication")); @@ -5281,24 +8067,20 @@ var _operators = require("rxjs/operators"); var _util = require("../util"); -var _core = require("../core"); - var _rxError = require("../rx-error"); -var _pouchDb = require("../pouch-db"); +var _pouchdb = require("../plugins/pouchdb"); var _rxCollection = require("../rx-collection"); -var _watchForChanges = require("./watch-for-changes"); +var _rxCollectionHelper = require("../rx-collection-helper"); /** * this plugin adds the RxCollection.sync()-function to rxdb * you can use it to sync collections with remote or local couchdb-instances */ // add pouchdb-replication-plugin -(0, _core.addRxPlugin)(_pouchdbReplication["default"]); // add the watch-for-changes-plugin - -(0, _core.addRxPlugin)(_watchForChanges.RxDBWatchForChangesPlugin); +(0, _pouchdb.addPouchPlugin)(_pouchdbReplication["default"]); /** * Contains all pouchdb instances that * are used inside of RxDB by collections or databases. @@ -5307,8 +8089,8 @@ var _watchForChanges = require("./watch-for-changes"); var INTERNAL_POUCHDBS = new WeakSet(); -var RxReplicationStateBase = /*#__PURE__*/function () { - function RxReplicationStateBase(collection, syncOptions) { +var RxCouchDBReplicationStateBase = /*#__PURE__*/function () { + function RxCouchDBReplicationStateBase(collection, syncOptions) { var _this = this; this._subs = []; @@ -5334,7 +8116,7 @@ var RxReplicationStateBase = /*#__PURE__*/function () { }); } - var _proto = RxReplicationStateBase.prototype; + var _proto = RxCouchDBReplicationStateBase.prototype; _proto.awaitInitialReplication = function awaitInitialReplication() { if (this.syncOptions.options && this.syncOptions.options.live) { @@ -5381,10 +8163,10 @@ var RxReplicationStateBase = /*#__PURE__*/function () { return Promise.resolve(true); }; - return RxReplicationStateBase; + return RxCouchDBReplicationStateBase; }(); -exports.RxReplicationStateBase = RxReplicationStateBase; +exports.RxCouchDBReplicationStateBase = RxCouchDBReplicationStateBase; function setPouchEventEmitter(rxRepState, evEmitter) { if (rxRepState._pouchEventEmitterObject) { @@ -5409,7 +8191,7 @@ function setPouchEventEmitter(rxRepState, evEmitter) { return doc.language !== 'query'; }) // remove internal docs .map(function (doc) { - return rxRepState.collection._handleFromPouch(doc); + return (0, _rxCollectionHelper._handleFromStorageInstance)(rxRepState.collection, doc); }) // do primary-swap and keycompression .forEach(function (doc) { return rxRepState._subjects.docs.next(doc); @@ -5431,17 +8213,30 @@ function setPouchEventEmitter(rxRepState, evEmitter) { })); // complete - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'complete').subscribe(function (info) { - /** - * when complete fires, it might be that not all changeEvents - * have passed throught, because of the delay of .wachtForChanges() - * Therefore we have to first ensure that all previous changeEvents have been handled - */ - var unhandledEvents = Array.from(rxRepState.collection._watchForChangesUnhandled); - Promise.all(unhandledEvents).then(function () { - return rxRepState._subjects.complete.next(info); - }); - })); // auto-cancel one-time replications on complelete to not cause memory leak + rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'complete').subscribe( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(info) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _util.promiseWait)(100); + + case 2: + rxRepState._subjects.complete.next(info); + + case 3: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); // auto-cancel one-time replications on complelete to not cause memory leak if (!rxRepState.syncOptions.options || !rxRepState.syncOptions.options.live) { @@ -5485,30 +8280,30 @@ function setPouchEventEmitter(rxRepState, evEmitter) { })); } -function createRxReplicationState(collection, syncOptions) { - return new RxReplicationStateBase(collection, syncOptions); +function createRxCouchDBReplicationState(collection, syncOptions) { + return new RxCouchDBReplicationStateBase(collection, syncOptions); } -function sync(_ref) { +function syncCouchDB(_ref2) { var _this2 = this; - var remote = _ref.remote, - _ref$waitForLeadershi = _ref.waitForLeadership, - waitForLeadership = _ref$waitForLeadershi === void 0 ? true : _ref$waitForLeadershi, - _ref$direction = _ref.direction, - direction = _ref$direction === void 0 ? { + var remote = _ref2.remote, + _ref2$waitForLeadersh = _ref2.waitForLeadership, + waitForLeadership = _ref2$waitForLeadersh === void 0 ? true : _ref2$waitForLeadersh, + _ref2$direction = _ref2.direction, + direction = _ref2$direction === void 0 ? { pull: true, push: true - } : _ref$direction, - _ref$options = _ref.options, - options = _ref$options === void 0 ? { + } : _ref2$direction, + _ref2$options = _ref2.options, + options = _ref2$options === void 0 ? { live: true, retry: true - } : _ref$options, - query = _ref.query; + } : _ref2$options, + query = _ref2.query; var useOptions = (0, _util.flatClone)(options); // prevent #641 by not allowing internal pouchdbs as remote - if ((0, _pouchDb.isInstanceOf)(remote) && INTERNAL_POUCHDBS.has(remote)) { + if ((0, _pouchdb.isInstanceOf)(remote) && INTERNAL_POUCHDBS.has(remote)) { throw (0, _rxError.newRxError)('RC3', { database: this.database.name, collection: this.name @@ -5516,9 +8311,8 @@ function sync(_ref) { } // if remote is RxCollection, get internal pouchdb - if ((0, _rxCollection.isInstanceOf)(remote)) { - remote.watchForChanges(); - remote = remote.pouch; + if ((0, _rxCollection.isRxCollection)(remote)) { + remote = remote.storageInstance.internals.pouch; } if (query && this !== query.collection) { @@ -5527,13 +8321,13 @@ function sync(_ref) { }); } - var syncFun = (0, _pouchDb.pouchReplicationFunction)(this.pouch, direction); + var syncFun = (0, _pouchdb.pouchReplicationFunction)(this.storageInstance.internals.pouch, direction); if (query) { - useOptions.selector = query.keyCompress().selector; + useOptions.selector = query.toJSON().selector; } - var repState = createRxReplicationState(this, { + var repState = createRxCouchDBReplicationState(this, { remote: remote, waitForLeadership: waitForLeadership, direction: direction, @@ -5548,8 +8342,6 @@ function sync(_ref) { return; } - _this2.watchForChanges(); - var pouchSync = syncFun(remote, useOptions); setPouchEventEmitter(repState, pouchSync); @@ -5562,26 +8354,30 @@ var rxdb = true; exports.rxdb = rxdb; var prototypes = { RxCollection: function RxCollection(proto) { - proto.sync = sync; + proto.syncCouchDB = syncCouchDB; } }; exports.prototypes = prototypes; var hooks = { createRxCollection: function createRxCollection(collection) { - INTERNAL_POUCHDBS.add(collection.pouch); + var pouch = collection.storageInstance.internals.pouch; + + if (pouch) { + INTERNAL_POUCHDBS.add(collection.storageInstance.internals.pouch); + } } }; exports.hooks = hooks; -var RxDBReplicationPlugin = { - name: 'replication', +var RxDBReplicationCouchDBPlugin = { + name: 'replication-couchdb', rxdb: rxdb, prototypes: prototypes, hooks: hooks }; -exports.RxDBReplicationPlugin = RxDBReplicationPlugin; +exports.RxDBReplicationCouchDBPlugin = RxDBReplicationCouchDBPlugin; -},{"../core":3,"../pouch-db":37,"../rx-collection":41,"../rx-error":46,"../util":56,"./watch-for-changes":36,"@babel/runtime/helpers/interopRequireDefault":65,"pouchdb-replication":664,"rxjs":684,"rxjs/operators":908}],34:[function(require,module,exports){ +},{"../plugins/pouchdb":32,"../rx-collection":44,"../rx-collection-helper":43,"../rx-error":48,"../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"pouchdb-replication":664,"rxjs":684,"rxjs/operators":908}],39:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -5608,7 +8404,9 @@ function update(updateObj) { function RxQueryUpdate(updateObj) { return this.exec().then(function (docs) { - if (!docs) return null; + if (!docs) { + return null; + } if (Array.isArray(docs)) { return Promise.all(docs.map(function (doc) { @@ -5644,426 +8442,101 @@ var RxDBUpdatePlugin = { exports.RxDBUpdatePlugin = RxDBUpdatePlugin; -},{"@babel/runtime/helpers/interopRequireDefault":65,"modifyjs":620}],35:[function(require,module,exports){ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxDBValidatePlugin = exports.hooks = exports.prototypes = exports.rxdb = void 0; - -var _isMyJsonValid = _interopRequireDefault(require("is-my-json-valid")); - -var _rxError = require("../rx-error"); - -var _util = require("../util"); - -/** - * this plugin validates documents before they can be inserted into the RxCollection. - * It's using is-my-json-valid as jsonschema-validator - * @link https://github.com/mafintosh/is-my-json-valid - */ - -/** - * cache the validators by the schema-hash - * so we can reuse them when multiple collections have the same schema - */ -var VALIDATOR_CACHE = new Map(); -/** - * returns the parsed validator from is-my-json-valid - */ - -function _getValidator(rxSchema) { - var hash = rxSchema.hash; - - if (!VALIDATOR_CACHE.has(hash)) { - var validator = (0, _isMyJsonValid["default"])(rxSchema.jsonSchema); - VALIDATOR_CACHE.set(hash, validator); - } - - return VALIDATOR_CACHE.get(hash); -} -/** - * validates the given object against the schema - * @param schemaPath if given, the sub-schema will be validated - * @throws {RxError} if not valid - */ - - -var validate = function validate(obj) { - var useValidator = _getValidator(this); - - var isValid = useValidator(obj); - if (isValid) return obj;else { - throw (0, _rxError.newRxError)('VD2', { - errors: useValidator.errors, - obj: obj, - schema: this.jsonSchema - }); - } -}; - -var runAfterSchemaCreated = function runAfterSchemaCreated(rxSchema) { - // pre-generate the isMyJsonValid-validator from the schema - (0, _util.requestIdleCallbackIfAvailable)(function () { - _getValidator(rxSchema); - }); -}; - -var rxdb = true; -exports.rxdb = rxdb; -var prototypes = { - /** - * set validate-function for the RxSchema.prototype - * @param prototype of RxSchema - */ - RxSchema: function RxSchema(proto) { - proto._getValidator = _getValidator; - proto.validate = validate; - } -}; -exports.prototypes = prototypes; -var hooks = { - createRxSchema: runAfterSchemaCreated -}; -exports.hooks = hooks; -var RxDBValidatePlugin = { - name: 'validate', - rxdb: rxdb, - prototypes: prototypes, - hooks: hooks -}; -exports.RxDBValidatePlugin = RxDBValidatePlugin; - - -},{"../rx-error":46,"../util":56,"@babel/runtime/helpers/interopRequireDefault":65,"is-my-json-valid":597}],36:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.watchForChanges = watchForChanges; -exports.RxDBWatchForChangesPlugin = exports.prototypes = exports.rxdb = void 0; - -var _rxjs = require("rxjs"); - -var _operators = require("rxjs/operators"); - -var _util = require("../util"); - -var _rxChangeEvent = require("../rx-change-event"); - -/** - * listens to changes of the internal pouchdb - * and ensures they are emitted to the internal RxChangeEvent-Stream - */ -function watchForChanges() { - var _this = this; - - // do not call twice on same collection - if (this.synced) return; - this.synced = true; - this._watchForChangesUnhandled = new Set(); - /** - * this will grap the changes and publish them to the rx-stream - * this is to ensure that changes from 'synced' dbs will be published - */ - - var pouch$ = (0, _rxjs.fromEvent)(this.pouch.changes({ - since: 'now', - live: true, - include_docs: true - }), 'change').pipe((0, _operators.map)(function (ar) { - return ar[0]; - }) // rxjs6.x fires an array for whatever reason - ).subscribe(function (change) { - var resPromise = _handleSingleChange(_this, change); // add and remove to the Set so RxReplicationState.complete$ can know when all events where handled - - - _this._watchForChangesUnhandled.add(resPromise); - - resPromise.then(function () { - _this._watchForChangesUnhandled["delete"](resPromise); - }); - }); - - this._subs.push(pouch$); -} -/** - * handles a single change-event - * and ensures that it is not already handled - */ - - -function _handleSingleChange(collection, change) { - if (change.id.charAt(0) === '_') { - // do not handle changes of internal docs - return Promise.resolve(false); - } - - var startTime = (0, _util.now)(); - var endTime = (0, _util.now)(); // wait 2 ticks and 20 ms to give the internal event-handling time to run - - return (0, _util.promiseWait)(20).then(function () { - return (0, _util.nextTick)(); - }).then(function () { - return (0, _util.nextTick)(); - }).then(function () { - var docData = change.doc; // already handled by internal event-stream - - if (collection._changeEventBuffer.hasChangeWithRevision(docData._rev)) { - return false; - } - - var cE = (0, _rxChangeEvent.changeEventfromPouchChange)(docData, collection, startTime, endTime); - collection.$emit(cE); - return true; - }); -} -/** - * After a collection is destroyed, - * we must await all promises of collection._watchForChangesUnhandled - * to ensure nothing is running anymore. - */ - - -function postDestroyRxCollection(collection) { - var unhandled = collection._watchForChangesUnhandled; - - if (!unhandled) { - return Promise.resolve(); - } - - return Promise.all(Array.from(unhandled)); -} - -var rxdb = true; -exports.rxdb = rxdb; -var prototypes = { - RxCollection: function RxCollection(proto) { - proto.watchForChanges = watchForChanges; - } -}; -exports.prototypes = prototypes; -var RxDBWatchForChangesPlugin = { - name: 'watch-for-changes', - rxdb: rxdb, - prototypes: prototypes, - hooks: { - postDestroyRxCollection: postDestroyRxCollection - } -}; -exports.RxDBWatchForChangesPlugin = RxDBWatchForChangesPlugin; - - -},{"../rx-change-event":39,"../util":56,"rxjs":684,"rxjs/operators":908}],37:[function(require,module,exports){ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.countAllUndeleted = countAllUndeleted; -exports.getBatch = getBatch; -exports.isLevelDown = isLevelDown; -exports.validateCouchDBString = validateCouchDBString; -exports.pouchReplicationFunction = pouchReplicationFunction; -exports.pouchAttachmentBinaryHash = pouchAttachmentBinaryHash; -exports.getNewestSequence = getNewestSequence; -exports.isInstanceOf = isInstanceOf; -exports.PouchDB = void 0; - -var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); - -var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); - -var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); - -var _pouchdbFind = _interopRequireDefault(require("pouchdb-find")); - -var _pouchdbMd = require("pouchdb-md5"); - -var _rxError = require("./rx-error"); - -var _util = require("./util"); - -/** - * this handles the pouchdb-instance - * to easy add modules and manipulate things - * Adapters can be found here: - * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules - */ -// pouchdb-find -_pouchdbCore["default"].plugin(_pouchdbFind["default"]); -/* -// comment in to debug -const pouchdbDebug = require('pouchdb-debug'); -PouchDB.plugin(pouchdbDebug); -PouchDB.debug.enable('*'); -*/ - - -/** - * get the number of all undeleted documents - */ -function countAllUndeleted(pouchdb) { - return pouchdb.allDocs({ - include_docs: false, - attachments: false - }).then(function (docs) { - return docs.rows.filter(function (row) { - return !row.id.startsWith('_design/'); - }).length; - }); -} -/** - * get a batch of documents from the pouch-instance - */ +},{"@babel/runtime/helpers/interopRequireDefault":67,"modifyjs":619}],40:[function(require,module,exports){ +"use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -function getBatch(pouchdb, limit) { - if (limit <= 1) { - throw (0, _rxError.newRxError)('P1', { - limit: limit - }); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RxDBValidatePlugin = exports.hooks = exports.prototypes = exports.rxdb = void 0; - return pouchdb.allDocs({ - include_docs: true, - attachments: false, - limit: limit - }).then(function (docs) { - return docs.rows.map(function (row) { - return row.doc; - }).filter(function (doc) { - return !doc._id.startsWith('_design'); - }); - }); -} -/** - * check if the given module is a leveldown-adapter - * throws if not - */ +var _isMyJsonValid = _interopRequireDefault(require("is-my-json-valid")); +var _rxError = require("../rx-error"); -function isLevelDown(adapter) { - if (!adapter || typeof adapter.super_ !== 'function') { - throw (0, _rxError.newRxError)('UT4', { - adapter: adapter - }); - } -} +var _util = require("../util"); -var validCouchDBStringRegexStr = '^[a-z][_$a-z0-9]*$'; -var validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr); /** - * validates that a given string is ok to be used with couchdb-collection-names - * @link https://wiki.apache.org/couchdb/HTTP_database_API - * @throws {Error} + * this plugin validates documents before they can be inserted into the RxCollection. + * It's using is-my-json-valid as jsonschema-validator + * @link https://github.com/mafintosh/is-my-json-valid */ -function validateCouchDBString(name) { - if (typeof name !== 'string' || name.length === 0) { - throw (0, _rxError.newRxTypeError)('UT1', { - name: name - }); - } // do not check, if foldername is given - +/** + * cache the validators by the schema-hash + * so we can reuse them when multiple collections have the same schema + */ +var VALIDATOR_CACHE = new Map(); +/** + * returns the parsed validator from is-my-json-valid + */ - if ((0, _util.isFolderPath)(name)) { - return true; - } +function _getValidator(rxSchema) { + var hash = rxSchema.hash; - if (!name.match(validCouchDBStringRegex)) { - throw (0, _rxError.newRxError)('UT2', { - regex: validCouchDBStringRegexStr, - givenName: name - }); + if (!VALIDATOR_CACHE.has(hash)) { + var validator = (0, _isMyJsonValid["default"])(rxSchema.jsonSchema); + VALIDATOR_CACHE.set(hash, validator); } - return true; + return VALIDATOR_CACHE.get(hash); } /** - * get the correct function-name for pouchdb-replication + * validates the given object against the schema + * @param schemaPath if given, the sub-schema will be validated + * @throws {RxError} if not valid */ -function pouchReplicationFunction(pouch, _ref) { - var _ref$pull = _ref.pull, - pull = _ref$pull === void 0 ? true : _ref$pull, - _ref$push = _ref.push, - push = _ref$push === void 0 ? true : _ref$push; - if (pull && push) return pouch.sync.bind(pouch); - if (!pull && push) return pouch.replicate.to.bind(pouch); - if (pull && !push) return pouch.replicate.from.bind(pouch); +var validate = function validate(obj) { + var useValidator = _getValidator(this); - if (!pull && !push) { - throw (0, _rxError.newRxError)('UT3', { - pull: pull, - push: push + var isValid = useValidator(obj); + if (isValid) return obj;else { + throw (0, _rxError.newRxError)('VD2', { + errors: useValidator.errors, + obj: obj, + schema: this.jsonSchema }); } -} -/** - * create the same diggest as an attachment with that data - * would have - */ - +}; -function pouchAttachmentBinaryHash(data) { - return new Promise(function (res) { - (0, _pouchdbMd.binaryMd5)(data, function (d) { - res('md5-' + d); - }); +var runAfterSchemaCreated = function runAfterSchemaCreated(rxSchema) { + // pre-generate the isMyJsonValid-validator from the schema + (0, _util.requestIdleCallbackIfAvailable)(function () { + _getValidator(rxSchema); }); -} - -function getNewestSequence(_x) { - return _getNewestSequence.apply(this, arguments); -} - -function _getNewestSequence() { - _getNewestSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(pouch) { - var pouchChanges; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return pouch.changes({ - live: false, - since: 0, - limit: 1, - descending: true, - include_docs: false - }); - - case 2: - pouchChanges = _context.sent; - return _context.abrupt("return", pouchChanges.last_seq); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - return _getNewestSequence.apply(this, arguments); -} - -function isInstanceOf(obj) { - return obj instanceof _pouchdbCore["default"]; -} +}; -var PouchDB = _pouchdbCore["default"]; -exports.PouchDB = PouchDB; +var rxdb = true; +exports.rxdb = rxdb; +var prototypes = { + /** + * set validate-function for the RxSchema.prototype + * @param prototype of RxSchema + */ + RxSchema: function RxSchema(proto) { + proto._getValidator = _getValidator; + proto.validate = validate; + } +}; +exports.prototypes = prototypes; +var hooks = { + createRxSchema: runAfterSchemaCreated +}; +exports.hooks = hooks; +var RxDBValidatePlugin = { + name: 'validate', + rxdb: rxdb, + prototypes: prototypes, + hooks: hooks +}; +exports.RxDBValidatePlugin = RxDBValidatePlugin; -},{"./rx-error":46,"./util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"pouchdb-core":655,"pouchdb-find":658,"pouchdb-md5":662}],38:[function(require,module,exports){ +},{"../rx-error":48,"../util":58,"@babel/runtime/helpers/interopRequireDefault":67,"is-my-json-valid":596}],41:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -6216,202 +8689,253 @@ function triggerCacheReplacement(rxCollection) { } -},{"./util":56}],39:[function(require,module,exports){ +},{"./util":58}],42:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.changeEventfromPouchChange = changeEventfromPouchChange; -exports.createInsertEvent = createInsertEvent; -exports.createUpdateEvent = createUpdateEvent; -exports.createDeleteEvent = createDeleteEvent; -exports.isInstanceOf = isInstanceOf; -exports.RxChangeEvent = void 0; +exports.getDocumentDataOfRxChangeEvent = getDocumentDataOfRxChangeEvent; +exports.isRxChangeEventIntern = isRxChangeEventIntern; +exports.rxChangeEventToEventReduceChangeEvent = rxChangeEventToEventReduceChangeEvent; + +var _overwritable = require("./overwritable"); /** * RxChangeEvents a emitted when something in the database changes * they can be grabbed by the observables of database, collection and document */ -var RxChangeEvent = /*#__PURE__*/function () { - function RxChangeEvent(operation, documentId, documentData, databaseToken, collectionName, isLocal, - /** - * timestam on when the operation was triggered - * and when it was finished - * This is optional because we do not have this time - * for events that come from pouchdbs changestream. - */ - startTime, endTime, previousData, rxDocument) { - this.operation = operation; - this.documentId = documentId; - this.documentData = documentData; - this.databaseToken = databaseToken; - this.collectionName = collectionName; - this.isLocal = isLocal; - this.startTime = startTime; - this.endTime = endTime; - this.previousData = previousData; - this.rxDocument = rxDocument; +function getDocumentDataOfRxChangeEvent(rxChangeEvent) { + if (rxChangeEvent.documentData) { + return rxChangeEvent.documentData; + } else { + return rxChangeEvent.previousDocumentData; } +} - var _proto = RxChangeEvent.prototype; +function isRxChangeEventIntern(rxChangeEvent) { + if (rxChangeEvent.collectionName && rxChangeEvent.collectionName.charAt(0) === '_') { + return true; + } else { + return false; + } +} - _proto.isIntern = function isIntern() { - if (this.collectionName && this.collectionName.charAt(0) === '_') { - return true; - } else { - return false; - } - }; +function rxChangeEventToEventReduceChangeEvent(rxChangeEvent) { + switch (rxChangeEvent.operation) { + case 'INSERT': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: rxChangeEvent.documentData, + previous: null + }; - _proto.toJSON = function toJSON() { - var ret = { - operation: this.operation, - documentId: this.documentId, - documentData: this.documentData, - previousData: this.previousData ? this.previousData : undefined, - databaseToken: this.databaseToken, - collectionName: this.collectionName, - isLocal: this.isLocal, - startTime: this.startTime, - endTime: this.endTime - }; - return ret; - }; + case 'UPDATE': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: _overwritable.overwritable.deepFreezeWhenDevMode(rxChangeEvent.documentData), + previous: rxChangeEvent.previousDocumentData ? rxChangeEvent.previousDocumentData : 'UNKNOWN' + }; - _proto.toEventReduceChangeEvent = function toEventReduceChangeEvent() { - switch (this.operation) { - case 'INSERT': - return { - operation: this.operation, - id: this.documentId, - doc: this.documentData, - previous: null - }; + case 'DELETE': + return { + operation: rxChangeEvent.operation, + id: rxChangeEvent.documentId, + doc: null, + previous: rxChangeEvent.previousDocumentData + }; + } +} - case 'UPDATE': - return { - operation: this.operation, - id: this.documentId, - doc: this.documentData, - previous: this.previousData ? this.previousData : 'UNKNOWN' - }; - case 'DELETE': - return { - operation: this.operation, - id: this.documentId, - doc: null, - previous: this.previousData - }; - } - }; +},{"./overwritable":9}],43:[function(require,module,exports){ +"use strict"; - return RxChangeEvent; -}(); +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -exports.RxChangeEvent = RxChangeEvent; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.writeToStorageInstance = writeToStorageInstance; +exports._handleToStorageInstance = _handleToStorageInstance; +exports._handleFromStorageInstance = _handleFromStorageInstance; +exports.fillObjectDataBeforeInsert = fillObjectDataBeforeInsert; -function changeEventfromPouchChange(changeDoc, collection, startTime, // time when the event was streamed out of pouchdb -endTime) { - var operation = changeDoc._rev.startsWith('1-') ? 'INSERT' : 'UPDATE'; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); - if (changeDoc._deleted) { - operation = 'DELETE'; - } // decompress / primarySwap +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _util = require("./util"); - var doc = collection._handleFromPouch(changeDoc); +var _rxError = require("./rx-error"); - var documentId = doc[collection.schema.primaryPath]; - var cE = new RxChangeEvent(operation, documentId, doc, collection.database.token, collection.name, false, startTime, endTime); - return cE; -} +var _hooks = require("./hooks"); -function createInsertEvent(collection, docData, startTime, endTime, doc) { - var ret = new RxChangeEvent('INSERT', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, null, doc); - return ret; -} +var _rxStorageHelper = require("./rx-storage-helper"); -function createUpdateEvent(collection, docData, previous, startTime, endTime, rxDocument) { - return new RxChangeEvent('UPDATE', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, previous, rxDocument); +/** + * Every write access on the storage engine, + * goes throught this method + * so we can run hooks and resolve stuff etc. + */ +function writeToStorageInstance(_x, _x2) { + return _writeToStorageInstance.apply(this, arguments); } +/** + * wrappers to process document data beofre/after it goes to the storage instnace. + * Used to handle keycompression, encryption etc + */ -function createDeleteEvent(collection, docData, previous, startTime, endTime, rxDocument) { - return new RxChangeEvent('DELETE', docData[collection.schema.primaryPath], docData, collection.database.token, collection.name, false, startTime, endTime, previous, rxDocument); -} -function isInstanceOf(obj) { - return obj instanceof RxChangeEvent; -} +function _writeToStorageInstance() { + _writeToStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collection, writeRow) { + var overwrite, + toStorageInstance, + writeResult, + ret, + _args2 = arguments; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + overwrite = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; + toStorageInstance = { + previous: writeRow.previous ? _handleToStorageInstance(collection, (0, _util.flatClone)(writeRow.previous)) : undefined, + document: _handleToStorageInstance(collection, (0, _util.flatClone)(writeRow.document)) + }; + case 2: + if (!true) { + _context2.next = 16; + break; + } -},{}],40:[function(require,module,exports){ -"use strict"; + _context2.prev = 3; + _context2.next = 6; + return collection.database.lockedRun(function () { + return (0, _rxStorageHelper.writeSingle)(collection.storageInstance, toStorageInstance); + }); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports._handleToPouch = _handleToPouch; -exports._handleFromPouch = _handleFromPouch; -exports.fillObjectDataBeforeInsert = fillObjectDataBeforeInsert; + case 6: + writeResult = _context2.sent; + // on success, just return the result + ret = _handleFromStorageInstance(collection, writeResult); + return _context2.abrupt("return", ret); + + case 11: + _context2.prev = 11; + _context2.t0 = _context2["catch"](3); + return _context2.delegateYield( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var useErr, primary, singleRes; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + useErr = _context2.t0; + primary = useErr.documentId; -var _util = require("./util"); + if (!(overwrite && useErr.status === 409)) { + _context.next = 11; + break; + } -var _rxError = require("./rx-error"); + _context.next = 5; + return collection.database.lockedRun(function () { + return (0, _rxStorageHelper.getSingleDocument)(collection.storageInstance, primary); + }); -/** - * wrappers for Pouch.put/get to handle keycompression etc - */ -function _handleToPouch(col, data) { - data = col._crypter.encrypt(data); - data = col.schema.swapPrimaryToId(data); + case 5: + singleRes = _context.sent; - if (col.schema.doKeyCompression()) { - data = col._keyCompressor.compress(data); - } + if (singleRes) { + _context.next = 8; + break; + } + + throw (0, _rxError.newRxError)('SNH'); - return data; + case 8: + toStorageInstance.previous = singleRes; // now we can retry + + _context.next = 16; + break; + + case 11: + if (!(useErr.status === 409)) { + _context.next = 15; + break; + } + + throw (0, _rxError.newRxError)('COL19', { + id: primary, + pouchDbError: useErr, + data: writeRow + }); + + case 15: + throw useErr; + + case 16: + case "end": + return _context.stop(); + } + } + }, _callee); + })(), "t1", 14); + + case 14: + _context2.next = 2; + break; + + case 16: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[3, 11]]); + })); + return _writeToStorageInstance.apply(this, arguments); +} + +function _handleToStorageInstance(col, data) { + data = col._crypter.encrypt(data); + var hookParams = { + collection: col, + doc: data + }; + (0, _hooks.runPluginHooks)('preWriteToStorageInstance', hookParams); + return hookParams.doc; } -function _handleFromPouch(col, data) { +function _handleFromStorageInstance(col, data) { var noDecrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - data = col.schema.swapIdToPrimary(data); - if (col.schema.doKeyCompression()) data = col._keyCompressor.decompress(data); + var hookParams = { + collection: col, + doc: data + }; + (0, _hooks.runPluginHooks)('postReadFromInstance', hookParams); if (noDecrypt) { - return data; + return hookParams.doc; } - data = col._crypter.decrypt(data); - return data; + return col._crypter.decrypt(hookParams.doc); } /** - * fills in the _id and the - * default data. - * This also clones the data + * fills in the default data. + * This also clones the data. */ function fillObjectDataBeforeInsert(collection, data) { var useJson = collection.schema.fillObjectWithDefaults(data); - - if (useJson._id && collection.schema.primaryPath !== '_id') { - throw (0, _rxError.newRxError)('COL2', { - data: data - }); - } // fill _id - - - if (collection.schema.primaryPath === '_id' && !useJson._id) { - useJson._id = (0, _util.generateId)(); - } - return useJson; } -},{"./rx-error":46,"./util":56}],41:[function(require,module,exports){ +},{"./hooks":7,"./rx-error":48,"./rx-storage-helper":52,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72}],44:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -6419,9 +8943,9 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.create = create; -exports.isInstanceOf = isInstanceOf; -exports["default"] = exports.RxCollectionBase = void 0; +exports.createRxCollection = createRxCollection; +exports.isRxCollection = isRxCollection; +exports.RxCollectionBase = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -6433,16 +8957,12 @@ var _operators = require("rxjs/operators"); var _util = require("./util"); -var _pouchDb = require("./pouch-db"); - var _rxCollectionHelper = require("./rx-collection-helper"); var _rxQuery = require("./rx-query"); var _rxSchema = require("./rx-schema"); -var _rxChangeEvent = require("./rx-change-event"); - var _rxError = require("./rx-error"); var _crypter = require("./crypter"); @@ -6453,21 +8973,23 @@ var _queryCache = require("./query-cache"); var _changeEventBuffer = require("./change-event-buffer"); -var _overwritable = require("./overwritable"); - var _hooks = require("./hooks"); var _rxDocument = require("./rx-document"); var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); +var _rxStorageHelper = require("./rx-storage-helper"); + +var _checkNames = require("./plugins/dev-mode/check-names"); + var HOOKS_WHEN = ['pre', 'post']; var HOOKS_KEYS = ['insert', 'save', 'remove', 'create']; var hooksApplied = false; var RxCollectionBase = /*#__PURE__*/function () { function RxCollectionBase(database, name, schema) { - var pouchSettings = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var instanceCreationOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var migrationStrategies = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var methods = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; var attachments = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; @@ -6481,15 +9003,17 @@ var RxCollectionBase = /*#__PURE__*/function () { this.hooks = {}; this._subs = []; this._repStates = new Set(); - this.pouch = {}; + this.storageInstance = {}; + this.localDocumentsStore = {}; this._docCache = (0, _docCache.createDocCache)(); this._queryCache = (0, _queryCache.createQueryCache)(); this._crypter = {}; + this._observable$ = {}; this._changeEventBuffer = {}; this.database = database; this.name = name; this.schema = schema; - this.pouchSettings = pouchSettings; + this.instanceCreationOptions = instanceCreationOptions; this.migrationStrategies = migrationStrategies; this.methods = methods; this.attachments = attachments; @@ -6506,49 +9030,95 @@ var RxCollectionBase = /*#__PURE__*/function () { var _proto = RxCollectionBase.prototype; - _proto.prepare = function prepare( - /** - * set to true if the collection data already exists on this storage adapter - */ - wasCreatedBefore) { - var _this = this; + _proto.prepare = /*#__PURE__*/function () { + var _prepare = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee( + /** + * set to true if the collection data already exists on this storage adapter + */ + wasCreatedBefore) { + var _this = this; - this.pouch = this.database._spawnPouchDB(this.name, this.schema.version, this.pouchSettings); + var storageInstanceCreationParams, _yield$Promise$all, storageInstance, localDocumentsStore, subDocs, subLocalDocs; - if (this.schema.doKeyCompression()) { - this._keyCompressor = _overwritable.overwritable.createKeyCompressor(this.schema); - } // we trigger the non-blocking things first and await them later so we can do stuff in the mean time + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + storageInstanceCreationParams = { + databaseName: this.database.name, + collectionName: this.name, + schema: this.schema.jsonSchema, + options: this.instanceCreationOptions + }; + (0, _hooks.runPluginHooks)('preCreateRxStorageInstance', storageInstanceCreationParams); + _context.next = 4; + return Promise.all([this.database.storage.createStorageInstance(storageInstanceCreationParams), this.database.storage.createKeyObjectStorageInstance(this.database.name, + /** + * Use a different collection name for the local documents instance + * so that the local docs can be kept while deleting the normal instance + * after migration. + */ + this.name + '-local', this.instanceCreationOptions)]); - /** - * Sometimes pouchdb emits before the instance is useable. - * To prevent random errors, we wait until the .info() call resolved - */ + case 4: + _yield$Promise$all = _context.sent; + storageInstance = _yield$Promise$all[0]; + localDocumentsStore = _yield$Promise$all[1]; + this.storageInstance = storageInstance; + this.localDocumentsStore = localDocumentsStore; // we trigger the non-blocking things first and await them later so we can do stuff in the mean time + + this._crypter = (0, _crypter.createCrypter)(this.database.password, this.schema); + this._observable$ = this.database.$.pipe((0, _operators.filter)(function (event) { + return event.collectionName === _this.name; + })); + this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(this.asRxCollection); + subDocs = storageInstance.changeStream().pipe((0, _operators.map)(function (storageEvent) { + return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(false, storageEvent, _this.database, _this); + })).subscribe(function (cE) { + _this.$emit(cE); + }); + this._subs.push(subDocs); - var spawnedPouchPromise = wasCreatedBefore ? Promise.resolve() : this.pouch.info(); - /** - * if wasCreatedBefore we can assume that the indexes already exist - * because changing them anyway requires a schema-version change - */ + subLocalDocs = this.localDocumentsStore.changeStream().pipe((0, _operators.map)(function (storageEvent) { + return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(true, storageEvent, _this.database, _this); + })).subscribe(function (cE) { + return _this.$emit(cE); + }); - var createIndexesPromise = wasCreatedBefore ? Promise.resolve() : _prepareCreateIndexes(this.asRxCollection, spawnedPouchPromise); - this._crypter = (0, _crypter.createCrypter)(this.database.password, this.schema); - this._observable$ = this.database.$.pipe((0, _operators.filter)(function (event) { - return event.collectionName === _this.name; - })); - this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(this.asRxCollection); + this._subs.push(subLocalDocs); + /** + * When a write happens to the collection + * we find the changed document in the docCache + * and tell it that it has to change its data. + */ - this._subs.push(this._observable$.pipe((0, _operators.filter)(function (cE) { - return !cE.isLocal; - })).subscribe(function (cE) { - // when data changes, send it to RxDocument in docCache - var doc = _this._docCache.get(cE.documentId); - if (doc) doc._handleChangeEvent(cE); + this._subs.push(this._observable$.pipe((0, _operators.filter)(function (cE) { + return !cE.isLocal; + })).subscribe(function (cE) { + // when data changes, send it to RxDocument in docCache + var doc = _this._docCache.get(cE.documentId); + + if (doc) { + doc._handleChangeEvent(cE); + } + })); + + case 17: + case "end": + return _context.stop(); + } + } + }, _callee, this); })); - return Promise.all([spawnedPouchPromise, createIndexesPromise]); - } // overwritte by migration-plugin + function prepare(_x) { + return _prepare.apply(this, arguments); + } + + return prepare; + }() // overwritte by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { @@ -6573,296 +9143,286 @@ var RxCollectionBase = /*#__PURE__*/function () { return this.getDataMigrator().migratePromise(batchSize); } /** - * wrappers for Pouch.put/get to handle keycompression etc + * wrapps pouch-find */ ; - _proto._handleToPouch = function _handleToPouch(docData) { - return (0, _rxCollectionHelper._handleToPouch)(this, docData); - }; + _proto._queryStorageInstance = + /*#__PURE__*/ + function () { + var _queryStorageInstance2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rxQuery, limit) { + var _this2 = this; + + var noDecrypt, + preparedQuery, + queryResult, + docs, + _args2 = arguments; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + noDecrypt = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; + preparedQuery = rxQuery.toJSON(); - _proto._handleFromPouch = function _handleFromPouch(docData) { - var noDecrypt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - return (0, _rxCollectionHelper._handleFromPouch)(this, docData, noDecrypt); - } - /** - * every write on the pouchdb - * is tunneld throught this function - */ - ; + if (limit) { + preparedQuery['limit'] = limit; + } - _proto._pouchPut = function _pouchPut(obj) { - var _this2 = this; + _context2.next = 5; + return this.database.lockedRun(function () { + return _this2.storageInstance.query(preparedQuery); + }); - var overwrite = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - obj = this._handleToPouch(obj); - return this.database.lockedRun(function () { - return _this2.pouch.put(obj); - })["catch"](function (err) { - if (overwrite && err.status === 409) { - return _this2.database.lockedRun(function () { - return _this2.pouch.get(obj._id); - }).then(function (exist) { - obj._rev = exist._rev; - return _this2.database.lockedRun(function () { - return _this2.pouch.put(obj); - }); - }); - } else if (err.status === 409) { - throw (0, _rxError.newRxError)('COL19', { - id: obj._id, - pouchDbError: err, - data: obj - }); - } else throw err; - }); - } - /** - * get document from pouchdb by its _id - */ - ; + case 5: + queryResult = _context2.sent; + docs = queryResult.documents.map(function (doc) { + return (0, _rxCollectionHelper._handleFromStorageInstance)(_this2, doc, noDecrypt); + }); + return _context2.abrupt("return", docs); - _proto._pouchGet = function _pouchGet(key) { - var _this3 = this; + case 8: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); - return this.pouch.get(key).then(function (doc) { - return _this3._handleFromPouch(doc); - }); + function _queryStorageInstance(_x2, _x3) { + return _queryStorageInstance2.apply(this, arguments); + } + + return _queryStorageInstance; + }(); + + _proto.$emit = function $emit(changeEvent) { + return this.database.$emit(changeEvent); } /** - * wrapps pouch-find + * TODO internally call bulkInsert + * to not have duplicated code. */ ; - _proto._pouchFind = function _pouchFind(rxQuery, limit) { - var _this4 = this; + _proto.insert = + /*#__PURE__*/ + function () { + var _insert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(json) { + var tempDoc, useJson, newDoc, insertResult; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + // inserting a temporary-document + tempDoc = null; + + if (!(0, _rxDocument.isRxDocument)(json)) { + _context3.next = 6; + break; + } - var noDecrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var compressedQueryJSON = rxQuery.keyCompress(); + tempDoc = json; - if (limit) { - compressedQueryJSON['limit'] = limit; - } + if (tempDoc._isTemporary) { + _context3.next = 5; + break; + } - return this.database.lockedRun(function () { - return _this4.pouch.find(compressedQueryJSON); - }).then(function (docsCompressed) { - var docs = docsCompressed.docs.map(function (doc) { - return _this4._handleFromPouch(doc, noDecrypt); - }); - return docs; - }); - }; + throw (0, _rxError.newRxError)('COL1', { + data: json + }); - _proto.$emit = function $emit(changeEvent) { - return this.database.$emit(changeEvent); - }; + case 5: + json = tempDoc.toJSON(); - _proto.insert = function insert(json) { - var _this5 = this; + case 6: + useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this, json); + newDoc = tempDoc; + _context3.next = 10; + return this._runHooks('pre', 'insert', useJson); - // inserting a temporary-document - var tempDoc = null; + case 10: + this.schema.validate(useJson); + _context3.next = 13; + return (0, _rxCollectionHelper.writeToStorageInstance)(this, { + document: useJson + }); - if ((0, _rxDocument.isInstanceOf)(json)) { - tempDoc = json; + case 13: + insertResult = _context3.sent; - if (!tempDoc._isTemporary) { - throw (0, _rxError.newRxError)('COL1', { - data: json - }); - } + if (tempDoc) { + tempDoc._dataSync$.next(insertResult); + } else { + newDoc = (0, _rxDocumentPrototypeMerge.createRxDocument)(this, insertResult); + } - json = tempDoc.toJSON(); - } + _context3.next = 17; + return this._runHooks('post', 'insert', useJson, newDoc); - var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this, json); - var newDoc = tempDoc; - var startTime; - var endTime; - return this._runHooks('pre', 'insert', useJson).then(function () { - _this5.schema.validate(useJson); + case 17: + return _context3.abrupt("return", newDoc); - startTime = (0, _util.now)(); - return _this5._pouchPut(useJson); - }).then(function (insertResult) { - endTime = (0, _util.now)(); - useJson[_this5.schema.primaryPath] = insertResult.id; - useJson._rev = insertResult.rev; + case 18: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); - if (tempDoc) { - tempDoc._dataSync$.next(useJson); - } else newDoc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this5, useJson); + function insert(_x4) { + return _insert.apply(this, arguments); + } - return _this5._runHooks('post', 'insert', useJson, newDoc); - }).then(function () { - // event - var emitEvent = (0, _rxChangeEvent.createInsertEvent)(_this5, useJson, startTime, endTime, newDoc); + return insert; + }(); - _this5.$emit(emitEvent); + _proto.bulkInsert = /*#__PURE__*/function () { + var _bulkInsert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(docsData) { + var _this3 = this; - return newDoc; - }); - }; + var useDocs, docs, insertDocs, docsMap, results, successEntries, rxDocuments; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + useDocs = docsData.map(function (docData) { + var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this3, docData); + return useDocData; + }); + _context4.next = 3; + return Promise.all(useDocs.map(function (doc) { + return _this3._runHooks('pre', 'insert', doc).then(function () { + _this3.schema.validate(doc); - _proto.bulkInsert = function bulkInsert(docsData) { - var _this6 = this; + return doc; + }); + })); - var useDocs = docsData.map(function (docData) { - var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this6, docData); - return useDocData; - }); - return Promise.all(useDocs.map(function (doc) { - return _this6._runHooks('pre', 'insert', doc).then(function () { - _this6.schema.validate(doc); + case 3: + docs = _context4.sent; + insertDocs = docs.map(function (d) { + return { + document: (0, _rxCollectionHelper._handleToStorageInstance)(_this3, d) + }; + }); + docsMap = new Map(); + docs.forEach(function (d) { + docsMap.set(d[_this3.schema.primaryPath], d); + }); + _context4.next = 9; + return this.database.lockedRun(function () { + return _this3.storageInstance.bulkWrite(insertDocs); + }); - return doc; - }); - })).then(function (docs) { - var insertDocs = docs.map(function (d) { - return _this6._handleToPouch(d); - }); - var docsMap = new Map(); - docs.forEach(function (d) { - docsMap.set(d[_this6.schema.primaryPath], d); - }); - return _this6.database.lockedRun(function () { - var startTime = (0, _util.now)(); - return _this6.pouch.bulkDocs(insertDocs).then(function (results) { - var okResults = results.filter(function (r) { - return r.ok; - }); // create documents - - var rxDocuments = okResults.map(function (r) { - var docData = docsMap.get(r.id); - docData._rev = r.rev; - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this6, docData); - return doc; - }); - return Promise.all(rxDocuments.map(function (doc) { - return _this6._runHooks('post', 'insert', docsMap.get(doc.primary), doc); - })).then(function () { - var errorResults = results.filter(function (r) { - return !r.ok; - }); - return { - rxDocuments: rxDocuments, - errorResults: errorResults - }; - }); - }).then(function (_ref) { - var rxDocuments = _ref.rxDocuments, - errorResults = _ref.errorResults; - var endTime = (0, _util.now)(); // emit events + case 9: + results = _context4.sent; + // create documents + successEntries = Array.from(results.success.entries()); + rxDocuments = successEntries.map(function (_ref) { + var key = _ref[0], + writtenDocData = _ref[1]; + var docData = (0, _util.getFromMapOrThrow)(docsMap, key); + docData._rev = writtenDocData._rev; + var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this3, docData); + return doc; + }); + _context4.next = 14; + return Promise.all(rxDocuments.map(function (doc) { + return _this3._runHooks('post', 'insert', docsMap.get(doc.primary), doc); + })); + + case 14: + return _context4.abrupt("return", { + success: rxDocuments, + error: Array.from(results.error.values()) + }); - rxDocuments.forEach(function (doc) { - var emitEvent = (0, _rxChangeEvent.createInsertEvent)(_this6, doc.toJSON(true), startTime, endTime, doc); + case 15: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); - _this6.$emit(emitEvent); - }); - return { - success: rxDocuments, - error: errorResults - }; - }); - }); - }); - }; + function bulkInsert(_x5) { + return _bulkInsert.apply(this, arguments); + } + + return bulkInsert; + }(); _proto.bulkRemove = /*#__PURE__*/function () { - var _bulkRemove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(ids) { - var _this7 = this; + var _bulkRemove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(ids) { + var _this4 = this; - var rxDocumentMap, docsData, docsMap, removeDocs, startTime, results, endTime, okResults, rxDocuments; - return _regenerator["default"].wrap(function _callee2$(_context2) { + var rxDocumentMap, docsData, docsMap, removeDocs, results, successIds, rxDocuments; + return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context5.prev = _context5.next) { case 0: - _context2.next = 2; + _context5.next = 2; return this.findByIds(ids); case 2: - rxDocumentMap = _context2.sent; + rxDocumentMap = _context5.sent; docsData = []; docsMap = new Map(); Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { - var data = rxDocument.toJSON(true); + var data = (0, _util.clone)(rxDocument.toJSON(true)); docsData.push(data); docsMap.set(rxDocument.primary, data); }); - _context2.next = 8; + _context5.next = 8; return Promise.all(docsData.map(function (doc) { - var primary = doc[_this7.schema.primaryPath]; - return _this7._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); + var primary = doc[_this4.schema.primaryPath]; + return _this4._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); })); case 8: - docsData.forEach(function (doc) { - return doc._deleted = true; - }); removeDocs = docsData.map(function (doc) { - return _this7._handleToPouch(doc); + var writeDoc = (0, _util.flatClone)(doc); + writeDoc._deleted = true; + return { + previous: (0, _rxCollectionHelper._handleToStorageInstance)(_this4, doc), + document: (0, _rxCollectionHelper._handleToStorageInstance)(_this4, writeDoc) + }; + }); + _context5.next = 11; + return this.database.lockedRun(function () { + return _this4.storageInstance.bulkWrite(removeDocs); }); - _context2.next = 12; - return this.database.lockedRun( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { - var bulkResults; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - startTime = (0, _util.now)(); - _context.next = 3; - return _this7.pouch.bulkDocs(removeDocs); - - case 3: - bulkResults = _context.sent; - return _context.abrupt("return", bulkResults); - case 5: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); + case 11: + results = _context5.sent; + successIds = Array.from(results.success.keys()); // run hooks - case 12: - results = _context2.sent; - endTime = (0, _util.now)(); - okResults = results.filter(function (r) { - return r.ok; - }); - _context2.next = 17; - return Promise.all(okResults.map(function (r) { - return _this7._runHooks('post', 'remove', docsMap.get(r.id), rxDocumentMap.get(r.id)); + _context5.next = 15; + return Promise.all(successIds.map(function (id) { + return _this4._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); })); - case 17: - okResults.forEach(function (r) { - var rxDocument = rxDocumentMap.get(r.id); - var emitEvent = (0, _rxChangeEvent.createDeleteEvent)(_this7, docsMap.get(r.id), rxDocument._data, startTime, endTime, rxDocument); - - _this7.$emit(emitEvent); - }); - rxDocuments = okResults.map(function (r) { - return rxDocumentMap.get(r.id); + case 15: + rxDocuments = successIds.map(function (id) { + return rxDocumentMap.get(id); }); - return _context2.abrupt("return", { + return _context5.abrupt("return", { success: rxDocuments, - error: okResults.filter(function (r) { - return !r.ok; - }) + error: Array.from(results.error.values()) }); - case 20: + case 17: case "end": - return _context2.stop(); + return _context5.stop(); } } - }, _callee2, this); + }, _callee5, this); })); - function bulkRemove(_x) { + function bulkRemove(_x6) { return _bulkRemove.apply(this, arguments); } @@ -6874,7 +9434,7 @@ var RxCollectionBase = /*#__PURE__*/function () { ; _proto.upsert = function upsert(json) { - var _this8 = this; + var _this5 = this; var useJson = (0, _util.flatClone)(json); var primary = useJson[this.schema.primaryPath]; @@ -6895,7 +9455,7 @@ var RxCollectionBase = /*#__PURE__*/function () { return existing; }); } else { - return _this8.insert(json); + return _this5.insert(json); } }); } @@ -6905,7 +9465,7 @@ var RxCollectionBase = /*#__PURE__*/function () { ; _proto.atomicUpsert = function atomicUpsert(json) { - var _this9 = this; + var _this6 = this; var primary = json[this.schema.primaryPath]; @@ -6925,13 +9485,21 @@ var RxCollectionBase = /*#__PURE__*/function () { } queue = queue.then(function () { - return _atomicUpsertEnsureRxDocumentExists(_this9, primary, json); + return _atomicUpsertEnsureRxDocumentExists(_this6, primary, json); }).then(function (wasInserted) { if (!wasInserted.inserted) { - return _atomicUpsertUpdate(wasInserted.doc, json).then(function () { - return (0, _util.nextTick)(); - }) // tick here so the event can propagate + return _atomicUpsertUpdate(wasInserted.doc, json) + /** + * tick here so the event can propagate + * TODO we should not need that here + */ .then(function () { + return (0, _util.nextTick)(); + }).then(function () { + return (0, _util.nextTick)(); + }).then(function () { + return (0, _util.nextTick)(); + }).then(function () { return wasInserted.doc; }); } else return wasInserted.doc; @@ -6961,10 +9529,10 @@ var RxCollectionBase = /*#__PURE__*/function () { var query; if (typeof queryObj === 'string') { + var _selector; + query = (0, _rxQuery.createRxQuery)('findOne', { - selector: { - _id: queryObj - } + selector: (_selector = {}, _selector[this.schema.primaryPath] = queryObj, _selector) }, this); } else { if (!queryObj) { @@ -6996,19 +9564,19 @@ var RxCollectionBase = /*#__PURE__*/function () { _proto.findByIds = /*#__PURE__*/ function () { - var _findByIds = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(ids) { - var _this10 = this; + var _findByIds = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(ids) { + var _this7 = this; - var ret, mustBeQueried, result; - return _regenerator["default"].wrap(function _callee3$(_context3) { + var ret, mustBeQueried, docs; + return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { - switch (_context3.prev = _context3.next) { + switch (_context6.prev = _context6.next) { case 0: ret = new Map(); mustBeQueried = []; // first try to fill from docCache ids.forEach(function (id) { - var doc = _this10._docCache.get(id); + var doc = _this7._docCache.get(id); if (doc) { ret.set(id, doc); @@ -7018,42 +9586,33 @@ var RxCollectionBase = /*#__PURE__*/function () { }); // find everything which was not in docCache if (!(mustBeQueried.length > 0)) { - _context3.next = 8; + _context6.next = 8; break; } - _context3.next = 6; - return this.pouch.allDocs({ - include_docs: true, - keys: mustBeQueried - }); + _context6.next = 6; + return this.storageInstance.findDocumentsById(mustBeQueried, false); case 6: - result = _context3.sent; - result.rows.forEach(function (row) { - if (!row.doc) { - // not found - return; - } - - var plainData = _this10._handleFromPouch(row.doc); - - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this10, plainData); + docs = _context6.sent; + Array.from(docs.values()).forEach(function (docData) { + docData = (0, _rxCollectionHelper._handleFromStorageInstance)(_this7, docData); + var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this7, docData); ret.set(doc.primary, doc); }); case 8: - return _context3.abrupt("return", ret); + return _context6.abrupt("return", ret); case 9: case "end": - return _context3.stop(); + return _context6.stop(); } } - }, _callee3, this); + }, _callee6, this); })); - function findByIds(_x2) { + function findByIds(_x7) { return _findByIds.apply(this, arguments); } @@ -7066,12 +9625,12 @@ var RxCollectionBase = /*#__PURE__*/function () { ; _proto.findByIds$ = function findByIds$(ids) { - var _this11 = this; + var _this8 = this; var currentValue = null; var lastChangeEvent = -1; var initialPromise = this.findByIds(ids).then(function (docsMap) { - lastChangeEvent = _this11._changeEventBuffer.counter; + lastChangeEvent = _this8._changeEventBuffer.counter; currentValue = docsMap; }); return this.$.pipe((0, _operators.startWith)(null), (0, _operators.mergeMap)(function (ev) { @@ -7086,32 +9645,32 @@ var RxCollectionBase = /*#__PURE__*/function () { * since the last subscription. */ (0, _operators.mergeMap)( /*#__PURE__*/function () { - var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ev) { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(ev) { var resultMap, missedChangeEvents, newResult; - return _regenerator["default"].wrap(function _callee4$(_context4) { + return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { - switch (_context4.prev = _context4.next) { + switch (_context7.prev = _context7.next) { case 0: resultMap = (0, _util.ensureNotFalsy)(currentValue); - missedChangeEvents = _this11._changeEventBuffer.getFrom(lastChangeEvent + 1); + missedChangeEvents = _this8._changeEventBuffer.getFrom(lastChangeEvent + 1); if (!(missedChangeEvents === null)) { - _context4.next = 10; + _context7.next = 10; break; } - _context4.next = 5; - return _this11.findByIds(ids); + _context7.next = 5; + return _this8.findByIds(ids); case 5: - newResult = _context4.sent; - lastChangeEvent = _this11._changeEventBuffer.counter; - Array.from(newResult.entries()).forEach(function (_ref4) { - var k = _ref4[0], - v = _ref4[1]; + newResult = _context7.sent; + lastChangeEvent = _this8._changeEventBuffer.counter; + Array.from(newResult.entries()).forEach(function (_ref3) { + var k = _ref3[0], + v = _ref3[1]; return resultMap.set(k, v); }); - _context4.next = 11; + _context7.next = 11; break; case 10: @@ -7121,25 +9680,25 @@ var RxCollectionBase = /*#__PURE__*/function () { var op = rxChangeEvent.operation; if (op === 'INSERT' || op === 'UPDATE') { - resultMap.set(rxChangeEvent.documentId, _this11._docCache.get(rxChangeEvent.documentId)); + resultMap.set(rxChangeEvent.documentId, _this8._docCache.get(rxChangeEvent.documentId)); } else { resultMap["delete"](rxChangeEvent.documentId); } }); case 11: - return _context4.abrupt("return", resultMap); + return _context7.abrupt("return", resultMap); case 12: case "end": - return _context4.stop(); + return _context7.stop(); } } - }, _callee4); + }, _callee7); })); - return function (_x3) { - return _ref3.apply(this, arguments); + return function (_x8) { + return _ref2.apply(this, arguments); }; }()), (0, _operators.filter)(function (x) { return !!x; @@ -7157,36 +9716,26 @@ var RxCollectionBase = /*#__PURE__*/function () { */ ; - _proto.dump = function dump() { + _proto.exportJSON = function exportJSON() { var _decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; throw (0, _util.pluginMissing)('json-dump'); } /** * Import the parsed JSON export into the collection. - * @param _exportedJSON The previously exported data from the `.dump()` method. + * @param _exportedJSON The previously exported data from the `.exportJSON()` method. */ ; - _proto.importDump = function importDump(_exportedJSON) { + _proto.importJSON = function importJSON(_exportedJSON) { throw (0, _util.pluginMissing)('json-dump'); } /** - * waits for external changes to the database - * and ensures they are emitted to the internal RxChangeEvent-Stream - * TODO this can be removed by listening to the pull-change-events of the RxReplicationState + * sync with a CouchDB endpoint */ ; - _proto.watchForChanges = function watchForChanges() { - throw (0, _util.pluginMissing)('watch-for-changes'); - } - /** - * sync with another database - */ - ; - - _proto.sync = function sync(_syncOptions) { + _proto.syncCouchDB = function syncCouchDB(_syncOptions) { throw (0, _util.pluginMissing)('replication'); } /** @@ -7308,6 +9857,8 @@ var RxCollectionBase = /*#__PURE__*/function () { }; _proto.destroy = function destroy() { + var _this9 = this; + if (this.destroyed) { return Promise.resolve(false); } @@ -7327,10 +9878,12 @@ var RxCollectionBase = /*#__PURE__*/function () { Array.from(this._repStates).forEach(function (replicationState) { return replicationState.cancel(); }); - delete this.database.collections[this.name]; - this.destroyed = true; - return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', this).then(function () { - return true; + return this.storageInstance.close().then(function () { + delete _this9.database.collections[_this9.name]; + _this9.destroyed = true; + return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', _this9).then(function () { + return true; + }); }); } /** @@ -7371,11 +9924,11 @@ var RxCollectionBase = /*#__PURE__*/function () { }, { key: "onDestroy", get: function get() { - var _this12 = this; + var _this10 = this; if (!this._onDestroy) { this._onDestroy = new Promise(function (res) { - return _this12._onDestroyCall = res; + return _this10._onDestroyCall = res; }); } @@ -7429,6 +9982,19 @@ function _atomicUpsertUpdate(doc, json) { function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { + /** + * Optimisation shortcut, + * first try to find the document in the doc-cache + */ + var docFromCache = rxCollection._docCache.get(primary); + + if (docFromCache) { + return Promise.resolve({ + doc: docFromCache, + inserted: false + }); + } + return rxCollection.findOne(primary).exec().then(function (doc) { if (!doc) { return rxCollection.insert(json).then(function (newDoc) { @@ -7445,90 +10011,32 @@ function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { } }); } -/** - * creates the indexes in the pouchdb - */ - - -function _prepareCreateIndexes(rxCollection, spawnedPouchPromise) { - /** - * pouchdb does no check on already existing indexes - * which makes collection re-creation really slow on page reloads - * So we have to manually check if the index already exists - */ - return spawnedPouchPromise.then(function () { - return rxCollection.pouch.getIndexes(); - }).then(function (indexResult) { - var existingIndexes = new Set(); - indexResult.indexes.forEach(function (idx) { - return existingIndexes.add(idx.name); - }); - return existingIndexes; - }).then(function (existingIndexes) { - return Promise.all(rxCollection.schema.indexes.map(function (indexAr) { - var compressedIdx = indexAr.map(function (key) { - var primPath = rxCollection.schema.primaryPath; - var useKey = key === primPath ? '_id' : key; - - if (!rxCollection.schema.doKeyCompression()) { - return useKey; - } else { - var indexKey = rxCollection._keyCompressor.transformKey(useKey); - - return indexKey; - } - }); - var indexName = 'idx-rxdb-index-' + compressedIdx.join(','); - - if (existingIndexes.has(indexName)) { - // index already exists - return; - } - /** - * TODO - * we might have even better performance by doing a bulkDocs - * on index creation - */ - - - return spawnedPouchPromise.then(function () { - return rxCollection.pouch.createIndex({ - name: indexName, - ddoc: indexName, - index: { - fields: compressedIdx - } - }); - }); - })); - }); -} /** * creates and prepares a new collection */ -function create(_ref5, wasCreatedBefore) { - var database = _ref5.database, - name = _ref5.name, - schema = _ref5.schema, - _ref5$pouchSettings = _ref5.pouchSettings, - pouchSettings = _ref5$pouchSettings === void 0 ? {} : _ref5$pouchSettings, - _ref5$migrationStrate = _ref5.migrationStrategies, - migrationStrategies = _ref5$migrationStrate === void 0 ? {} : _ref5$migrationStrate, - _ref5$autoMigrate = _ref5.autoMigrate, - autoMigrate = _ref5$autoMigrate === void 0 ? true : _ref5$autoMigrate, - _ref5$statics = _ref5.statics, - statics = _ref5$statics === void 0 ? {} : _ref5$statics, - _ref5$methods = _ref5.methods, - methods = _ref5$methods === void 0 ? {} : _ref5$methods, - _ref5$attachments = _ref5.attachments, - attachments = _ref5$attachments === void 0 ? {} : _ref5$attachments, - _ref5$options = _ref5.options, - options = _ref5$options === void 0 ? {} : _ref5$options, - _ref5$cacheReplacemen = _ref5.cacheReplacementPolicy, - cacheReplacementPolicy = _ref5$cacheReplacemen === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref5$cacheReplacemen; - (0, _pouchDb.validateCouchDBString)(name); // ensure it is a schema-object +function createRxCollection(_ref4, wasCreatedBefore) { + var database = _ref4.database, + name = _ref4.name, + schema = _ref4.schema, + _ref4$instanceCreatio = _ref4.instanceCreationOptions, + instanceCreationOptions = _ref4$instanceCreatio === void 0 ? {} : _ref4$instanceCreatio, + _ref4$migrationStrate = _ref4.migrationStrategies, + migrationStrategies = _ref4$migrationStrate === void 0 ? {} : _ref4$migrationStrate, + _ref4$autoMigrate = _ref4.autoMigrate, + autoMigrate = _ref4$autoMigrate === void 0 ? true : _ref4$autoMigrate, + _ref4$statics = _ref4.statics, + statics = _ref4$statics === void 0 ? {} : _ref4$statics, + _ref4$methods = _ref4.methods, + methods = _ref4$methods === void 0 ? {} : _ref4$methods, + _ref4$attachments = _ref4.attachments, + attachments = _ref4$attachments === void 0 ? {} : _ref4$attachments, + _ref4$options = _ref4.options, + options = _ref4$options === void 0 ? {} : _ref4$options, + _ref4$cacheReplacemen = _ref4.cacheReplacementPolicy, + cacheReplacementPolicy = _ref4$cacheReplacemen === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref4$cacheReplacemen; + (0, _checkNames.validateDatabaseName)(name); // ensure it is a schema-object if (!(0, _rxSchema.isInstanceOf)(schema)) { schema = (0, _rxSchema.createRxSchema)(schema); @@ -7541,12 +10049,12 @@ function create(_ref5, wasCreatedBefore) { funName: funName }); }); - var collection = new RxCollectionBase(database, name, schema, pouchSettings, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics); + var collection = new RxCollectionBase(database, name, schema, instanceCreationOptions, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics); return collection.prepare(wasCreatedBefore).then(function () { // ORM add statics - Object.entries(statics).forEach(function (_ref6) { - var funName = _ref6[0], - fun = _ref6[1]; + Object.entries(statics).forEach(function (_ref5) { + var funName = _ref5[0], + fun = _ref5[1]; Object.defineProperty(collection, funName, { get: function get() { return fun.bind(collection); @@ -7566,92 +10074,12 @@ function create(_ref5, wasCreatedBefore) { }); } -function isInstanceOf(obj) { +function isRxCollection(obj) { return obj instanceof RxCollectionBase; } -var _default = { - create: create, - isInstanceOf: isInstanceOf, - RxCollectionBase: RxCollectionBase -}; -exports["default"] = _default; - -},{"./change-event-buffer":2,"./crypter":4,"./doc-cache":5,"./hooks":7,"./overwritable":9,"./pouch-db":37,"./query-cache":38,"./rx-change-event":39,"./rx-collection-helper":40,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-error":46,"./rx-query":47,"./rx-schema":48,"./util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"rxjs/operators":908}],42:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getLocalDocument = getLocalDocument; -exports.setLocalDocument = setLocalDocument; -exports.putDocument = putDocument; -exports.getAllDocuments = getAllDocuments; -exports.deleteStorageInstance = deleteStorageInstance; -exports.INTERNAL_STORAGE_NAME = void 0; - -var _util = require("./util"); - -/** - * In this file we handle all accesses to the internal store of the database - * This store is used to save hashes and checksums and metadata - * ATM this only works with PouchDB but in the future - * it should work by using the storage.interface - */ -// will be typed when we have more then one -var INTERNAL_STORAGE_NAME = '_rxdb_internal'; -/** - * returns to local document with the given id - * or null if not exists - */ - -exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; - -function getLocalDocument(storageInstance, id) { - return storageInstance.get(_util.LOCAL_PREFIX + id)["catch"](function () { - return null; - }); -} - -function setLocalDocument(storageInstance, id, value) { - return storageInstance.put({ - _id: id, - value: value - }).then(function () {}); -} - -function putDocument(storageInstance, doc) { - return storageInstance.put(doc).then(function (putResult) { - return Object.assign({ - _id: putResult.id, - _rev: putResult.rev - }, doc); - }); -} -/** - * returns all NON-LOCAL documents - */ - - -function getAllDocuments(storageInstance) { - return storageInstance.allDocs({ - include_docs: true - }).then(function (result) { - return result.rows; - }); -} -/** - * deletes the storage instance and all of it's data - */ - - -function deleteStorageInstance(storageInstance) { - return storageInstance.destroy(); -} - - -},{"./util":56}],43:[function(require,module,exports){ +},{"./change-event-buffer":2,"./crypter":4,"./doc-cache":5,"./hooks":7,"./plugins/dev-mode/check-names":13,"./query-cache":41,"./rx-collection-helper":43,"./rx-document":47,"./rx-document-prototype-merge":46,"./rx-error":48,"./rx-query":49,"./rx-schema":51,"./rx-storage-helper":52,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"rxjs/operators":908}],45:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -7665,10 +10093,9 @@ exports._collectionNamePrimary = _collectionNamePrimary; exports._removeAllOfCollection = _removeAllOfCollection; exports.createRxDatabase = createRxDatabase; exports.removeRxDatabase = removeRxDatabase; -exports.checkAdapter = checkAdapter; -exports.isInstanceOf = isInstanceOf; +exports.isRxDatabase = isRxDatabase; exports.dbCount = dbCount; -exports["default"] = exports.RxDatabaseBase = void 0; +exports.RxDatabaseBase = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -7696,46 +10123,45 @@ var _hooks = require("./hooks"); var _rxjs = require("rxjs"); -var _operators = require("rxjs/operators"); - -var _pouchDb = require("./pouch-db"); - var _rxCollection = require("./rx-collection"); -var _rxStoragePouchdb = require("./rx-storage-pouchdb"); +var _rxStorageHelper = require("./rx-storage-helper"); -var _rxDatabaseInternalStore = require("./rx-database-internal-store"); +var _rxSchemaHelper = require("./rx-schema-helper"); /** - * stores the combinations - * of used database-names with their adapters - * so we can throw when the same database is created more then once + * stores the used database names + * so we can throw when the same database is created more then once. */ -var USED_COMBINATIONS = {}; -var DB_COUNT = 0; +var USED_DATABASE_NAMES = new Set(); +var DB_COUNT = 0; // stores information about the collections var RxDatabaseBase = /*#__PURE__*/function () { - function RxDatabaseBase(name, adapter, password, multiInstance) { - var eventReduce = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; - var pouchSettings = arguments.length > 6 ? arguments[6] : undefined; + /** + * Stores information documents about the collections of the database + */ + + /** + * Stores the local documents which are attached to this database. + */ + function RxDatabaseBase(name, storage, instanceCreationOptions, password, multiInstance) { + var eventReduce = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + var options = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; this.internalStore = {}; + this.localDocumentsStore = {}; this.idleQueue = new _customIdleQueue.IdleQueue(); this.token = (0, _randomToken["default"])(10); this._subs = []; this.destroyed = false; this.subject = new _rxjs.Subject(); - this.observable$ = this.subject.asObservable().pipe((0, _operators.filter)(function (cEvent) { - return (0, _rxChangeEvent.isInstanceOf)(cEvent); - })); + this.observable$ = this.subject.asObservable(); this.name = name; - this.adapter = adapter; + this.storage = storage; + this.instanceCreationOptions = instanceCreationOptions; this.password = password; this.multiInstance = multiInstance; this.eventReduce = eventReduce; this.options = options; - this.pouchSettings = pouchSettings; - this.storage = (0, _rxStoragePouchdb.getRxStoragePouchDb)(adapter, pouchSettings); this.collections = {}; DB_COUNT++; } @@ -7747,31 +10173,45 @@ var RxDatabaseBase = /*#__PURE__*/function () { * only use this if you have to upgrade from a major rxdb-version * do NEVER use this to change the schema of a collection */ - _proto.dangerousRemoveCollectionInfo = function dangerousRemoveCollectionInfo() { - var _this = this; + _proto.dangerousRemoveCollectionInfo = + /*#__PURE__*/ + function () { + var _dangerousRemoveCollectionInfo = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var allDocs, writeData; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _rxStorageHelper.getAllDocuments)(this.internalStore); - return (0, _rxDatabaseInternalStore.getAllDocuments)(this.internalStore).then(function (docsRes) { - return Promise.all(docsRes.map(function (row) { - return { - _id: row.key, - _rev: row.value.rev - }; - }).map(function (doc) { - return _this.internalStore.remove(doc._id, doc._rev); - })); - }); - } - /** - * spawns a new pouch-instance - */ - ; + case 2: + allDocs = _context.sent; + writeData = allDocs.map(function (doc) { + var deletedDoc = (0, _util.flatClone)(doc); + deletedDoc._deleted = true; + return { + previous: doc, + document: deletedDoc + }; + }); + _context.next = 6; + return this.internalStore.bulkWrite(writeData); - _proto._spawnPouchDB = function _spawnPouchDB(collectionName, schemaVersion) { - var pouchSettings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - return this.storage.createStorageInstance(this.name, collectionName, schemaVersion, { - pouchSettings: pouchSettings - }); - } + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function dangerousRemoveCollectionInfo() { + return _dangerousRemoveCollectionInfo.apply(this, arguments); + } + + return dangerousRemoveCollectionInfo; + }() /** * This is the main handle-point for all change events * ChangeEvents created by this instance go: @@ -7782,8 +10222,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.$emit = function $emit(changeEvent) { - if (!changeEvent) return; // emit into own stream - + // emit into own stream this.subject.next(changeEvent); // write to socket if event was created by this instance if (changeEvent.databaseToken === this.token) { @@ -7791,77 +10230,113 @@ var RxDatabaseBase = /*#__PURE__*/function () { } } /** - * removes the collection-doc from this._collectionsPouch + * removes the collection-doc from the internalStore */ ; - _proto.removeCollectionDoc = function removeCollectionDoc(name, schema) { - var _this2 = this; + _proto.removeCollectionDoc = + /*#__PURE__*/ + function () { + var _removeCollectionDoc = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(name, schema) { + var _this = this; + + var docId, doc, writeDoc; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + docId = _collectionNamePrimary(name, schema); + _context2.next = 3; + return (0, _rxStorageHelper.getSingleDocument)(this.internalStore, docId); - var docId = _collectionNamePrimary(name, schema); + case 3: + doc = _context2.sent; - return this.internalStore.get(docId).then(function (doc) { - return _this2.lockedRun(function () { - return _this2.internalStore.remove(doc); - }); - }); - } + if (doc) { + _context2.next = 6; + break; + } + + throw (0, _rxError.newRxError)('SNH'); + + case 6: + writeDoc = (0, _util.flatClone)(doc); + writeDoc._deleted = true; + _context2.next = 10; + return this.lockedRun(function () { + return _this.internalStore.bulkWrite([{ + document: writeDoc, + previous: doc + }]); + }); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function removeCollectionDoc(_x, _x2) { + return _removeCollectionDoc.apply(this, arguments); + } + + return removeCollectionDoc; + }() /** * creates multiple RxCollections at once * to be much faster by saving db txs and doing stuff in bulk-operations * This function is not called often, but mostly in the critical path at the initial page load - * So it must be as fast as possible + * So it must be as fast as possible. */ ; _proto.addCollections = /*#__PURE__*/ function () { - var _addCollections = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(collectionCreators) { - var _this3 = this; + var _addCollections = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collectionCreators) { + var _this2 = this; - var pouch, result, internalDocByCollectionName, schemaHashByName, collections, bulkPutDocs, ret; - return _regenerator["default"].wrap(function _callee$(_context) { + var collectionDocs, internalDocByCollectionName, schemaHashByName, collections, bulkPutDocs, ret; + return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { - switch (_context.prev = _context.next) { + switch (_context3.prev = _context3.next) { case 0: - pouch = this.internalStore; // get local management docs in bulk request + _context3.next = 2; + return this.internalStore.findDocumentsById(Object.keys(collectionCreators).map(function (name) { + var schema = collectionCreators[name].schema; + return _collectionNamePrimary(name, schema); + }), false); - _context.next = 3; - return pouch.allDocs({ - include_docs: true, - keys: Object.keys(collectionCreators).map(function (name) { - return _collectionNamePrimary(name, collectionCreators[name].schema); - }) - }); - - case 3: - result = _context.sent; + case 2: + collectionDocs = _context3.sent; internalDocByCollectionName = {}; - result.rows.forEach(function (row) { - if (!row.error) { - internalDocByCollectionName[row.key] = row.doc; - } + Array.from(collectionDocs.entries()).forEach(function (_ref) { + var key = _ref[0], + doc = _ref[1]; + internalDocByCollectionName[key] = doc; }); schemaHashByName = {}; - _context.next = 9; - return Promise.all(Object.entries(collectionCreators).map(function (_ref) { - var name = _ref[0], - args = _ref[1]; + _context3.next = 8; + return Promise.all(Object.entries(collectionCreators).map(function (_ref2) { + var name = _ref2[0], + args = _ref2[1]; + var useName = name; - var internalDoc = internalDocByCollectionName[_collectionNamePrimary(name, collectionCreators[name].schema)]; + var internalDoc = internalDocByCollectionName[_collectionNamePrimary(name, collectionCreators[useName].schema)]; var useArgs = (0, _util.flatClone)(args); - useArgs.name = name; + useArgs.name = useName; var schema = (0, _rxSchema.createRxSchema)(args.schema); - schemaHashByName[name] = schema.hash; + schemaHashByName[useName] = schema.hash; useArgs.schema = schema; - useArgs.database = _this3; // TODO check if already exists and schema hash has changed + useArgs.database = _this2; // TODO check if already exists and schema hash has changed // collection already exists // TODO check if already exists and schema hash has changed // collection already exists - if (_this3.collections[name]) { + if (_this2.collections[name]) { throw (0, _rxError.newRxError)('DB3', { name: name }); @@ -7869,32 +10344,32 @@ var RxDatabaseBase = /*#__PURE__*/function () { // collection already exists but has different schema - if (internalDoc && internalDoc.schemaHash !== schemaHashByName[name]) { + if (internalDoc && internalDoc.schemaHash !== schemaHashByName[useName]) { throw (0, _rxError.newRxError)('DB6', { name: name, previousSchemaHash: internalDoc.schemaHash, - schemaHash: schemaHashByName[name] + schemaHash: schemaHashByName[useName] }); } // run hooks // run hooks var hookData = (0, _util.flatClone)(args); - hookData.database = _this3; + hookData.database = _this2; hookData.name = name; (0, _hooks.runPluginHooks)('preCreateRxCollection', hookData); - return (0, _rxCollection.create)(useArgs, !!internalDoc); + return (0, _rxCollection.createRxCollection)(useArgs, !!internalDoc); })); - case 9: - collections = _context.sent; + case 8: + collections = _context3.sent; bulkPutDocs = []; ret = {}; collections.forEach(function (collection) { var name = collection.name; ret[name] = collection; - if (collection.schema.crypt && !_this3.password) { + if (collection.schema.crypt && !_this2.password) { throw (0, _rxError.newRxError)('DB7', { name: name }); @@ -7903,90 +10378,81 @@ var RxDatabaseBase = /*#__PURE__*/function () { if (!internalDocByCollectionName[name]) { bulkPutDocs.push({ - _id: _collectionNamePrimary(name, collectionCreators[name].schema), - schemaHash: schemaHashByName[name], - schema: collection.schema.normalized, - version: collection.schema.version + document: { + collectionName: _collectionNamePrimary(name, collectionCreators[name].schema), + schemaHash: schemaHashByName[name], + schema: collection.schema.normalized, + version: collection.schema.version, + _attachments: {} + } }); } // set as getter to the database - _this3.collections[name] = collection; + _this2.collections[name] = collection; - if (!_this3[name]) { - Object.defineProperty(_this3, name, { + if (!_this2[name]) { + Object.defineProperty(_this2, name, { get: function get() { - return _this3.collections[name]; + return _this2.collections[name]; } }); } }); // make a single call to the pouchdb instance if (!(bulkPutDocs.length > 0)) { - _context.next = 16; + _context3.next = 15; break; } - _context.next = 16; - return pouch.bulkDocs({ - docs: bulkPutDocs - }); + _context3.next = 15; + return this.internalStore.bulkWrite(bulkPutDocs); - case 16: - return _context.abrupt("return", ret); + case 15: + return _context3.abrupt("return", ret); - case 17: + case 16: case "end": - return _context.stop(); + return _context3.stop(); } } - }, _callee, this); + }, _callee3, this); })); - function addCollections(_x) { + function addCollections(_x3) { return _addCollections.apply(this, arguments); } return addCollections; }() - /** - * create or fetch a collection - * @deprecated use addCollections() instead, it is faster and better typed - */ - ; - - _proto.collection = function collection(args) { - var _this$addCollections; - - if (typeof args === 'string') { - return Promise.resolve(this.collections[args]); - } // collection() is deprecated, call new bulk-creation method - - - return this.addCollections((_this$addCollections = {}, _this$addCollections[args.name] = args, _this$addCollections)).then(function (colObject) { - return colObject[args.name]; - }); - } /** * delete all data of the collection and its previous versions */ ; _proto.removeCollection = function removeCollection(collectionName) { - var _this4 = this; + var _this3 = this; + + if (this.collections[collectionName]) { + this.collections[collectionName].destroy(); + } // remove schemas from internal db - if (this.collections[collectionName]) this.collections[collectionName].destroy(); // remove schemas from internal db return _removeAllOfCollection(this, collectionName) // get all relevant pouchdb-instances .then(function (knownVersions) { - return knownVersions.map(function (v) { - return _this4._spawnPouchDB(collectionName, v); - }); + return Promise.all(knownVersions.map(function (v) { + return _this3.storage.createStorageInstance({ + databaseName: _this3.name, + collectionName: collectionName, + schema: (0, _rxSchemaHelper.getPseudoSchemaForVersion)(v, 'collectionName'), + options: _this3.instanceCreationOptions + }); + })); }) // remove documents - .then(function (pouches) { - return Promise.all(pouches.map(function (pouch) { - return _this4.lockedRun(function () { - return pouch.destroy(); + .then(function (storageInstance) { + return Promise.all(storageInstance.map(function (instance) { + return _this3.lockedRun(function () { + return instance.remove(); }); })); }).then(function () {}); @@ -8010,7 +10476,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { */ ; - _proto.dump = function dump() { + _proto.exportJSON = function exportJSON() { var _decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var _collections = arguments.length > 1 ? arguments[1] : undefined; @@ -8019,13 +10485,13 @@ var RxDatabaseBase = /*#__PURE__*/function () { } /** * Import the parsed JSON export into the collection. - * @param _exportedJSON The previously exported data from the `.dump()` method. + * @param _exportedJSON The previously exported data from the `.exportJSON()` method. * @note When an interface is loaded in this collection all base properties of the type are typed as `any` * since data could be encrypted. */ ; - _proto.importDump = function importDump(_exportedJSON) { + _proto.importJSON = function importJSON(_exportedJSON) { throw (0, _util.pluginMissing)('json-dump'); } /** @@ -8066,7 +10532,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.destroy = function destroy() { - var _this5 = this; + var _this4 = this; if (this.destroyed) return Promise.resolve(false); (0, _hooks.runPluginHooks)('preDestroyRxDatabase', this); @@ -8080,17 +10546,20 @@ var RxDatabaseBase = /*#__PURE__*/function () { return this.requestIdlePromise() // destroy all collections .then(function () { - return Promise.all(Object.keys(_this5.collections).map(function (key) { - return _this5.collections[key]; + return Promise.all(Object.keys(_this4.collections).map(function (key) { + return _this4.collections[key]; }).map(function (col) { return col.destroy(); })); + }) // destroy internal storage instances + .then(function () { + return _this4.internalStore.close ? _this4.internalStore.close() : null; }) // close broadcastChannel if exists .then(function () { - return _this5.broadcastChannel ? _this5.broadcastChannel.close() : Promise.resolve(); + return _this4.broadcastChannel ? _this4.broadcastChannel.close() : Promise.resolve(); }) // remove combination from USED_COMBINATIONS-map .then(function () { - return _removeUsedCombination(_this5.name, _this5.adapter); + return USED_DATABASE_NAMES["delete"](_this4.name); }).then(function () { return true; }); @@ -8101,10 +10570,10 @@ var RxDatabaseBase = /*#__PURE__*/function () { ; _proto.remove = function remove() { - var _this6 = this; + var _this5 = this; return this.destroy().then(function () { - return removeRxDatabase(_this6.name, _this6.adapter); + return removeRxDatabase(_this5.name, _this5.storage); }); }; @@ -8124,27 +10593,16 @@ var RxDatabaseBase = /*#__PURE__*/function () { exports.RxDatabaseBase = RxDatabaseBase; -function _isNameAdapterUsed(name, adapter) { - if (!USED_COMBINATIONS[name]) return false; - var used = false; - USED_COMBINATIONS[name].forEach(function (ad) { - if (ad === adapter) used = true; - }); - - if (used) { +function throwIfDatabaseNameUsed(name) { + if (!USED_DATABASE_NAMES.has(name)) { + return; + } else { throw (0, _rxError.newRxError)('DB8', { name: name, - adapter: adapter, link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate' }); } } - -function _removeUsedCombination(name, adapter) { - if (!USED_COMBINATIONS[name]) return; - var index = USED_COMBINATIONS[name].indexOf(adapter); - USED_COMBINATIONS[name].splice(index, 1); -} /** * to not confuse multiInstance-messages with other databases that have the same * name and adapter, but do not share state with this one (for example in-memory-instances), @@ -8152,30 +10610,67 @@ function _removeUsedCombination(name, adapter) { */ -function _ensureStorageTokenExists(rxDatabase) { - return rxDatabase.internalStore.get(_util.LOCAL_PREFIX + 'storageToken')["catch"](function () { - // no doc exists -> insert - return rxDatabase.internalStore.put({ - _id: _util.LOCAL_PREFIX + 'storageToken', - value: (0, _randomToken["default"])(10) - })["catch"](function () {}).then(function () { - return (0, _util.promiseWait)(0); - }); - }).then(function () { - return rxDatabase.internalStore.get(_util.LOCAL_PREFIX + 'storageToken'); - }).then(function (storageTokenDoc2) { - return storageTokenDoc2.value; - }); +function _ensureStorageTokenExists(_x4) { + return _ensureStorageTokenExists2.apply(this, arguments); } /** * writes the changeEvent to the broadcastChannel */ +function _ensureStorageTokenExists2() { + _ensureStorageTokenExists2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(rxDatabase) { + var storageTokenDocumentId, storageTokenDoc, storageToken; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + storageTokenDocumentId = 'storageToken'; + _context4.next = 3; + return (0, _rxStorageHelper.findLocalDocument)(rxDatabase.localDocumentsStore, storageTokenDocumentId); + + case 3: + storageTokenDoc = _context4.sent; + + if (storageTokenDoc) { + _context4.next = 11; + break; + } + + storageToken = (0, _randomToken["default"])(10); + _context4.next = 8; + return rxDatabase.localDocumentsStore.bulkWrite([{ + document: { + _id: storageTokenDocumentId, + value: storageToken, + _attachments: {} + } + }]); + + case 8: + return _context4.abrupt("return", storageToken); + + case 11: + return _context4.abrupt("return", storageTokenDoc.value); + + case 12: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + return _ensureStorageTokenExists2.apply(this, arguments); +} + function writeToSocket(rxDatabase, changeEvent) { - if (rxDatabase.multiInstance && !changeEvent.isIntern() && rxDatabase.broadcastChannel) { + if (rxDatabase.destroyed) { + return Promise.resolve(false); + } + + if (rxDatabase.multiInstance && !(0, _rxChangeEvent.isRxChangeEventIntern)(changeEvent) && rxDatabase.broadcastChannel) { var sendOverChannel = { - cE: changeEvent.toJSON(), + cE: changeEvent, storageToken: rxDatabase.storageToken }; return rxDatabase.broadcastChannel.postMessage(sendOverChannel).then(function () { @@ -8198,27 +10693,51 @@ function _collectionNamePrimary(name, schema) { */ -function _removeAllOfCollection(rxDatabase, collectionName) { - return rxDatabase.lockedRun(function () { - return (0, _rxDatabaseInternalStore.getAllDocuments)(rxDatabase.internalStore); - }).then(function (data) { - var relevantDocs = data.map(function (row) { - return row.doc; - }).filter(function (doc) { - var name = doc._id.split('-')[0]; +function _removeAllOfCollection(_x5, _x6) { + return _removeAllOfCollection2.apply(this, arguments); +} - return name === collectionName; - }); - return Promise.all(relevantDocs.map(function (doc) { - return rxDatabase.lockedRun(function () { - return rxDatabase.internalStore.remove(doc); - }); - })).then(function () { - return relevantDocs.map(function (doc) { - return doc.version; - }); - }); - }); +function _removeAllOfCollection2() { + _removeAllOfCollection2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(rxDatabase, collectionName) { + var docs, relevantDocs; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return rxDatabase.lockedRun(function () { + return (0, _rxStorageHelper.getAllDocuments)(rxDatabase.internalStore); + }); + + case 2: + docs = _context5.sent; + relevantDocs = docs.filter(function (doc) { + var name = doc.collectionName.split('-')[0]; + return name === collectionName; + }); + return _context5.abrupt("return", Promise.all(relevantDocs.map(function (doc) { + var writeDoc = (0, _util.flatClone)(doc); + writeDoc._deleted = true; + return rxDatabase.lockedRun(function () { + return (0, _rxStorageHelper.writeSingle)(rxDatabase.internalStore, { + previous: doc, + document: writeDoc + }); + }); + })).then(function () { + return relevantDocs.map(function (doc) { + return doc.version; + }); + })); + + case 5: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + return _removeAllOfCollection2.apply(this, arguments); } function _prepareBroadcastChannel(rxDatabase) { @@ -8231,74 +10750,134 @@ function _prepareBroadcastChannel(rxDatabase) { if (msg.cE.databaseToken === rxDatabase.token) return; // same db - var changeEvent = new _rxChangeEvent.RxChangeEvent(msg.cE.operation, msg.cE.documentId, msg.cE.documentData, msg.cE.databaseToken, msg.cE.collectionName, msg.cE.isLocal, msg.cE.startTime, msg.cE.endTime, msg.cE.previousData); + var changeEvent = msg.cE; rxDatabase.broadcastChannel$.next(changeEvent); - }; // TODO only subscribe when something is listening to the event-chain - + }; rxDatabase._subs.push(rxDatabase.broadcastChannel$.subscribe(function (cE) { rxDatabase.$emit(cE); })); } +/** + * Creates the storage instances that are used internally in the database + * to store schemas and other configuration stuff. + */ + + +function createRxDatabaseStorageInstances(_x7, _x8, _x9) { + return _createRxDatabaseStorageInstances.apply(this, arguments); +} /** * do the async things for this database */ -function prepare(rxDatabase) { - return rxDatabase.storage.createInternalStorageInstance(rxDatabase.name).then(function (internalStore) { - rxDatabase.internalStore = internalStore; - return _ensureStorageTokenExists(rxDatabase); - }).then(function (storageToken) { - rxDatabase.storageToken = storageToken; +function _createRxDatabaseStorageInstances() { + _createRxDatabaseStorageInstances = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(storage, databaseName, options) { + var internalStore, localDocumentsStore; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return storage.createStorageInstance({ + databaseName: databaseName, + collectionName: _rxStorageHelper.INTERNAL_STORAGE_NAME, + schema: (0, _rxSchemaHelper.getPseudoSchemaForVersion)(0, 'collectionName'), + options: options + }); - if (rxDatabase.multiInstance) { - _prepareBroadcastChannel(rxDatabase); - } - }); + case 2: + internalStore = _context6.sent; + _context6.next = 5; + return storage.createKeyObjectStorageInstance(databaseName, // TODO having to set an empty string here is ugly. + // we should change the rx-storage interface to account for non-collection storage instances. + '', options); + + case 5: + localDocumentsStore = _context6.sent; + return _context6.abrupt("return", { + internalStore: internalStore, + localDocumentsStore: localDocumentsStore + }); + + case 7: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + return _createRxDatabaseStorageInstances.apply(this, arguments); } -function createRxDatabase(_ref2) { - var name = _ref2.name, - adapter = _ref2.adapter, - password = _ref2.password, - _ref2$multiInstance = _ref2.multiInstance, - multiInstance = _ref2$multiInstance === void 0 ? true : _ref2$multiInstance, - _ref2$eventReduce = _ref2.eventReduce, - eventReduce = _ref2$eventReduce === void 0 ? false : _ref2$eventReduce, - _ref2$ignoreDuplicate = _ref2.ignoreDuplicate, - ignoreDuplicate = _ref2$ignoreDuplicate === void 0 ? false : _ref2$ignoreDuplicate, - _ref2$options = _ref2.options, - options = _ref2$options === void 0 ? {} : _ref2$options, - _ref2$pouchSettings = _ref2.pouchSettings, - pouchSettings = _ref2$pouchSettings === void 0 ? {} : _ref2$pouchSettings; +function prepare(_x10) { + return _prepare.apply(this, arguments); +} + +function _prepare() { + _prepare = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(rxDatabase) { + var storageInstances, localDocsSub; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return createRxDatabaseStorageInstances(rxDatabase.storage, rxDatabase.name, rxDatabase.instanceCreationOptions); + + case 2: + storageInstances = _context7.sent; + rxDatabase.internalStore = storageInstances.internalStore; + rxDatabase.localDocumentsStore = storageInstances.localDocumentsStore; + localDocsSub = rxDatabase.localDocumentsStore.changeStream().subscribe(function (rxStorageChangeEvent) { + rxDatabase.$emit((0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(true, rxStorageChangeEvent, rxDatabase)); + }); + + rxDatabase._subs.push(localDocsSub); + + _context7.next = 9; + return _ensureStorageTokenExists(rxDatabase); + + case 9: + rxDatabase.storageToken = _context7.sent; + + if (rxDatabase.multiInstance) { + _prepareBroadcastChannel(rxDatabase); + } + + case 11: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + return _prepare.apply(this, arguments); +} + +function createRxDatabase(_ref3) { + var storage = _ref3.storage, + instanceCreationOptions = _ref3.instanceCreationOptions, + name = _ref3.name, + password = _ref3.password, + _ref3$multiInstance = _ref3.multiInstance, + multiInstance = _ref3$multiInstance === void 0 ? true : _ref3$multiInstance, + _ref3$eventReduce = _ref3.eventReduce, + eventReduce = _ref3$eventReduce === void 0 ? false : _ref3$eventReduce, + _ref3$ignoreDuplicate = _ref3.ignoreDuplicate, + ignoreDuplicate = _ref3$ignoreDuplicate === void 0 ? false : _ref3$ignoreDuplicate, + _ref3$options = _ref3.options, + options = _ref3$options === void 0 ? {} : _ref3$options; (0, _hooks.runPluginHooks)('preCreateRxDatabase', { + storage: storage, + instanceCreationOptions: instanceCreationOptions, name: name, - adapter: adapter, password: password, multiInstance: multiInstance, eventReduce: eventReduce, ignoreDuplicate: ignoreDuplicate, - options: options, - pouchSettings: pouchSettings - }); // check if pouchdb-adapter - - if (typeof adapter === 'string') { - // TODO make a function hasAdapter() - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters[adapter]) { - throw (0, _rxError.newRxError)('DB9', { - adapter: adapter - }); - } - } else { - (0, _pouchDb.isLevelDown)(adapter); - - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.leveldb) { - throw (0, _rxError.newRxError)('DB10', { - adapter: adapter - }); - } - } + options: options + }); if (password) { _overwritable.overwritable.validatePassword(password); @@ -8306,16 +10885,11 @@ function createRxDatabase(_ref2) { if (!ignoreDuplicate) { - _isNameAdapterUsed(name, adapter); - } // add to used_map - - - if (!USED_COMBINATIONS[name]) { - USED_COMBINATIONS[name] = []; + throwIfDatabaseNameUsed(name); } - USED_COMBINATIONS[name].push(adapter); - var rxDatabase = new RxDatabaseBase(name, adapter, password, multiInstance, eventReduce, options, pouchSettings); + USED_DATABASE_NAMES.add(name); + var rxDatabase = new RxDatabaseBase(name, storage, instanceCreationOptions, password, multiInstance, eventReduce, options); return prepare(rxDatabase).then(function () { return (0, _hooks.runAsyncPluginHooks)('createRxDatabase', rxDatabase); }).then(function () { @@ -8327,36 +10901,79 @@ function createRxDatabase(_ref2) { */ -function removeRxDatabase(databaseName, adapter) { - var storage = (0, _rxStoragePouchdb.getRxStoragePouchDb)(adapter); - return storage.createInternalStorageInstance(databaseName).then(function (internalStore) { - return (0, _rxDatabaseInternalStore.getAllDocuments)(internalStore).then(function (docs) { - // remove collections storages - return Promise.all(docs.map(function (colDoc) { - return colDoc.id; - }).map(function (id) { - var split = id.split('-'); - var name = split[0]; - var version = parseInt(split[1], 10); - var instance = storage.createStorageInstance(databaseName, name, version); - return instance.destroy(); - })); - }) // remove internals - .then(function () { - return (0, _rxDatabaseInternalStore.deleteStorageInstance)(internalStore); - }); - }); +function removeRxDatabase(_x11, _x12) { + return _removeRxDatabase.apply(this, arguments); } -/** - * check if the given adapter can be used - */ +function _removeRxDatabase() { + _removeRxDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(databaseName, storage) { + var storageInstance, docs; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return createRxDatabaseStorageInstances(storage, databaseName, {}); -function checkAdapter(adapter) { - return _overwritable.overwritable.checkAdapter(adapter); + case 2: + storageInstance = _context9.sent; + _context9.next = 5; + return (0, _rxStorageHelper.getAllDocuments)(storageInstance.internalStore); + + case 5: + docs = _context9.sent; + _context9.next = 8; + return Promise.all(docs.map(function (colDoc) { + return colDoc.collectionName; + }).map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(id) { + var split, name, version, instance; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + split = id.split('-'); + name = split[0]; + version = parseInt(split[1], 10); + _context8.next = 5; + return storage.createStorageInstance({ + databaseName: databaseName, + collectionName: name, + schema: (0, _rxSchemaHelper.getPseudoSchemaForVersion)(version, 'collectionName'), + options: {} + }); + + case 5: + instance = _context8.sent; + return _context8.abrupt("return", instance.remove()); + + case 7: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + + return function (_x13) { + return _ref4.apply(this, arguments); + }; + }())); + + case 8: + return _context9.abrupt("return", Promise.all([storageInstance.internalStore.remove(), storageInstance.localDocumentsStore.remove()])); + + case 9: + case "end": + return _context9.stop(); + } + } + }, _callee9); + })); + return _removeRxDatabase.apply(this, arguments); } -function isInstanceOf(obj) { +function isRxDatabase(obj) { return obj instanceof RxDatabaseBase; } @@ -8364,18 +10981,8 @@ function dbCount() { return DB_COUNT; } -var _default = { - createRxDatabase: createRxDatabase, - removeRxDatabase: removeRxDatabase, - checkAdapter: checkAdapter, - isInstanceOf: isInstanceOf, - RxDatabaseBase: RxDatabaseBase, - dbCount: dbCount -}; -exports["default"] = _default; - -},{"./hooks":7,"./overwritable":9,"./pouch-db":37,"./rx-change-event":39,"./rx-collection":41,"./rx-database-internal-store":42,"./rx-error":46,"./rx-schema":48,"./rx-storage-pouchdb":49,"./util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"broadcast-channel":112,"custom-idle-queue":494,"random-token":675,"rxjs":684,"rxjs/operators":908}],44:[function(require,module,exports){ +},{"./hooks":7,"./overwritable":9,"./rx-change-event":42,"./rx-collection":44,"./rx-error":48,"./rx-schema":51,"./rx-schema-helper":50,"./rx-storage-helper":52,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"broadcast-channel":113,"custom-idle-queue":495,"random-token":675,"rxjs":684}],46:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -8459,15 +11066,17 @@ function getRxDocumentConstructor(rxCollection) { function createRxDocument(rxCollection, docData) { - // return from cache if exsists - var id = docData[rxCollection.schema.primaryPath]; + var primary = docData[rxCollection.schema.primaryPath]; // return from cache if exsists + + var cacheDoc = rxCollection._docCache.get(primary); - var cacheDoc = rxCollection._docCache.get(id); + if (cacheDoc) { + return cacheDoc; + } - if (cacheDoc) return cacheDoc; var doc = (0, _rxDocument.createWithConstructor)(getRxDocumentConstructor(rxCollection), rxCollection, docData); - rxCollection._docCache.set(id, doc); + rxCollection._docCache.set(primary, doc); rxCollection._runHooksSync('post', 'create', docData, doc); @@ -8502,7 +11111,7 @@ function getDocumentOrmPrototype(rxCollection) { } -},{"./hooks":7,"./rx-document":45}],45:[function(require,module,exports){ +},{"./hooks":7,"./rx-document":47}],47:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -8513,7 +11122,7 @@ Object.defineProperty(exports, "__esModule", { exports.createRxDocumentConstructor = createRxDocumentConstructor; exports.defineGetterSetter = defineGetterSetter; exports.createWithConstructor = createWithConstructor; -exports.isInstanceOf = isInstanceOf; +exports.isRxDocument = isRxDocument; exports.basePrototype = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); @@ -8528,12 +11137,18 @@ var _operators = require("rxjs/operators"); var _util = require("./util"); -var _rxChangeEvent = require("./rx-change-event"); - var _rxError = require("./rx-error"); var _hooks = require("./hooks"); +var _rxChangeEvent = require("./rx-change-event"); + +var _rxCollectionHelper = require("./rx-collection-helper"); + +var _overwritable = require("./overwritable"); + +var _rxSchemaHelper = require("./rx-schema-helper"); + var basePrototype = { /** * TODO @@ -8592,7 +11207,7 @@ var basePrototype = { return undefined; } - return _this._deleted$.asObservable(); + return _this._isDeleted$.asObservable(); }, get deleted() { @@ -8602,7 +11217,7 @@ var basePrototype = { return undefined; } - return _this._deleted$.getValue(); + return _this._isDeleted$.getValue(); }, /** @@ -8615,9 +11230,13 @@ var basePrototype = { }, _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) return; // ensure that new _rev is higher then current + if (changeEvent.documentId !== this.primary) { + return; + } // ensure that new _rev is higher then current + - var newRevNr = (0, _util.getHeightOfRevision)(changeEvent.documentData._rev); + var docData = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + var newRevNr = (0, _util.getHeightOfRevision)(docData._rev); var currentRevNr = (0, _util.getHeightOfRevision)(this._data._rev); if (currentRevNr > newRevNr) return; @@ -8636,7 +11255,7 @@ var basePrototype = { // remove from docCache to assure new upserted RxDocuments will be a new instance this.collection._docCache["delete"](this.primary); - this._deleted$.next(true); + this._isDeleted$.next(true); break; } @@ -8667,7 +11286,7 @@ var basePrototype = { }); } - var schemaObj = this.collection.schema.getSchemaByObjectPath(path); + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); if (!schemaObj) { throw (0, _rxError.newRxError)('DOC4', { @@ -8684,7 +11303,7 @@ var basePrototype = { * populate the given path */ populate: function populate(path) { - var schemaObj = this.collection.schema.getSchemaByObjectPath(path); + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); var value = this.get(path); if (!value) { @@ -8730,24 +11349,33 @@ var basePrototype = { get: function get(objPath) { if (!this._data) return undefined; - var valueObj = _objectPath["default"].get(this._data, objPath); + var valueObj = _objectPath["default"].get(this._data, objPath); // direct return if array or non-object - valueObj = (0, _util.clone)(valueObj); // direct return if array or non-object - if (typeof valueObj !== 'object' || Array.isArray(valueObj)) return valueObj; + if (typeof valueObj !== 'object' || Array.isArray(valueObj)) { + return _overwritable.overwritable.deepFreezeWhenDevMode(valueObj); + } + /** + * TODO find a way to deep-freeze together with defineGetterSetter + * so we do not have to do a deep clone here. + */ + + + valueObj = (0, _util.clone)(valueObj); defineGetterSetter(this.collection.schema, valueObj, objPath, this); return valueObj; }, toJSON: function toJSON() { var withRevAndAttachments = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var data = (0, _util.clone)(this._data); if (!withRevAndAttachments) { + var data = (0, _util.flatClone)(this._data); delete data._rev; delete data._attachments; + return _overwritable.overwritable.deepFreezeWhenDevMode(data); + } else { + return _overwritable.overwritable.deepFreezeWhenDevMode(this._data); } - - return data; }, /** @@ -8905,60 +11533,59 @@ var basePrototype = { }); }, - /** - * @deprecated use atomicPatch instead because it is better typed - * and does not allow any keys and values - */ - atomicSet: function atomicSet(key, value) { - return this.atomicUpdate(function (docData) { - _objectPath["default"].set(docData, key, value); - - return docData; - }); - }, - /** * saves the new document-data * and handles the events */ - _saveData: function _saveData(newData, oldData) { - var _this3 = this; - - newData = newData; // deleted documents cannot be changed - - if (this._deleted$.getValue()) { - throw (0, _rxError.newRxError)('DOC11', { - id: this.primary, - document: this - }); - } // ensure modifications are ok + _saveData: function () { + var _saveData2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(newData, oldData) { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + newData = newData; // deleted documents cannot be changed + if (!this._isDeleted$.getValue()) { + _context2.next = 3; + break; + } - this.collection.schema.validateChange(oldData, newData); - var startTime; - return this.collection._runHooks('pre', 'save', newData, this).then(function () { - _this3.collection.schema.validate(newData); + throw (0, _rxError.newRxError)('DOC11', { + id: this.primary, + document: this + }); - startTime = (0, _util.now)(); - return _this3.collection._pouchPut(newData); - }).then(function (ret) { - var endTime = (0, _util.now)(); + case 3: + // ensure modifications are ok + this.collection.schema.validateChange(oldData, newData); + _context2.next = 6; + return this.collection._runHooks('pre', 'save', newData, this); - if (!ret.ok) { - throw (0, _rxError.newRxError)('DOC12', { - data: ret - }); - } + case 6: + this.collection.schema.validate(newData); + _context2.next = 9; + return (0, _rxCollectionHelper.writeToStorageInstance)(this.collection, { + previous: oldData, + document: newData + }); - newData._rev = ret.rev; // emit event + case 9: + return _context2.abrupt("return", this.collection._runHooks('post', 'save', newData, this)); - var changeEvent = (0, _rxChangeEvent.createUpdateEvent)(_this3.collection, newData, oldData, startTime, endTime, _this3); + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); - _this3.$emit(changeEvent); + function _saveData(_x, _x2) { + return _saveData2.apply(this, arguments); + } - return _this3.collection._runHooks('post', 'save', newData, _this3); - }); - }, + return _saveData; + }(), /** * saves the temporary document and makes a non-temporary out of it @@ -8966,7 +11593,7 @@ var basePrototype = { * @return false if nothing to save */ save: function save() { - var _this4 = this; + var _this3 = this; // .save() cannot be called on non-temporary-documents if (!this._isTemporary) { @@ -8977,12 +11604,12 @@ var basePrototype = { } return this.collection.insert(this).then(function () { - _this4._isTemporary = false; + _this3._isTemporary = false; - _this4.collection._docCache.set(_this4.primary, _this4); // internal events + _this3.collection._docCache.set(_this3.primary, _this3); // internal events - _this4._dataSync$.next(_this4._data); + _this3._dataSync$.next(_this3._data); return true; }); @@ -8994,7 +11621,7 @@ var basePrototype = { * instead we keep the values and only set _deleted: true */ remove: function remove() { - var _this5 = this; + var _this4 = this; if (this.deleted) { return Promise.reject((0, _rxError.newRxError)('DOC13', { @@ -9003,25 +11630,19 @@ var basePrototype = { })); } - var deletedData = (0, _util.clone)(this._data); + var deletedData = (0, _util.flatClone)(this._data); var startTime; return this.collection._runHooks('pre', 'remove', deletedData, this).then(function () { deletedData._deleted = true; startTime = (0, _util.now)(); - /** - * because pouch.remove will also empty the object, - * we set _deleted: true and use pouch.put - */ - - return _this5.collection._pouchPut(deletedData); + return (0, _rxCollectionHelper.writeToStorageInstance)(_this4.collection, { + previous: _this4._data, + document: deletedData + }); }).then(function () { - var endTime = (0, _util.now)(); - - _this5.$emit((0, _rxChangeEvent.createDeleteEvent)(_this5.collection, deletedData, _this5._data, startTime, endTime, _this5)); - - return _this5.collection._runHooks('post', 'remove', deletedData, _this5); + return _this4.collection._runHooks('post', 'remove', deletedData, _this4); }).then(function () { - return _this5; + return _this4; }); }, destroy: function destroy() { @@ -9039,7 +11660,7 @@ function createRxDocumentConstructor() { this._isTemporary = false; // assume that this is always equal to the doc-data in the database this._dataSync$ = new _rxjs.BehaviorSubject(jsonData); - this._deleted$ = new _rxjs.BehaviorSubject(false); + this._isDeleted$ = new _rxjs.BehaviorSubject(false); this._atomicQueue = Promise.resolve(); /** * because of the prototype-merge, @@ -9057,7 +11678,7 @@ function defineGetterSetter(schema, valueObj) { var objPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var thisObj = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (valueObj === null) return; - var pathProperties = schema.getSchemaByObjectPath(objPath); + var pathProperties = (0, _rxSchemaHelper.getSchemaByObjectPath)(schema.jsonSchema, objPath); if (typeof pathProperties === 'undefined') return; if (pathProperties.properties) pathProperties = pathProperties.properties; Object.keys(pathProperties).forEach(function (key) { @@ -9116,13 +11737,13 @@ function createWithConstructor(constructor, collection, jsonData) { return doc; } -function isInstanceOf(obj) { +function isRxDocument(obj) { if (typeof obj === 'undefined') return false; return !!obj.isInstanceOfRxDocument; } -},{"./hooks":7,"./rx-change-event":39,"./rx-error":46,"./util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"object-path":630,"rxjs":684,"rxjs/operators":908}],46:[function(require,module,exports){ +},{"./hooks":7,"./overwritable":9,"./rx-change-event":42,"./rx-collection-helper":43,"./rx-error":48,"./rx-schema-helper":50,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"object-path":629,"rxjs":684,"rxjs/operators":908}],48:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -9268,7 +11889,7 @@ function isPouchdbConflictError(err) { } -},{"./overwritable":9,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/inheritsLoose":64,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/helpers/wrapNativeSuper":69}],47:[function(require,module,exports){ +},{"./overwritable":9,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/inheritsLoose":66,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/helpers/wrapNativeSuper":71}],49:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -9290,8 +11911,6 @@ var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _pouchdbSelectorCore = require("pouchdb-selector-core"); - var _util = require("./util"); var _rxError = require("./rx-error"); @@ -9304,6 +11923,8 @@ var _eventReduce = require("./event-reduce"); var _queryCache = require("./query-cache"); +var _rxCollectionHelper = require("./rx-collection-helper"); + var _queryCount = 0; var newQueryID = function newQueryID() { @@ -9369,11 +11990,11 @@ var RxQueryBase = /*#__PURE__*/function () { switch (this.op) { case 'find': - docsPromise = this.collection._pouchFind(this); + docsPromise = this.collection._queryStorageInstance(this); break; case 'findOne': - docsPromise = this.collection._pouchFind(this, 1); + docsPromise = this.collection._queryStorageInstance(this, 1); break; default: @@ -9435,7 +12056,7 @@ var RxQueryBase = /*#__PURE__*/function () { }); } /** - * cached call to get the massageSelector + * cached call to get the queryMatcher * @overwrites itself with the actual value */ ; @@ -9460,35 +12081,23 @@ var RxQueryBase = /*#__PURE__*/function () { } /** * returns the prepared query + * which can be send to the storage instance to query for documents. * @overwrites itself with the actual value + * TODO rename this function, toJSON is missleading + * because we do not return the plain mango query object. */ ; _proto.toJSON = function toJSON() { - var value = this.collection.database.storage.prepareQuery(this.asRxQuery, (0, _util.clone)(this.mangoQuery)); - - this.toJSON = function () { - return value; + var hookInput = { + rxQuery: this, + // can be mutated by the hooks so we have to deep clone first. + mangoQuery: (0, _util.clone)(this.mangoQuery) }; + (0, _hooks.runPluginHooks)('prePrepareQuery', hookInput); + var value = this.collection.storageInstance.prepareQuery(hookInput.mangoQuery); - return value; - } - /** - * returns the key-compressed version of the query - * @overwrites itself with the actual value - */ - ; - - _proto.keyCompress = function keyCompress() { - var value; - - if (!this.collection.schema.doKeyCompression()) { - value = this.toJSON(); - } else { - value = this.collection._keyCompressor.compressQuery(this.toJSON()); - } - - this.keyCompress = function () { + this.toJSON = function () { return value; }; @@ -9503,24 +12112,11 @@ var RxQueryBase = /*#__PURE__*/function () { _proto.doesDocumentDataMatch = function doesDocumentDataMatch(docData) { // if doc is deleted, it cannot match - if (docData._deleted) return false; - docData = this.collection.schema.swapPrimaryToId(docData); // return matchesSelector(docData, selector); - - /** - * the following is equal to the implementation of pouchdb - * we do not use matchesSelector() directly so we can cache the - * result of massageSelector - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ + if (docData._deleted) { + return false; + } - var selector = this.massageSelector; - var row = { - doc: docData - }; - var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { - selector: selector - }, Object.keys(selector)); - return rowsMatched && rowsMatched.length === 1; + return this.queryMatcher((0, _rxCollectionHelper._handleToStorageInstance)(this.collection, docData)); } /** * deletes all found documents @@ -9532,9 +12128,14 @@ var RxQueryBase = /*#__PURE__*/function () { var ret; return this.exec().then(function (docs) { ret = docs; - if (Array.isArray(docs)) return Promise.all(docs.map(function (doc) { - return doc.remove(); - }));else return docs.remove(); + + if (Array.isArray(docs)) { + return Promise.all(docs.map(function (doc) { + return doc.remove(); + })); + } else { + return docs.remove(); + } }).then(function () { return ret; }); @@ -9582,19 +12183,25 @@ var RxQueryBase = /*#__PURE__*/function () { */ var results$ = this._resultsDocs$.pipe((0, _operators.mergeMap)(function (docs) { return _ensureEqual(_this3).then(function (hasChanged) { - if (hasChanged) return false; // wait for next emit - else return docs; + if (hasChanged) { + // wait for next emit + return false; + } else { + return docs; + } }); }), (0, _operators.filter)(function (docs) { return !!docs; }), // not if previous returned false (0, _operators.map)(function (docs) { - // findOne()-queries emit document or null if (_this3.op === 'findOne') { + // findOne()-queries emit document or null var doc = docs.length === 0 ? null : docs[0]; return doc; - } else return docs; // find()-queries emit RxDocument[] - + } else { + // find()-queries emit RxDocument[] + return docs; + } }), (0, _operators.map)(function (docs) { // copy the array so it wont matter if the user modifies it var ret = Array.isArray(docs) ? docs.slice() : docs; @@ -9620,9 +12227,9 @@ var RxQueryBase = /*#__PURE__*/function () { } // stores the changeEvent-Number of the last handled change-event }, { - key: "massageSelector", + key: "queryMatcher", get: function get() { - return (0, _util.overwriteGetterForCaching)(this, 'massageSelector', (0, _pouchdbSelectorCore.massageSelector)(this.mangoQuery.selector)); + return (0, _util.overwriteGetterForCaching)(this, 'queryMatcher', this.collection.storageInstance.getQueryMatcher(this.toJSON())); } }, { key: "asRxQuery", @@ -9697,15 +12304,11 @@ function _isResultsInSync(rxQuery) { function _ensureEqual(rxQuery) { rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue.then(function () { - return new Promise(function (res) { - return setTimeout(res, 0); - }); + return (0, _util.promiseWait)(0); }).then(function () { return __ensureEqual(rxQuery); }).then(function (ret) { - return new Promise(function (res) { - return setTimeout(res, 0); - }).then(function () { + return (0, _util.promiseWait)(0).then(function () { return ret; }); }); @@ -9808,7 +12411,56 @@ function isInstanceOf(obj) { } -},{"./event-reduce":6,"./hooks":7,"./query-cache":38,"./rx-document-prototype-merge":44,"./rx-error":46,"./util":56,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"deep-equal":496,"pouchdb-selector-core":665,"rxjs":684,"rxjs/operators":908}],48:[function(require,module,exports){ +},{"./event-reduce":6,"./hooks":7,"./query-cache":41,"./rx-collection-helper":43,"./rx-document-prototype-merge":46,"./rx-error":48,"./util":58,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"deep-equal":497,"rxjs":684,"rxjs/operators":908}],50:[function(require,module,exports){ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getPseudoSchemaForVersion = getPseudoSchemaForVersion; +exports.getSchemaByObjectPath = getSchemaByObjectPath; + +var _objectPath = _interopRequireDefault(require("object-path")); + +var _util = require("./util"); + +/** + * Helper function to create a valid RxJsonSchema + * with a given version. + */ +function getPseudoSchemaForVersion(version, primaryKey) { + var _properties; + + var pseudoSchema = { + version: version, + type: 'object', + primaryKey: primaryKey, + properties: (_properties = {}, _properties[primaryKey] = { + type: 'string' + }, _properties) + }; + return pseudoSchema; +} +/** + * Returns the sub-schema for a given path + */ + + +function getSchemaByObjectPath(rxJsonSchema, path) { + var usePath = path; + usePath = usePath.replace(/\./g, '.properties.'); + usePath = 'properties.' + usePath; + usePath = (0, _util.trimDots)(usePath); + + var ret = _objectPath["default"].get(rxJsonSchema, usePath); + + return ret; +} + + +},{"./util":58,"@babel/runtime/helpers/interopRequireDefault":67,"object-path":629}],51:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -9817,18 +12469,16 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.getIndexes = getIndexes; -exports.getPrimary = getPrimary; exports.getPreviousVersions = getPreviousVersions; exports.getFinalFields = getFinalFields; exports.normalize = normalize; +exports.fillWithDefaultSettings = fillWithDefaultSettings; exports.createRxSchema = createRxSchema; exports.isInstanceOf = isInstanceOf; -exports.fillWithDefaultSettings = exports.RxSchema = void 0; +exports.RxSchema = void 0; var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); -var _objectPath = _interopRequireDefault(require("object-path")); - var _deepEqual = _interopRequireDefault(require("deep-equal")); var _util = require("./util"); @@ -9844,7 +12494,7 @@ var RxSchema = /*#__PURE__*/function () { this.jsonSchema = jsonSchema; this.indexes = getIndexes(this.jsonSchema); // primary is always required - this.primaryPath = getPrimary(this.jsonSchema); + this.primaryPath = this.jsonSchema.primaryKey; if (this.primaryPath) { this.jsonSchema.required.push(this.primaryPath); @@ -9855,28 +12505,10 @@ var RxSchema = /*#__PURE__*/function () { this.jsonSchema.required = this.jsonSchema.required.concat(this.finalFields).filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos; }); // unique; - // add primary to schema if not there (if _id) - - if (!this.jsonSchema.properties[this.primaryPath]) { - this.jsonSchema.properties[this.primaryPath] = { - type: 'string', - minLength: 1 - }; - } } var _proto = RxSchema.prototype; - _proto.getSchemaByObjectPath = function getSchemaByObjectPath(path) { - var usePath = path; - usePath = usePath.replace(/\./g, '.properties.'); - usePath = 'properties.' + usePath; - usePath = (0, _util.trimDots)(usePath); - - var ret = _objectPath["default"].get(this.jsonSchema, usePath); - - return ret; - } /** * checks if a given change on a document is allowed * Ensures that: @@ -9884,8 +12516,6 @@ var RxSchema = /*#__PURE__*/function () { * - final fields are not modified * @throws {Error} if not valid */ - ; - _proto.validateChange = function validateChange(dataBefore, dataAfter) { this.finalFields.forEach(function (fieldName) { if (!(0, _deepEqual["default"])(dataBefore[fieldName], dataAfter[fieldName])) { @@ -9925,39 +12555,6 @@ var RxSchema = /*#__PURE__*/function () { return obj[k] = v; }); return obj; - }; - - _proto.swapIdToPrimary = function swapIdToPrimary(obj) { - if (this.primaryPath === '_id' || obj[this.primaryPath]) { - return obj; - } - - obj[this.primaryPath] = obj._id; - delete obj._id; - return obj; - }; - - _proto.swapPrimaryToId = function swapPrimaryToId(obj) { - var _this = this; - - if (this.primaryPath === '_id') { - return obj; - } - - var ret = {}; - Object.entries(obj).forEach(function (entry) { - var newKey = entry[0] === _this.primaryPath ? '_id' : entry[0]; - ret[newKey] = entry[1]; - }); - return ret; - } - /** - * returns true if key-compression should be done - */ - ; - - _proto.doKeyCompression = function doKeyCompression() { - return this.jsonSchema.keyCompression; } /** * creates the schema-based document-prototype, @@ -10045,18 +12642,6 @@ function getIndexes(jsonSchema) { return Array.isArray(index) ? index : [index]; }); } -/** - * returns the primary path of a jsonschema - * @return primaryPath which is _id if none defined - */ - - -function getPrimary(jsonSchema) { - var ret = Object.keys(jsonSchema.properties).filter(function (key) { - return jsonSchema.properties[key].primary; - }).shift(); - if (!ret) return '_id';else return ret; -} /** * array with previous version-numbers */ @@ -10080,7 +12665,7 @@ function getFinalFields(jsonSchema) { return jsonSchema.properties[key]["final"]; }); // primary is also final - ret.push(getPrimary(jsonSchema)); + ret.push(jsonSchema.primaryKey); return ret; } /** @@ -10096,6 +12681,12 @@ function normalize(jsonSchema) { normalizedSchema.indexes = Array.from(jsonSchema.indexes); // indexes should remain unsorted } + if (!jsonSchema.required) { + jsonSchema.required = [jsonSchema.primaryKey]; + } else if (!jsonSchema.required.includes(jsonSchema.primaryKey)) { + jsonSchema.required.push(jsonSchema.primaryKey); + } + return normalizedSchema; } /** @@ -10104,18 +12695,26 @@ function normalize(jsonSchema) { */ -var fillWithDefaultSettings = function fillWithDefaultSettings(schemaObj) { +function fillWithDefaultSettings(schemaObj) { schemaObj = (0, _util.clone)(schemaObj); // additionalProperties is always false schemaObj.additionalProperties = false; // fill with key-compression-state () - if (!schemaObj.hasOwnProperty('keyCompression')) schemaObj.keyCompression = false; // indexes must be array + if (!schemaObj.hasOwnProperty('keyCompression')) { + schemaObj.keyCompression = false; + } // indexes must be array + schemaObj.indexes = schemaObj.indexes || []; // required must be array schemaObj.required = schemaObj.required || []; // encrypted must be array - schemaObj.encrypted = schemaObj.encrypted || []; // add _rev + schemaObj.encrypted = schemaObj.encrypted || []; + /** + * TODO we should not need to added the internal fields to the schema. + * Better remove the before validation. + */ + // add _rev schemaObj.properties._rev = { type: 'string', @@ -10124,13 +12723,15 @@ var fillWithDefaultSettings = function fillWithDefaultSettings(schemaObj) { schemaObj.properties._attachments = { type: 'object' + }; // add deleted flag + + schemaObj.properties._deleted = { + type: 'boolean' }; // version is 0 by default schemaObj.version = schemaObj.version || 0; return schemaObj; -}; - -exports.fillWithDefaultSettings = fillWithDefaultSettings; +} function createRxSchema(jsonSchema) { var runPreCreateHooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; @@ -10149,309 +12750,402 @@ function isInstanceOf(obj) { } -},{"./hooks":7,"./rx-document":45,"./rx-error":46,"./util":56,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"deep-equal":496,"object-path":630}],49:[function(require,module,exports){ +},{"./hooks":7,"./rx-document":47,"./rx-error":48,"./util":58,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"deep-equal":497}],52:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + Object.defineProperty(exports, "__esModule", { value: true }); -exports.primarySwapPouchDbQuerySelector = primarySwapPouchDbQuerySelector; -exports.getPouchLocation = getPouchLocation; -exports.getRxStoragePouchDb = getRxStoragePouchDb; -exports.RxStoragePouchDbClass = void 0; +exports.getAllDocuments = getAllDocuments; +exports.getSingleDocument = getSingleDocument; +exports.countAllUndeleted = countAllUndeleted; +exports.getBatch = getBatch; +exports.writeSingle = writeSingle; +exports.writeSingleLocal = writeSingleLocal; +exports.findLocalDocument = findLocalDocument; +exports.getNewestSequence = getNewestSequence; +exports.storageChangeEventToRxChangeEvent = storageChangeEventToRxChangeEvent; +exports.INTERNAL_STORAGE_NAME = void 0; -var _pouchdbSelectorCore = require("pouchdb-selector-core"); +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); -var _util = require("./util"); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _hooks = require("./hooks"); -var _pouchDb = require("./pouch-db"); +var _overwritable = require("./overwritable"); var _rxError = require("./rx-error"); -var RxStoragePouchDbClass = /*#__PURE__*/function () { - function RxStoragePouchDbClass(adapter) { - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.name = 'pouchdb'; - this.adapter = adapter; - this.pouchSettings = pouchSettings; - } +/** + * Helper functions for accessing the RxStorage instances. + */ +var INTERNAL_STORAGE_NAME = '_rxdb_internal'; +/** + * returns all NON-LOCAL documents + * TODO this is pouchdb specific should not be needed + */ - var _proto = RxStoragePouchDbClass.prototype; +exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; - _proto.getSortComparator = function getSortComparator(primaryKey, query) { - var _ref; +function getAllDocuments(_x) { + return _getAllDocuments.apply(this, arguments); +} - var sortOptions = query.sort ? query.sort : [(_ref = {}, _ref[primaryKey] = 'asc', _ref)]; - var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); - var inMemoryFields = Object.keys(query.selector); +function _getAllDocuments() { + _getAllDocuments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(storageInstance) { + var getAllQueryPrepared, queryResult, allDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + getAllQueryPrepared = storageInstance.prepareQuery({ + selector: {} + }); + _context.next = 3; + return storageInstance.query(getAllQueryPrepared); - var fun = function fun(a, b) { - // TODO use createFieldSorter - // TODO make a performance test - var rows = [a, b].map(function (doc) { - // swap primary to _id - var cloned = (0, _util.flatClone)(doc); - var primaryValue = cloned[primaryKey]; - delete cloned[primaryKey]; - cloned._id = primaryValue; - return { - doc: cloned - }; - }); - var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, { - selector: massagedSelector, - sort: sortOptions - }, inMemoryFields); + case 3: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); - if (sortedRows[0].doc._id === rows[0].doc._id) { - return -1; - } else { - return 1; + case 6: + case "end": + return _context.stop(); + } } - }; + }, _callee); + })); + return _getAllDocuments.apply(this, arguments); +} - return fun; - } - /** - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ - ; +function getSingleDocument(_x2, _x3) { + return _getSingleDocument.apply(this, arguments); +} +/** + * get the number of all undeleted documents + */ - _proto.getQueryMatcher = function getQueryMatcher(primaryKey, query) { - var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(query.selector); - var fun = function fun(doc) { - // swap primary to _id - var cloned = (0, _util.flatClone)(doc); - var primaryValue = cloned[primaryKey]; - delete cloned[primaryKey]; - cloned._id = primaryValue; - var row = { - doc: cloned - }; - var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { - selector: massagedSelector - }, Object.keys(query.selector)); - return rowsMatched && rowsMatched.length === 1; - }; +function _getSingleDocument() { + _getSingleDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(storageInstance, documentId) { + var results, doc; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return storageInstance.findDocumentsById([documentId], false); - return fun; - }; + case 2: + results = _context2.sent; + doc = results.get(documentId); - _proto.createStorageInstance = function createStorageInstance(databaseName, collectionName, schemaVersion) { - var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + if (!doc) { + _context2.next = 8; + break; + } - if (!options.pouchSettings) { - options.pouchSettings = {}; - } + return _context2.abrupt("return", doc); - var pouchLocation = getPouchLocation(databaseName, collectionName, schemaVersion); - var pouchDbParameters = { - location: pouchLocation, - adapter: (0, _util.adapterObject)(this.adapter), - settings: options.pouchSettings - }; - var pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); - (0, _hooks.runPluginHooks)('preCreatePouchDb', pouchDbParameters); - return new _pouchDb.PouchDB(pouchDbParameters.location, pouchDBOptions); - }; + case 8: + return _context2.abrupt("return", null); - _proto.createInternalStorageInstance = function createInternalStorageInstance(databaseName, _options) { - var storageInstance = this.createStorageInstance(databaseName, '_rxdb_internal', 0, { - pouchSettings: { - // no compaction because this only stores local documents - auto_compaction: false, - revs_limit: 1 + case 9: + case "end": + return _context2.stop(); + } } - }); - return Promise.resolve(storageInstance); - } - /** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ - ; + }, _callee2); + })); + return _getSingleDocument.apply(this, arguments); +} - _proto.prepareQuery = function prepareQuery(rxQuery, mutateableQuery) { - var primPath = rxQuery.collection.schema.primaryPath; - var query = mutateableQuery; - /** - * because sort wont work on unused keys we have to workaround - * so we add the key to the selector if necessary - * @link https://github.com/nolanlawson/pouchdb-find/issues/204 - */ +function countAllUndeleted(_x4) { + return _countAllUndeleted.apply(this, arguments); +} +/** + * get a batch of documents from the storage-instance + */ - if (query.sort) { - query.sort.forEach(function (sortPart) { - var key = Object.keys(sortPart)[0]; - var comparisonOperators = ['$gt', '$gte', '$lt', '$lte']; - var keyUsed = query.selector[key] && Object.keys(query.selector[key]).some(function (op) { - return comparisonOperators.includes(op); - }) || false; - if (!keyUsed) { - var schemaObj = rxQuery.collection.schema.getSchemaByObjectPath(key); +function _countAllUndeleted() { + _countAllUndeleted = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(storageInstance) { + var docs; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getAllDocuments(storageInstance); - if (!schemaObj) { - throw (0, _rxError.newRxError)('QU5', { - key: key - }); - } + case 2: + docs = _context3.sent; + return _context3.abrupt("return", docs.length); - if (!query.selector[key]) { - query.selector[key] = {}; - } + case 4: + case "end": + return _context3.stop(); + } + } + }, _callee3); + })); + return _countAllUndeleted.apply(this, arguments); +} - switch (schemaObj.type) { - case 'number': - case 'integer': - // TODO change back to -Infinity when issue resolved - // @link https://github.com/pouchdb/pouchdb/issues/6454 - // -Infinity does not work since pouchdb 6.2.0 - query.selector[key].$gt = -9999999999999999999999999999; - break; +function getBatch(_x5, _x6) { + return _getBatch.apply(this, arguments); +} +/** + * Writes a single document, + * throws RxStorageBulkWriteError on failure + */ - case 'string': - /** - * strings need an empty string, see - * @link https://github.com/pubkey/rxdb/issues/585 - */ - if (typeof query.selector[key] !== 'string') { - query.selector[key].$gt = ''; - } +function _getBatch() { + _getBatch = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(storageInstance, limit) { + var preparedQuery, result; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (!(limit <= 1)) { + _context4.next = 2; break; + } - default: - query.selector[key].$gt = null; - break; - } + throw (0, _rxError.newRxError)('P1', { + limit: limit + }); + + case 2: + preparedQuery = storageInstance.prepareQuery({ + selector: {}, + limit: limit + }); + _context4.next = 5; + return storageInstance.query(preparedQuery); + + case 5: + result = _context4.sent; + return _context4.abrupt("return", result.documents); + + case 7: + case "end": + return _context4.stop(); } - }); - } // regex does not work over the primary key - // TODO move this to dev mode + } + }, _callee4); + })); + return _getBatch.apply(this, arguments); +} +function writeSingle(_x7, _x8) { + return _writeSingle.apply(this, arguments); +} +/** + * Writes a single local document, + * throws RxStorageBulkWriteError on failure + */ - if (query.selector[primPath] && query.selector[primPath].$regex) { - throw (0, _rxError.newRxError)('QU4', { - path: primPath, - query: rxQuery.mangoQuery - }); - } // primary-swap sorting +function _writeSingle() { + _writeSingle = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(instance, writeRow) { + var writeResult, error, ret; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return instance.bulkWrite([writeRow]); - if (query.sort) { - var sortArray = query.sort.map(function (part) { - var _newPart; + case 2: + writeResult = _context5.sent; - var key = Object.keys(part)[0]; - var direction = Object.values(part)[0]; - var useKey = key === primPath ? '_id' : key; - var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); - return newPart; - }); - query.sort = sortArray; - } // strip empty selectors + if (!(writeResult.error.size > 0)) { + _context5.next = 8; + break; + } + error = writeResult.error.values().next().value; + throw error; - Object.entries(query.selector).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; + case 8: + ret = writeResult.success.values().next().value; + return _context5.abrupt("return", ret); - if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { - delete query.selector[k]; + case 10: + case "end": + return _context5.stop(); + } } - }); + }, _callee5); + })); + return _writeSingle.apply(this, arguments); +} - if (primPath !== '_id') { - query.selector = primarySwapPouchDbQuerySelector(query.selector, primPath); - } +function writeSingleLocal(_x9, _x10) { + return _writeSingleLocal.apply(this, arguments); +} - return query; - }; +function _writeSingleLocal() { + _writeSingleLocal = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(instance, writeRow) { + var writeResult, error, ret; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return instance.bulkWrite([writeRow]); - return RxStoragePouchDbClass; -}(); -/** - * Runs a primary swap with transform all custom primaryKey occurences - * into '_id' - * @recursive - */ + case 2: + writeResult = _context6.sent; + if (!(writeResult.error.size > 0)) { + _context6.next = 8; + break; + } -exports.RxStoragePouchDbClass = RxStoragePouchDbClass; + error = writeResult.error.values().next().value; + throw error; -function primarySwapPouchDbQuerySelector(selector, primaryKey) { - if (Array.isArray(selector)) { - return selector.map(function (item) { - return primarySwapPouchDbQuerySelector(item, primaryKey); - }); - } else if (typeof selector === 'object') { - var ret = {}; - Object.entries(selector).forEach(function (_ref3) { - var k = _ref3[0], - v = _ref3[1]; + case 8: + ret = writeResult.success.values().next().value; + return _context6.abrupt("return", ret); - if (k === primaryKey) { - ret._id = v; - } else { - if (k.startsWith('$')) { - ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); - } else { - ret[k] = v; + case 10: + case "end": + return _context6.stop(); } } - }); - return ret; - } else { - return selector; - } + }, _callee6); + })); + return _writeSingleLocal.apply(this, arguments); } -/** - * returns the pouchdb-database-name - */ +function findLocalDocument(_x11, _x12) { + return _findLocalDocument.apply(this, arguments); +} -function getPouchLocation(dbName, collectionName, schemaVersion) { - var prefix = dbName + '-rxdb-' + schemaVersion + '-'; +function _findLocalDocument() { + _findLocalDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(instance, id) { + var docList, doc; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return instance.findLocalDocumentsById([id]); - if (!collectionName.includes('/')) { - return prefix + collectionName; - } else { - // if collectionName is a path, we have to prefix the last part only - var split = collectionName.split('/'); - var last = split.pop(); - var ret = split.join('/'); - ret += '/' + prefix + last; - return ret; - } -} + case 2: + docList = _context7.sent; + doc = docList.get(id); -function getRxStoragePouchDb(adapter, pouchSettings) { - if (!adapter) { - throw new Error('adapter missing'); - } + if (doc) { + _context7.next = 8; + break; + } - return new RxStoragePouchDbClass(adapter, pouchSettings); + return _context7.abrupt("return", null); + + case 8: + return _context7.abrupt("return", doc); + + case 9: + case "end": + return _context7.stop(); + } + } + }, _callee7); + })); + return _findLocalDocument.apply(this, arguments); } +function getNewestSequence(_x13) { + return _getNewestSequence.apply(this, arguments); +} -},{"./hooks":7,"./pouch-db":37,"./rx-error":46,"./util":56,"pouchdb-selector-core":665}],50:[function(require,module,exports){ -"use strict"; +function _getNewestSequence() { + _getNewestSequence = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(storageInstance) { + var changesResult; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return storageInstance.getChangedDocuments({ + order: 'desc', + limit: 1, + startSequence: 0 + }); + case 2: + changesResult = _context8.sent; + return _context8.abrupt("return", changesResult.lastSequence); -},{}],51:[function(require,module,exports){ -"use strict"; + case 4: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + return _getNewestSequence.apply(this, arguments); +} +function storageChangeEventToRxChangeEvent(isLocal, rxStorageChangeEvent, rxDatabase, rxCollection) { + var documentData; -},{}],52:[function(require,module,exports){ -"use strict"; + if (rxStorageChangeEvent.change.operation !== 'DELETE') { + if (!rxCollection) { + documentData = rxStorageChangeEvent.change.doc; + } else { + var hookParams = { + collection: rxCollection, + doc: rxStorageChangeEvent.change.doc + }; + (0, _hooks.runPluginHooks)('postReadFromInstance', hookParams); + documentData = hookParams.doc; + documentData = rxCollection._crypter.decrypt(documentData); + } + } + + var previousDocumentData; + if (rxStorageChangeEvent.change.operation !== 'INSERT') { + if (!rxCollection) { + previousDocumentData = rxStorageChangeEvent.change.previous; + } else { + var _hookParams = { + collection: rxCollection, + doc: rxStorageChangeEvent.change.previous + }; + (0, _hooks.runPluginHooks)('postReadFromInstance', _hookParams); + previousDocumentData = _hookParams.doc; + previousDocumentData = rxCollection._crypter.decrypt(previousDocumentData); + } + } -},{}],53:[function(require,module,exports){ + var ret = { + eventId: rxStorageChangeEvent.eventId, + documentId: rxStorageChangeEvent.documentId, + databaseToken: rxDatabase.token, + collectionName: rxCollection ? rxCollection.name : undefined, + startTime: rxStorageChangeEvent.startTime, + endTime: rxStorageChangeEvent.endTime, + isLocal: isLocal, + operation: rxStorageChangeEvent.change.operation, + documentData: _overwritable.overwritable.deepFreezeWhenDevMode(documentData), + previousDocumentData: _overwritable.overwritable.deepFreezeWhenDevMode(previousDocumentData) + }; + return ret; +} + + +},{"./hooks":7,"./overwritable":9,"./rx-error":48,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72}],53:[function(require,module,exports){ "use strict"; @@ -10464,6 +13158,14 @@ function getRxStoragePouchDb(adapter, pouchSettings) { },{}],56:[function(require,module,exports){ +"use strict"; + + +},{}],57:[function(require,module,exports){ +"use strict"; + + +},{}],58:[function(require,module,exports){ (function (Buffer){(function (){ "use strict"; @@ -10475,7 +13177,6 @@ Object.defineProperty(exports, "__esModule", { exports.pluginMissing = pluginMissing; exports.fastUnsecureHash = fastUnsecureHash; exports.hash = hash; -exports.generateId = generateId; exports.now = now; exports.nextTick = nextTick; exports.promiseWait = promiseWait; @@ -10489,6 +13190,7 @@ exports.ensureNotFalsy = ensureNotFalsy; exports.sortObject = sortObject; exports.stringifyFilter = stringifyFilter; exports.randomCouchString = randomCouchString; +exports.lastOfArray = lastOfArray; exports.shuffleArray = shuffleArray; exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; exports.adapterObject = adapterObject; @@ -10498,9 +13200,8 @@ exports.getHeightOfRevision = getHeightOfRevision; exports.createRevision = createRevision; exports.overwriteGetterForCaching = overwriteGetterForCaching; exports.isFolderPath = isFolderPath; -exports.blobBufferUtil = exports.LOCAL_PREFIX = exports.isElectronRenderer = exports.clone = exports.RXDB_HASH_SALT = void 0; - -var _randomToken = _interopRequireDefault(require("random-token")); +exports.getFromMapOrThrow = getFromMapOrThrow; +exports.blobBufferUtil = exports.isElectronRenderer = exports.clone = exports.RXDB_HASH_SALT = void 0; var _clone = _interopRequireDefault(require("clone")); @@ -10512,11 +13213,6 @@ var _pouchdbMd = require("pouchdb-md5"); var _pouchdbUtils = require("pouchdb-utils"); -/** - * this contains a mapping to basic dependencies - * which should be easy to change - */ - /** * Returns an error that indicates that a plugin is missing * We do not throw a RxError because this should not be handled @@ -10578,14 +13274,6 @@ function hash(msg) { return _sparkMd["default"].hash(RXDB_HASH_SALT + msg); } -/** - * generate a new _id as db-primary-key - */ - - -function generateId() { - return (0, _randomToken["default"])(10) + ':' + now(); -} /** * Returns the current unix time in milliseconds * Because the accuracy of getTime() in javascript is bad, @@ -10749,7 +13437,10 @@ function sortObject(obj) { function stringifyFilter(key, value) { - if (value instanceof RegExp) return value.toString(); + if (value instanceof RegExp) { + return value.toString(); + } + return value; } /** @@ -10769,6 +13460,10 @@ function randomCouchString() { return text; } + +function lastOfArray(ar) { + return ar[ar.length - 1]; +} /** * shuffle the given array */ @@ -10885,18 +13580,11 @@ function createRevision(docData, deterministic_revs) { }); return (0, _pouchdbMd.stringMd5)(JSON.stringify(docWithoutRev)); } -/** - * prefix of local pouchdb documents - */ - - -var LOCAL_PREFIX = '_local/'; /** * overwrites the getter with the actual value * Mostly used for caching stuff on the first run */ -exports.LOCAL_PREFIX = LOCAL_PREFIX; function overwriteGetterForCaching(obj, getterName, value) { Object.defineProperty(obj, getterName, { @@ -10922,6 +13610,16 @@ function isFolderPath(name) { } } +function getFromMapOrThrow(map, key) { + var val = map.get(key); + + if (!val) { + throw new Error('missing value from map ' + key); + } + + return val; +} + var blobBufferUtil = { /** * depending if we are on node or browser, @@ -10951,6 +13649,13 @@ var blobBufferUtil = { return blobBuffer; }, + isBlobBuffer: function isBlobBuffer(data) { + if (data instanceof Blob || Buffer.isBuffer(data)) { + return true; + } else { + return false; + } + }, toString: function toString(blobBuffer) { if (blobBuffer instanceof Buffer) { // node @@ -10985,7 +13690,7 @@ exports.blobBufferUtil = blobBufferUtil; }).call(this)}).call(this,require("buffer").Buffer) -},{"@babel/runtime/helpers/interopRequireDefault":65,"buffer":169,"clone":173,"is-electron":592,"pouchdb-md5":662,"pouchdb-utils":666,"random-token":675,"spark-md5":920}],57:[function(require,module,exports){ +},{"@babel/runtime/helpers/interopRequireDefault":67,"buffer":170,"clone":174,"is-electron":591,"pouchdb-md5":662,"pouchdb-utils":666,"spark-md5":920}],59:[function(require,module,exports){ "use strict"; require("./noConflict"); @@ -10999,7 +13704,7 @@ if (_global["default"]._babelPolyfill && typeof console !== "undefined" && conso } _global["default"]._babelPolyfill = true; -},{"./noConflict":58,"core-js/library/fn/global":186}],58:[function(require,module,exports){ +},{"./noConflict":60,"core-js/library/fn/global":187}],60:[function(require,module,exports){ "use strict"; require("core-js/es6"); @@ -11029,7 +13734,7 @@ require("core-js/fn/promise/finally"); require("core-js/web"); require("regenerator-runtime/runtime"); -},{"core-js/es6":174,"core-js/fn/array/flat-map":175,"core-js/fn/array/includes":176,"core-js/fn/object/entries":177,"core-js/fn/object/get-own-property-descriptors":178,"core-js/fn/object/values":179,"core-js/fn/promise/finally":180,"core-js/fn/string/pad-end":181,"core-js/fn/string/pad-start":182,"core-js/fn/string/trim-end":183,"core-js/fn/string/trim-start":184,"core-js/fn/symbol/async-iterator":185,"core-js/web":477,"regenerator-runtime/runtime":678}],59:[function(require,module,exports){ +},{"core-js/es6":175,"core-js/fn/array/flat-map":176,"core-js/fn/array/includes":177,"core-js/fn/object/entries":178,"core-js/fn/object/get-own-property-descriptors":179,"core-js/fn/object/values":180,"core-js/fn/promise/finally":181,"core-js/fn/string/pad-end":182,"core-js/fn/string/pad-start":183,"core-js/fn/string/trim-end":184,"core-js/fn/string/trim-start":185,"core-js/fn/symbol/async-iterator":186,"core-js/web":478,"regenerator-runtime/runtime":678}],61:[function(require,module,exports){ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); @@ -11040,7 +13745,7 @@ function _assertThisInitialized(self) { module.exports = _assertThisInitialized; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],60:[function(require,module,exports){ +},{}],62:[function(require,module,exports){ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); @@ -11079,7 +13784,7 @@ function _asyncToGenerator(fn) { module.exports = _asyncToGenerator; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],61:[function(require,module,exports){ +},{}],63:[function(require,module,exports){ var setPrototypeOf = require("./setPrototypeOf.js"); var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); @@ -11106,7 +13811,7 @@ function _construct(Parent, args, Class) { module.exports = _construct; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{"./isNativeReflectConstruct.js":67,"./setPrototypeOf.js":68}],62:[function(require,module,exports){ +},{"./isNativeReflectConstruct.js":69,"./setPrototypeOf.js":70}],64:[function(require,module,exports){ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; @@ -11125,7 +13830,7 @@ function _createClass(Constructor, protoProps, staticProps) { module.exports = _createClass; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],63:[function(require,module,exports){ +},{}],65:[function(require,module,exports){ function _getPrototypeOf(o) { module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); @@ -11136,7 +13841,7 @@ function _getPrototypeOf(o) { module.exports = _getPrototypeOf; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],64:[function(require,module,exports){ +},{}],66:[function(require,module,exports){ var setPrototypeOf = require("./setPrototypeOf.js"); function _inheritsLoose(subClass, superClass) { @@ -11147,7 +13852,7 @@ function _inheritsLoose(subClass, superClass) { module.exports = _inheritsLoose; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{"./setPrototypeOf.js":68}],65:[function(require,module,exports){ +},{"./setPrototypeOf.js":70}],67:[function(require,module,exports){ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj @@ -11156,14 +13861,14 @@ function _interopRequireDefault(obj) { module.exports = _interopRequireDefault; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],66:[function(require,module,exports){ +},{}],68:[function(require,module,exports){ function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } module.exports = _isNativeFunction; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],67:[function(require,module,exports){ +},{}],69:[function(require,module,exports){ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; @@ -11179,7 +13884,7 @@ function _isNativeReflectConstruct() { module.exports = _isNativeReflectConstruct; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],68:[function(require,module,exports){ +},{}],70:[function(require,module,exports){ function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; @@ -11192,7 +13897,7 @@ function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{}],69:[function(require,module,exports){ +},{}],71:[function(require,module,exports){ var getPrototypeOf = require("./getPrototypeOf.js"); var setPrototypeOf = require("./setPrototypeOf.js"); @@ -11238,10 +13943,10 @@ function _wrapNativeSuper(Class) { module.exports = _wrapNativeSuper; module.exports["default"] = module.exports, module.exports.__esModule = true; -},{"./construct.js":61,"./getPrototypeOf.js":63,"./isNativeFunction.js":66,"./setPrototypeOf.js":68}],70:[function(require,module,exports){ +},{"./construct.js":63,"./getPrototypeOf.js":65,"./isNativeFunction.js":68,"./setPrototypeOf.js":70}],72:[function(require,module,exports){ module.exports = require("regenerator-runtime"); -},{"regenerator-runtime":678}],71:[function(require,module,exports){ +},{"regenerator-runtime":678}],73:[function(require,module,exports){ 'use strict'; module.exports = argsArray; @@ -11261,34 +13966,7 @@ function argsArray(fun) { } }; } -},{}],72:[function(require,module,exports){ - -/** - * Array#filter. - * - * @param {Array} arr - * @param {Function} fn - * @param {Object=} self - * @return {Array} - * @throw TypeError - */ - -module.exports = function (arr, fn, self) { - if (arr.filter) return arr.filter(fn, self); - if (void 0 === arr || null === arr) throw new TypeError; - if ('function' != typeof fn) throw new TypeError; - var ret = []; - for (var i = 0; i < arr.length; i++) { - if (!hasOwn.call(arr, i)) continue; - var val = arr[i]; - if (fn.call(self, val, i, arr)) ret.push(val); - } - return ret; -}; - -var hasOwn = Object.prototype.hasOwnProperty; - -},{}],73:[function(require,module,exports){ +},{}],74:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -11336,7 +14014,7 @@ function pushAtSortPosition(array, item, compareFunction, noCopy) { ret.splice(mid, 0, item); return ret; } -},{}],74:[function(require,module,exports){ +},{}],75:[function(require,module,exports){ 'use strict'; const asn1 = exports; @@ -11349,7 +14027,7 @@ asn1.constants = require('./asn1/constants'); asn1.decoders = require('./asn1/decoders'); asn1.encoders = require('./asn1/encoders'); -},{"./asn1/api":75,"./asn1/base":77,"./asn1/constants":81,"./asn1/decoders":83,"./asn1/encoders":86,"bn.js":88}],75:[function(require,module,exports){ +},{"./asn1/api":76,"./asn1/base":78,"./asn1/constants":82,"./asn1/decoders":84,"./asn1/encoders":87,"bn.js":89}],76:[function(require,module,exports){ 'use strict'; const encoders = require('./encoders'); @@ -11408,7 +14086,7 @@ Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; -},{"./decoders":83,"./encoders":86,"inherits":587}],76:[function(require,module,exports){ +},{"./decoders":84,"./encoders":87,"inherits":586}],77:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -11563,7 +14241,7 @@ EncoderBuffer.prototype.join = function join(out, offset) { return out; }; -},{"../base/reporter":79,"inherits":587,"safer-buffer":910}],77:[function(require,module,exports){ +},{"../base/reporter":80,"inherits":586,"safer-buffer":910}],78:[function(require,module,exports){ 'use strict'; const base = exports; @@ -11573,7 +14251,7 @@ base.DecoderBuffer = require('./buffer').DecoderBuffer; base.EncoderBuffer = require('./buffer').EncoderBuffer; base.Node = require('./node'); -},{"./buffer":76,"./node":78,"./reporter":79}],78:[function(require,module,exports){ +},{"./buffer":77,"./node":79,"./reporter":80}],79:[function(require,module,exports){ 'use strict'; const Reporter = require('../base/reporter').Reporter; @@ -12213,7 +14891,7 @@ Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); }; -},{"../base/buffer":76,"../base/reporter":79,"minimalistic-assert":618}],79:[function(require,module,exports){ +},{"../base/buffer":77,"../base/reporter":80,"minimalistic-assert":617}],80:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -12338,7 +15016,7 @@ ReporterError.prototype.rethrow = function rethrow(msg) { return this; }; -},{"inherits":587}],80:[function(require,module,exports){ +},{"inherits":586}],81:[function(require,module,exports){ 'use strict'; // Helper @@ -12398,7 +15076,7 @@ exports.tag = { }; exports.tagByName = reverse(exports.tag); -},{}],81:[function(require,module,exports){ +},{}],82:[function(require,module,exports){ 'use strict'; const constants = exports; @@ -12421,7 +15099,7 @@ constants._reverse = function reverse(map) { constants.der = require('./der'); -},{"./der":80}],82:[function(require,module,exports){ +},{"./der":81}],83:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -12758,7 +15436,7 @@ function derDecodeLen(buf, primitive, fail) { return len; } -},{"../base/buffer":76,"../base/node":78,"../constants/der":80,"bn.js":88,"inherits":587}],83:[function(require,module,exports){ +},{"../base/buffer":77,"../base/node":79,"../constants/der":81,"bn.js":89,"inherits":586}],84:[function(require,module,exports){ 'use strict'; const decoders = exports; @@ -12766,7 +15444,7 @@ const decoders = exports; decoders.der = require('./der'); decoders.pem = require('./pem'); -},{"./der":82,"./pem":84}],84:[function(require,module,exports){ +},{"./der":83,"./pem":85}],85:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -12819,7 +15497,7 @@ PEMDecoder.prototype.decode = function decode(data, options) { return DERDecoder.prototype.decode.call(this, input, options); }; -},{"./der":82,"inherits":587,"safer-buffer":910}],85:[function(require,module,exports){ +},{"./der":83,"inherits":586,"safer-buffer":910}],86:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -13116,7 +15794,7 @@ function encodeTag(tag, primitive, cls, reporter) { return res; } -},{"../base/node":78,"../constants/der":80,"inherits":587,"safer-buffer":910}],86:[function(require,module,exports){ +},{"../base/node":79,"../constants/der":81,"inherits":586,"safer-buffer":910}],87:[function(require,module,exports){ 'use strict'; const encoders = exports; @@ -13124,7 +15802,7 @@ const encoders = exports; encoders.der = require('./der'); encoders.pem = require('./pem'); -},{"./der":85,"./pem":87}],87:[function(require,module,exports){ +},{"./der":86,"./pem":88}],88:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -13149,7 +15827,7 @@ PEMEncoder.prototype.encode = function encode(data, options) { return out.join('\n'); }; -},{"./der":85,"inherits":587}],88:[function(require,module,exports){ +},{"./der":86,"inherits":586}],89:[function(require,module,exports){ (function (module, exports) { 'use strict'; @@ -16597,32 +19275,36 @@ PEMEncoder.prototype.encode = function encode(data, options) { }; })(typeof module === 'undefined' || module, this); -},{"buffer":124}],89:[function(require,module,exports){ +},{"buffer":125}],90:[function(require,module,exports){ (function (global){(function (){ 'use strict'; -var filter = require('array-filter'); +var possibleNames = [ + 'BigInt64Array', + 'BigUint64Array', + 'Float32Array', + 'Float64Array', + 'Int16Array', + 'Int32Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Uint8Array', + 'Uint8ClampedArray' +]; module.exports = function availableTypedArrays() { - return filter([ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' - ], function (typedArray) { - return typeof global[typedArray] === 'function'; - }); + var out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof global[possibleNames[i]] === 'function') { + out[out.length] = possibleNames[i]; + } + } + return out; }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"array-filter":72}],90:[function(require,module,exports){ +},{}],91:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -16774,7 +19456,7 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],91:[function(require,module,exports){ +},{}],92:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("./util"); @@ -16949,7 +19631,7 @@ var AbstractNode = /** @class */ (function () { }()); exports.AbstractNode = AbstractNode; -},{"./find-similar-node":96,"./util":109}],92:[function(require,module,exports){ +},{"./find-similar-node":97,"./util":110}],93:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** @@ -17025,7 +19707,7 @@ function ensureNodesNotStrictEqual(node1, node2) { } exports.ensureNodesNotStrictEqual = ensureNodesNotStrictEqual; -},{}],93:[function(require,module,exports){ +},{}],94:[function(require,module,exports){ "use strict"; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; @@ -17101,7 +19783,7 @@ function createBddFromTruthTable(truthTable) { } exports.createBddFromTruthTable = createBddFromTruthTable; -},{"./internal-node":98,"./leaf-node":99,"./root-node":108,"./util":109}],94:[function(require,module,exports){ +},{"./internal-node":99,"./leaf-node":100,"./root-node":109,"./util":110}],95:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** @@ -17204,7 +19886,7 @@ function getNodesRecursive(node, set) { } exports.getNodesRecursive = getNodesRecursive; -},{}],95:[function(require,module,exports){ +},{}],96:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("./util"); @@ -17230,7 +19912,7 @@ function fillTruthTable(truthTable, inputLength, value) { } exports.fillTruthTable = fillTruthTable; -},{"./util":109}],96:[function(require,module,exports){ +},{"./util":110}],97:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** @@ -17252,7 +19934,7 @@ function findSimilarNode(own, others) { } exports.findSimilarNode = findSimilarNode; -},{}],97:[function(require,module,exports){ +},{}],98:[function(require,module,exports){ "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; @@ -17272,7 +19954,7 @@ __export(require("./parents")); __export(require("./root-node")); __export(require("./util")); -},{"./abstract-node":91,"./branches":92,"./create-bdd-from-truth-table":93,"./ensure-correct-bdd":94,"./fill-truth-table":95,"./find-similar-node":96,"./internal-node":98,"./leaf-node":99,"./minimal-string/index":102,"./optimize-brute-force":106,"./parents":107,"./root-node":108,"./util":109}],98:[function(require,module,exports){ +},{"./abstract-node":92,"./branches":93,"./create-bdd-from-truth-table":94,"./ensure-correct-bdd":95,"./fill-truth-table":96,"./find-similar-node":97,"./internal-node":99,"./leaf-node":100,"./minimal-string/index":103,"./optimize-brute-force":107,"./parents":108,"./root-node":109,"./util":110}],99:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { @@ -17335,7 +20017,7 @@ var InternalNode = /** @class */ (function (_super) { }(abstract_node_1.AbstractNode)); exports.InternalNode = InternalNode; -},{"./abstract-node":91,"./branches":92,"./parents":107}],99:[function(require,module,exports){ +},{"./abstract-node":92,"./branches":93,"./parents":108}],100:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { @@ -17385,7 +20067,7 @@ var LeafNode = /** @class */ (function (_super) { }(abstract_node_1.AbstractNode)); exports.LeafNode = LeafNode; -},{"./abstract-node":91,"./parents":107,"./util":109}],100:[function(require,module,exports){ +},{"./abstract-node":92,"./parents":108,"./util":110}],101:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var string_format_1 = require("./string-format"); @@ -17445,7 +20127,7 @@ function nodeToString(node, idByNode, lastCode) { } exports.nodeToString = nodeToString; -},{"./string-format":105}],101:[function(require,module,exports){ +},{"./string-format":106}],102:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** @@ -17469,7 +20151,7 @@ function nodeToSimpleBddNode(node) { } exports.nodeToSimpleBddNode = nodeToSimpleBddNode; -},{}],102:[function(require,module,exports){ +},{}],103:[function(require,module,exports){ "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; @@ -17481,7 +20163,7 @@ __export(require("./resolve-with-simple-bdd")); __export(require("./string-format")); __export(require("./bdd-to-simple-bdd")); -},{"./bdd-to-minimal-string":100,"./bdd-to-simple-bdd":101,"./minimal-string-to-simple-bdd":103,"./resolve-with-simple-bdd":104,"./string-format":105}],103:[function(require,module,exports){ +},{"./bdd-to-minimal-string":101,"./bdd-to-simple-bdd":102,"./minimal-string-to-simple-bdd":104,"./resolve-with-simple-bdd":105,"./string-format":106}],104:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("../util"); @@ -17539,7 +20221,7 @@ function minimalStringToSimpleBdd(str) { } exports.minimalStringToSimpleBdd = minimalStringToSimpleBdd; -},{"../util":109,"./string-format":105}],104:[function(require,module,exports){ +},{"../util":110,"./string-format":106}],105:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("../util"); @@ -17560,7 +20242,7 @@ function resolveWithSimpleBdd(simpleBdd, fns, input) { } exports.resolveWithSimpleBdd = resolveWithSimpleBdd; -},{"../util":109}],105:[function(require,module,exports){ +},{"../util":110}],106:[function(require,module,exports){ "use strict"; /* let t = 0; @@ -17621,7 +20303,7 @@ function getNextCharId(lastCode) { } exports.getNextCharId = getNextCharId; -},{}],106:[function(require,module,exports){ +},{}],107:[function(require,module,exports){ "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -17858,7 +20540,7 @@ function getArrayWithIndexes(size) { } exports.getArrayWithIndexes = getArrayWithIndexes; -},{"./create-bdd-from-truth-table":93,"./util":109}],107:[function(require,module,exports){ +},{"./create-bdd-from-truth-table":94,"./util":110}],108:[function(require,module,exports){ "use strict"; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; @@ -17927,7 +20609,7 @@ var Parents = /** @class */ (function () { }()); exports.Parents = Parents; -},{}],108:[function(require,module,exports){ +},{}],109:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { @@ -18136,7 +20818,7 @@ var RootNode = /** @class */ (function (_super) { }(abstract_node_1.AbstractNode)); exports.RootNode = RootNode; -},{"./abstract-node":91,"./branches":92,"./minimal-string":102,"./util":109}],109:[function(require,module,exports){ +},{"./abstract-node":92,"./branches":93,"./minimal-string":103,"./util":110}],110:[function(require,module,exports){ "use strict"; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; @@ -18281,7 +20963,7 @@ function splitStringToChunks(str, chunkSize) { } exports.splitStringToChunks = splitStringToChunks; -},{}],110:[function(require,module,exports){ +},{}],111:[function(require,module,exports){ (function (module, exports) { 'use strict'; @@ -21830,7 +24512,7 @@ exports.splitStringToChunks = splitStringToChunks; }; })(typeof module === 'undefined' || module, this); -},{"buffer":124}],111:[function(require,module,exports){ +},{"buffer":125}],112:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -22007,6 +24689,10 @@ BroadcastChannel.prototype = { get type() { return this.method.type; + }, + + get isClosed() { + return this.closed; } }; @@ -22106,7 +24792,7 @@ function _stopListening(channel) { channel.method.onMessage(channel._state, null, time); } } -},{"./method-chooser.js":115,"./options.js":121,"./util.js":122}],112:[function(require,module,exports){ +},{"./method-chooser.js":116,"./options.js":122,"./util.js":123}],113:[function(require,module,exports){ "use strict"; var _index = require("./index.js"); @@ -22126,7 +24812,7 @@ module.exports = { enforceOptions: _index.enforceOptions, beLeader: _index.beLeader }; -},{"./index.js":113}],113:[function(require,module,exports){ +},{"./index.js":114}],114:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -22166,7 +24852,7 @@ Object.defineProperty(exports, "beLeader", { var _broadcastChannel = require("./broadcast-channel"); var _leaderElection = require("./leader-election"); -},{"./broadcast-channel":111,"./leader-election":114}],114:[function(require,module,exports){ +},{"./broadcast-channel":112,"./leader-election":115}],115:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -22441,7 +25127,7 @@ function createLeaderElection(channel, options) { channel._leaderElector = elector; return elector; } -},{"./util.js":122,"@babel/runtime/helpers/interopRequireDefault":65,"unload":938}],115:[function(require,module,exports){ +},{"./util.js":123,"@babel/runtime/helpers/interopRequireDefault":67,"unload":938}],116:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -22522,7 +25208,7 @@ function chooseMethod(options) { return m.type; })));else return useMethod; } -},{"./methods/indexed-db.js":116,"./methods/localstorage.js":117,"./methods/native.js":118,"./methods/simulate.js":119,"./util":122,"@babel/runtime/helpers/interopRequireDefault":65}],116:[function(require,module,exports){ +},{"./methods/indexed-db.js":117,"./methods/localstorage.js":118,"./methods/native.js":119,"./methods/simulate.js":120,"./util":123,"@babel/runtime/helpers/interopRequireDefault":67}],117:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -22875,7 +25561,7 @@ var _default = { microSeconds: microSeconds }; exports["default"] = _default; -},{"../oblivious-set":120,"../options":121,"../util.js":122,"@babel/runtime/helpers/interopRequireDefault":65}],117:[function(require,module,exports){ +},{"../oblivious-set":121,"../options":122,"../util.js":123,"@babel/runtime/helpers/interopRequireDefault":67}],118:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -23075,7 +25761,7 @@ var _default = { microSeconds: microSeconds }; exports["default"] = _default; -},{"../oblivious-set":120,"../options":121,"../util":122,"@babel/runtime/helpers/interopRequireDefault":65}],118:[function(require,module,exports){ +},{"../oblivious-set":121,"../options":122,"../util":123,"@babel/runtime/helpers/interopRequireDefault":67}],119:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -23162,7 +25848,7 @@ var _default = { microSeconds: microSeconds }; exports["default"] = _default; -},{"../util":122}],119:[function(require,module,exports){ +},{"../util":123}],120:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -23238,7 +25924,7 @@ var _default = { microSeconds: microSeconds }; exports["default"] = _default; -},{"../util":122}],120:[function(require,module,exports){ +},{"../util":123}],121:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -23296,7 +25982,7 @@ function now() { var _default = ObliviousSet; exports["default"] = _default; -},{}],121:[function(require,module,exports){ +},{}],122:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -23328,7 +26014,7 @@ function fillOptionsWithDefaults() { if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true; return options; } -},{}],122:[function(require,module,exports){ +},{}],123:[function(require,module,exports){ (function (process){(function (){ "use strict"; @@ -23404,7 +26090,7 @@ function microSeconds() { var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; exports.isNode = isNode; }).call(this)}).call(this,require('_process')) -},{"_process":667}],123:[function(require,module,exports){ +},{"_process":667}],124:[function(require,module,exports){ var r; module.exports = function rand(len) { @@ -23471,9 +26157,9 @@ if (typeof self === 'object') { } } -},{"crypto":124}],124:[function(require,module,exports){ +},{"crypto":125}],125:[function(require,module,exports){ -},{}],125:[function(require,module,exports){ +},{}],126:[function(require,module,exports){ // based on the aes implimentation in triple sec // https://github.com/keybase/triplesec // which is in turn based on the one from crypto-js @@ -23703,7 +26389,7 @@ AES.prototype.scrub = function () { module.exports.AES = AES -},{"safe-buffer":909}],126:[function(require,module,exports){ +},{"safe-buffer":909}],127:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') @@ -23822,7 +26508,7 @@ StreamCipher.prototype.setAAD = function setAAD (buf) { module.exports = StreamCipher -},{"./aes":125,"./ghash":130,"./incr32":131,"buffer-xor":168,"cipher-base":172,"inherits":587,"safe-buffer":909}],127:[function(require,module,exports){ +},{"./aes":126,"./ghash":131,"./incr32":132,"buffer-xor":169,"cipher-base":173,"inherits":586,"safe-buffer":909}],128:[function(require,module,exports){ var ciphers = require('./encrypter') var deciphers = require('./decrypter') var modes = require('./modes/list.json') @@ -23837,7 +26523,7 @@ exports.createDecipher = exports.Decipher = deciphers.createDecipher exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv exports.listCiphers = exports.getCiphers = getCiphers -},{"./decrypter":128,"./encrypter":129,"./modes/list.json":139}],128:[function(require,module,exports){ +},{"./decrypter":129,"./encrypter":130,"./modes/list.json":140}],129:[function(require,module,exports){ var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer var MODES = require('./modes') @@ -23963,7 +26649,7 @@ function createDecipher (suite, password) { exports.createDecipher = createDecipher exports.createDecipheriv = createDecipheriv -},{"./aes":125,"./authCipher":126,"./modes":138,"./streamCipher":141,"cipher-base":172,"evp_bytestokey":540,"inherits":587,"safe-buffer":909}],129:[function(require,module,exports){ +},{"./aes":126,"./authCipher":127,"./modes":139,"./streamCipher":142,"cipher-base":173,"evp_bytestokey":539,"inherits":586,"safe-buffer":909}],130:[function(require,module,exports){ var MODES = require('./modes') var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer @@ -24079,7 +26765,7 @@ function createCipher (suite, password) { exports.createCipheriv = createCipheriv exports.createCipher = createCipher -},{"./aes":125,"./authCipher":126,"./modes":138,"./streamCipher":141,"cipher-base":172,"evp_bytestokey":540,"inherits":587,"safe-buffer":909}],130:[function(require,module,exports){ +},{"./aes":126,"./authCipher":127,"./modes":139,"./streamCipher":142,"cipher-base":173,"evp_bytestokey":539,"inherits":586,"safe-buffer":909}],131:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var ZEROES = Buffer.alloc(16, 0) @@ -24170,7 +26856,7 @@ GHASH.prototype.final = function (abl, bl) { module.exports = GHASH -},{"safe-buffer":909}],131:[function(require,module,exports){ +},{"safe-buffer":909}],132:[function(require,module,exports){ function incr32 (iv) { var len = iv.length var item @@ -24187,7 +26873,7 @@ function incr32 (iv) { } module.exports = incr32 -},{}],132:[function(require,module,exports){ +},{}],133:[function(require,module,exports){ var xor = require('buffer-xor') exports.encrypt = function (self, block) { @@ -24206,7 +26892,7 @@ exports.decrypt = function (self, block) { return xor(out, pad) } -},{"buffer-xor":168}],133:[function(require,module,exports){ +},{"buffer-xor":169}],134:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var xor = require('buffer-xor') @@ -24241,7 +26927,7 @@ exports.encrypt = function (self, data, decrypt) { return out } -},{"buffer-xor":168,"safe-buffer":909}],134:[function(require,module,exports){ +},{"buffer-xor":169,"safe-buffer":909}],135:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer function encryptByte (self, byteParam, decrypt) { @@ -24285,7 +26971,7 @@ exports.encrypt = function (self, chunk, decrypt) { return out } -},{"safe-buffer":909}],135:[function(require,module,exports){ +},{"safe-buffer":909}],136:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer function encryptByte (self, byteParam, decrypt) { @@ -24312,7 +26998,7 @@ exports.encrypt = function (self, chunk, decrypt) { return out } -},{"safe-buffer":909}],136:[function(require,module,exports){ +},{"safe-buffer":909}],137:[function(require,module,exports){ var xor = require('buffer-xor') var Buffer = require('safe-buffer').Buffer var incr32 = require('../incr32') @@ -24344,7 +27030,7 @@ exports.encrypt = function (self, chunk) { return xor(chunk, pad) } -},{"../incr32":131,"buffer-xor":168,"safe-buffer":909}],137:[function(require,module,exports){ +},{"../incr32":132,"buffer-xor":169,"safe-buffer":909}],138:[function(require,module,exports){ exports.encrypt = function (self, block) { return self._cipher.encryptBlock(block) } @@ -24353,7 +27039,7 @@ exports.decrypt = function (self, block) { return self._cipher.decryptBlock(block) } -},{}],138:[function(require,module,exports){ +},{}],139:[function(require,module,exports){ var modeModules = { ECB: require('./ecb'), CBC: require('./cbc'), @@ -24373,7 +27059,7 @@ for (var key in modes) { module.exports = modes -},{"./cbc":132,"./cfb":133,"./cfb1":134,"./cfb8":135,"./ctr":136,"./ecb":137,"./list.json":139,"./ofb":140}],139:[function(require,module,exports){ +},{"./cbc":133,"./cfb":134,"./cfb1":135,"./cfb8":136,"./ctr":137,"./ecb":138,"./list.json":140,"./ofb":141}],140:[function(require,module,exports){ module.exports={ "aes-128-ecb": { "cipher": "AES", @@ -24566,7 +27252,7 @@ module.exports={ } } -},{}],140:[function(require,module,exports){ +},{}],141:[function(require,module,exports){ (function (Buffer){(function (){ var xor = require('buffer-xor') @@ -24586,7 +27272,7 @@ exports.encrypt = function (self, chunk) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":169,"buffer-xor":168}],141:[function(require,module,exports){ +},{"buffer":170,"buffer-xor":169}],142:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') @@ -24615,7 +27301,7 @@ StreamCipher.prototype._final = function () { module.exports = StreamCipher -},{"./aes":125,"cipher-base":172,"inherits":587,"safe-buffer":909}],142:[function(require,module,exports){ +},{"./aes":126,"cipher-base":173,"inherits":586,"safe-buffer":909}],143:[function(require,module,exports){ var DES = require('browserify-des') var aes = require('browserify-aes/browser') var aesModes = require('browserify-aes/modes') @@ -24684,7 +27370,7 @@ exports.createDecipher = exports.Decipher = createDecipher exports.createDecipheriv = exports.Decipheriv = createDecipheriv exports.listCiphers = exports.getCiphers = getCiphers -},{"browserify-aes/browser":127,"browserify-aes/modes":138,"browserify-des":143,"browserify-des/modes":144,"evp_bytestokey":540}],143:[function(require,module,exports){ +},{"browserify-aes/browser":128,"browserify-aes/modes":139,"browserify-des":144,"browserify-des/modes":145,"evp_bytestokey":539}],144:[function(require,module,exports){ var CipherBase = require('cipher-base') var des = require('des.js') var inherits = require('inherits') @@ -24736,7 +27422,7 @@ DES.prototype._final = function () { return Buffer.from(this._des.final()) } -},{"cipher-base":172,"des.js":498,"inherits":587,"safe-buffer":909}],144:[function(require,module,exports){ +},{"cipher-base":173,"des.js":500,"inherits":586,"safe-buffer":909}],145:[function(require,module,exports){ exports['des-ecb'] = { key: 8, iv: 0 @@ -24762,7 +27448,7 @@ exports['des-ede'] = { iv: 0 } -},{}],145:[function(require,module,exports){ +},{}],146:[function(require,module,exports){ (function (Buffer){(function (){ var BN = require('bn.js') var randomBytes = require('randombytes') @@ -24801,10 +27487,10 @@ crt.getr = getr module.exports = crt }).call(this)}).call(this,require("buffer").Buffer) -},{"bn.js":110,"buffer":169,"randombytes":676}],146:[function(require,module,exports){ +},{"bn.js":111,"buffer":170,"randombytes":676}],147:[function(require,module,exports){ module.exports = require('./browser/algorithms.json') -},{"./browser/algorithms.json":147}],147:[function(require,module,exports){ +},{"./browser/algorithms.json":148}],148:[function(require,module,exports){ module.exports={ "sha224WithRSAEncryption": { "sign": "rsa", @@ -24958,7 +27644,7 @@ module.exports={ } } -},{}],148:[function(require,module,exports){ +},{}],149:[function(require,module,exports){ module.exports={ "1.3.132.0.10": "secp256k1", "1.3.132.0.33": "p224", @@ -24968,7 +27654,7 @@ module.exports={ "1.3.132.0.35": "p521" } -},{}],149:[function(require,module,exports){ +},{}],150:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var createHash = require('create-hash') var stream = require('readable-stream') @@ -25062,7 +27748,7 @@ module.exports = { createVerify: createVerify } -},{"./algorithms.json":147,"./sign":150,"./verify":151,"create-hash":480,"inherits":587,"readable-stream":166,"safe-buffer":167}],150:[function(require,module,exports){ +},{"./algorithms.json":148,"./sign":151,"./verify":152,"create-hash":481,"inherits":586,"readable-stream":167,"safe-buffer":168}],151:[function(require,module,exports){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var Buffer = require('safe-buffer').Buffer var createHmac = require('create-hmac') @@ -25207,7 +27893,7 @@ module.exports = sign module.exports.getKey = getKey module.exports.makeKey = makeKey -},{"./curves.json":148,"bn.js":110,"browserify-rsa":145,"create-hmac":482,"elliptic":510,"parse-asn1":639,"safe-buffer":167}],151:[function(require,module,exports){ +},{"./curves.json":149,"bn.js":111,"browserify-rsa":146,"create-hmac":483,"elliptic":512,"parse-asn1":639,"safe-buffer":168}],152:[function(require,module,exports){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var Buffer = require('safe-buffer').Buffer var BN = require('bn.js') @@ -25293,7 +27979,7 @@ function checkValue (b, q) { module.exports = verify -},{"./curves.json":148,"bn.js":110,"elliptic":510,"parse-asn1":639,"safe-buffer":167}],152:[function(require,module,exports){ +},{"./curves.json":149,"bn.js":111,"elliptic":512,"parse-asn1":639,"safe-buffer":168}],153:[function(require,module,exports){ 'use strict'; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } @@ -25422,7 +28108,7 @@ createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.codes = codes; -},{}],153:[function(require,module,exports){ +},{}],154:[function(require,module,exports){ (function (process){(function (){ // Copyright Joyent, Inc. and other Node contributors. // @@ -25564,7 +28250,7 @@ Object.defineProperty(Duplex.prototype, 'destroyed', { } }); }).call(this)}).call(this,require('_process')) -},{"./_stream_readable":155,"./_stream_writable":157,"_process":667,"inherits":587}],154:[function(require,module,exports){ +},{"./_stream_readable":156,"./_stream_writable":158,"_process":667,"inherits":586}],155:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -25604,7 +28290,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":156,"inherits":587}],155:[function(require,module,exports){ +},{"./_stream_transform":157,"inherits":586}],156:[function(require,module,exports){ (function (process,global){(function (){ // Copyright Joyent, Inc. and other Node contributors. // @@ -26731,7 +29417,7 @@ function indexOf(xs, x) { return -1; } }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":152,"./_stream_duplex":153,"./internal/streams/async_iterator":158,"./internal/streams/buffer_list":159,"./internal/streams/destroy":160,"./internal/streams/from":162,"./internal/streams/state":164,"./internal/streams/stream":165,"_process":667,"buffer":169,"events":539,"inherits":587,"string_decoder/":936,"util":124}],156:[function(require,module,exports){ +},{"../errors":153,"./_stream_duplex":154,"./internal/streams/async_iterator":159,"./internal/streams/buffer_list":160,"./internal/streams/destroy":161,"./internal/streams/from":163,"./internal/streams/state":165,"./internal/streams/stream":166,"_process":667,"buffer":170,"events":538,"inherits":586,"string_decoder/":936,"util":125}],157:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -26933,7 +29619,7 @@ function done(stream, er, data) { if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } -},{"../errors":152,"./_stream_duplex":153,"inherits":587}],157:[function(require,module,exports){ +},{"../errors":153,"./_stream_duplex":154,"inherits":586}],158:[function(require,module,exports){ (function (process,global){(function (){ // Copyright Joyent, Inc. and other Node contributors. // @@ -27633,7 +30319,7 @@ Writable.prototype._destroy = function (err, cb) { cb(err); }; }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":152,"./_stream_duplex":153,"./internal/streams/destroy":160,"./internal/streams/state":164,"./internal/streams/stream":165,"_process":667,"buffer":169,"inherits":587,"util-deprecate":939}],158:[function(require,module,exports){ +},{"../errors":153,"./_stream_duplex":154,"./internal/streams/destroy":161,"./internal/streams/state":165,"./internal/streams/stream":166,"_process":667,"buffer":170,"inherits":586,"util-deprecate":939}],159:[function(require,module,exports){ (function (process){(function (){ 'use strict'; @@ -27843,7 +30529,7 @@ var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterat module.exports = createReadableStreamAsyncIterator; }).call(this)}).call(this,require('_process')) -},{"./end-of-stream":161,"_process":667}],159:[function(require,module,exports){ +},{"./end-of-stream":162,"_process":667}],160:[function(require,module,exports){ 'use strict'; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } @@ -28054,7 +30740,7 @@ function () { return BufferList; }(); -},{"buffer":169,"util":124}],160:[function(require,module,exports){ +},{"buffer":170,"util":125}],161:[function(require,module,exports){ (function (process){(function (){ 'use strict'; // undocumented cb() API, needed for core, not for public API @@ -28162,7 +30848,7 @@ module.exports = { errorOrDestroy: errorOrDestroy }; }).call(this)}).call(this,require('_process')) -},{"_process":667}],161:[function(require,module,exports){ +},{"_process":667}],162:[function(require,module,exports){ // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; @@ -28267,12 +30953,12 @@ function eos(stream, opts, callback) { } module.exports = eos; -},{"../../../errors":152}],162:[function(require,module,exports){ +},{"../../../errors":153}],163:[function(require,module,exports){ module.exports = function () { throw new Error('Readable.from is not available in the browser') }; -},{}],163:[function(require,module,exports){ +},{}],164:[function(require,module,exports){ // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; @@ -28370,7 +31056,7 @@ function pipeline() { } module.exports = pipeline; -},{"../../../errors":152,"./end-of-stream":161}],164:[function(require,module,exports){ +},{"../../../errors":153,"./end-of-stream":162}],165:[function(require,module,exports){ 'use strict'; var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; @@ -28398,10 +31084,10 @@ function getHighWaterMark(state, options, duplexKey, isDuplex) { module.exports = { getHighWaterMark: getHighWaterMark }; -},{"../../../errors":152}],165:[function(require,module,exports){ +},{"../../../errors":153}],166:[function(require,module,exports){ module.exports = require('events').EventEmitter; -},{"events":539}],166:[function(require,module,exports){ +},{"events":538}],167:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; @@ -28412,7 +31098,7 @@ exports.PassThrough = require('./lib/_stream_passthrough.js'); exports.finished = require('./lib/internal/streams/end-of-stream.js'); exports.pipeline = require('./lib/internal/streams/pipeline.js'); -},{"./lib/_stream_duplex.js":153,"./lib/_stream_passthrough.js":154,"./lib/_stream_readable.js":155,"./lib/_stream_transform.js":156,"./lib/_stream_writable.js":157,"./lib/internal/streams/end-of-stream.js":161,"./lib/internal/streams/pipeline.js":163}],167:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":154,"./lib/_stream_passthrough.js":155,"./lib/_stream_readable.js":156,"./lib/_stream_transform.js":157,"./lib/_stream_writable.js":158,"./lib/internal/streams/end-of-stream.js":162,"./lib/internal/streams/pipeline.js":164}],168:[function(require,module,exports){ /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') @@ -28479,7 +31165,7 @@ SafeBuffer.allocUnsafeSlow = function (size) { return buffer.SlowBuffer(size) } -},{"buffer":169}],168:[function(require,module,exports){ +},{"buffer":170}],169:[function(require,module,exports){ (function (Buffer){(function (){ module.exports = function xor (a, b) { var length = Math.min(a.length, b.length) @@ -28493,7 +31179,7 @@ module.exports = function xor (a, b) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":169}],169:[function(require,module,exports){ +},{"buffer":170}],170:[function(require,module,exports){ (function (Buffer){(function (){ /*! * The buffer module from node.js, for the browser. @@ -30274,7 +32960,7 @@ function numberIsNaN (obj) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":90,"buffer":169,"ieee754":580}],170:[function(require,module,exports){ +},{"base64-js":91,"buffer":170,"ieee754":579}],171:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('get-intrinsic'); @@ -30291,7 +32977,7 @@ module.exports = function callBoundIntrinsic(name, allowMissing) { return intrinsic; }; -},{"./":171,"get-intrinsic":546}],171:[function(require,module,exports){ +},{"./":172,"get-intrinsic":545}],172:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); @@ -30340,7 +33026,7 @@ if ($defineProperty) { module.exports.apply = applyBind; } -},{"function-bind":543,"get-intrinsic":546}],172:[function(require,module,exports){ +},{"function-bind":542,"get-intrinsic":545}],173:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var Transform = require('stream').Transform var StringDecoder = require('string_decoder').StringDecoder @@ -30441,7 +33127,7 @@ CipherBase.prototype._toString = function (value, enc, fin) { module.exports = CipherBase -},{"inherits":587,"safe-buffer":909,"stream":921,"string_decoder":936}],173:[function(require,module,exports){ +},{"inherits":586,"safe-buffer":909,"stream":921,"string_decoder":936}],174:[function(require,module,exports){ (function (Buffer){(function (){ var clone = (function() { 'use strict'; @@ -30702,7 +33388,7 @@ if (typeof module === 'object' && module.exports) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":169}],174:[function(require,module,exports){ +},{"buffer":170}],175:[function(require,module,exports){ require('../modules/es6.symbol'); require('../modules/es6.object.create'); require('../modules/es6.object.define-property'); @@ -30843,74 +33529,74 @@ require('../modules/es6.reflect.set'); require('../modules/es6.reflect.set-prototype-of'); module.exports = require('../modules/_core'); -},{"../modules/_core":223,"../modules/es6.array.copy-within":325,"../modules/es6.array.every":326,"../modules/es6.array.fill":327,"../modules/es6.array.filter":328,"../modules/es6.array.find":330,"../modules/es6.array.find-index":329,"../modules/es6.array.for-each":331,"../modules/es6.array.from":332,"../modules/es6.array.index-of":333,"../modules/es6.array.is-array":334,"../modules/es6.array.iterator":335,"../modules/es6.array.join":336,"../modules/es6.array.last-index-of":337,"../modules/es6.array.map":338,"../modules/es6.array.of":339,"../modules/es6.array.reduce":341,"../modules/es6.array.reduce-right":340,"../modules/es6.array.slice":342,"../modules/es6.array.some":343,"../modules/es6.array.sort":344,"../modules/es6.array.species":345,"../modules/es6.date.now":346,"../modules/es6.date.to-iso-string":347,"../modules/es6.date.to-json":348,"../modules/es6.date.to-primitive":349,"../modules/es6.date.to-string":350,"../modules/es6.function.bind":351,"../modules/es6.function.has-instance":352,"../modules/es6.function.name":353,"../modules/es6.map":354,"../modules/es6.math.acosh":355,"../modules/es6.math.asinh":356,"../modules/es6.math.atanh":357,"../modules/es6.math.cbrt":358,"../modules/es6.math.clz32":359,"../modules/es6.math.cosh":360,"../modules/es6.math.expm1":361,"../modules/es6.math.fround":362,"../modules/es6.math.hypot":363,"../modules/es6.math.imul":364,"../modules/es6.math.log10":365,"../modules/es6.math.log1p":366,"../modules/es6.math.log2":367,"../modules/es6.math.sign":368,"../modules/es6.math.sinh":369,"../modules/es6.math.tanh":370,"../modules/es6.math.trunc":371,"../modules/es6.number.constructor":372,"../modules/es6.number.epsilon":373,"../modules/es6.number.is-finite":374,"../modules/es6.number.is-integer":375,"../modules/es6.number.is-nan":376,"../modules/es6.number.is-safe-integer":377,"../modules/es6.number.max-safe-integer":378,"../modules/es6.number.min-safe-integer":379,"../modules/es6.number.parse-float":380,"../modules/es6.number.parse-int":381,"../modules/es6.number.to-fixed":382,"../modules/es6.number.to-precision":383,"../modules/es6.object.assign":384,"../modules/es6.object.create":385,"../modules/es6.object.define-properties":386,"../modules/es6.object.define-property":387,"../modules/es6.object.freeze":388,"../modules/es6.object.get-own-property-descriptor":389,"../modules/es6.object.get-own-property-names":390,"../modules/es6.object.get-prototype-of":391,"../modules/es6.object.is":395,"../modules/es6.object.is-extensible":392,"../modules/es6.object.is-frozen":393,"../modules/es6.object.is-sealed":394,"../modules/es6.object.keys":396,"../modules/es6.object.prevent-extensions":397,"../modules/es6.object.seal":398,"../modules/es6.object.set-prototype-of":399,"../modules/es6.object.to-string":400,"../modules/es6.parse-float":401,"../modules/es6.parse-int":402,"../modules/es6.promise":403,"../modules/es6.reflect.apply":404,"../modules/es6.reflect.construct":405,"../modules/es6.reflect.define-property":406,"../modules/es6.reflect.delete-property":407,"../modules/es6.reflect.enumerate":408,"../modules/es6.reflect.get":411,"../modules/es6.reflect.get-own-property-descriptor":409,"../modules/es6.reflect.get-prototype-of":410,"../modules/es6.reflect.has":412,"../modules/es6.reflect.is-extensible":413,"../modules/es6.reflect.own-keys":414,"../modules/es6.reflect.prevent-extensions":415,"../modules/es6.reflect.set":417,"../modules/es6.reflect.set-prototype-of":416,"../modules/es6.regexp.constructor":418,"../modules/es6.regexp.exec":419,"../modules/es6.regexp.flags":420,"../modules/es6.regexp.match":421,"../modules/es6.regexp.replace":422,"../modules/es6.regexp.search":423,"../modules/es6.regexp.split":424,"../modules/es6.regexp.to-string":425,"../modules/es6.set":426,"../modules/es6.string.anchor":427,"../modules/es6.string.big":428,"../modules/es6.string.blink":429,"../modules/es6.string.bold":430,"../modules/es6.string.code-point-at":431,"../modules/es6.string.ends-with":432,"../modules/es6.string.fixed":433,"../modules/es6.string.fontcolor":434,"../modules/es6.string.fontsize":435,"../modules/es6.string.from-code-point":436,"../modules/es6.string.includes":437,"../modules/es6.string.italics":438,"../modules/es6.string.iterator":439,"../modules/es6.string.link":440,"../modules/es6.string.raw":441,"../modules/es6.string.repeat":442,"../modules/es6.string.small":443,"../modules/es6.string.starts-with":444,"../modules/es6.string.strike":445,"../modules/es6.string.sub":446,"../modules/es6.string.sup":447,"../modules/es6.string.trim":448,"../modules/es6.symbol":449,"../modules/es6.typed.array-buffer":450,"../modules/es6.typed.data-view":451,"../modules/es6.typed.float32-array":452,"../modules/es6.typed.float64-array":453,"../modules/es6.typed.int16-array":454,"../modules/es6.typed.int32-array":455,"../modules/es6.typed.int8-array":456,"../modules/es6.typed.uint16-array":457,"../modules/es6.typed.uint32-array":458,"../modules/es6.typed.uint8-array":459,"../modules/es6.typed.uint8-clamped-array":460,"../modules/es6.weak-map":461,"../modules/es6.weak-set":462}],175:[function(require,module,exports){ +},{"../modules/_core":224,"../modules/es6.array.copy-within":326,"../modules/es6.array.every":327,"../modules/es6.array.fill":328,"../modules/es6.array.filter":329,"../modules/es6.array.find":331,"../modules/es6.array.find-index":330,"../modules/es6.array.for-each":332,"../modules/es6.array.from":333,"../modules/es6.array.index-of":334,"../modules/es6.array.is-array":335,"../modules/es6.array.iterator":336,"../modules/es6.array.join":337,"../modules/es6.array.last-index-of":338,"../modules/es6.array.map":339,"../modules/es6.array.of":340,"../modules/es6.array.reduce":342,"../modules/es6.array.reduce-right":341,"../modules/es6.array.slice":343,"../modules/es6.array.some":344,"../modules/es6.array.sort":345,"../modules/es6.array.species":346,"../modules/es6.date.now":347,"../modules/es6.date.to-iso-string":348,"../modules/es6.date.to-json":349,"../modules/es6.date.to-primitive":350,"../modules/es6.date.to-string":351,"../modules/es6.function.bind":352,"../modules/es6.function.has-instance":353,"../modules/es6.function.name":354,"../modules/es6.map":355,"../modules/es6.math.acosh":356,"../modules/es6.math.asinh":357,"../modules/es6.math.atanh":358,"../modules/es6.math.cbrt":359,"../modules/es6.math.clz32":360,"../modules/es6.math.cosh":361,"../modules/es6.math.expm1":362,"../modules/es6.math.fround":363,"../modules/es6.math.hypot":364,"../modules/es6.math.imul":365,"../modules/es6.math.log10":366,"../modules/es6.math.log1p":367,"../modules/es6.math.log2":368,"../modules/es6.math.sign":369,"../modules/es6.math.sinh":370,"../modules/es6.math.tanh":371,"../modules/es6.math.trunc":372,"../modules/es6.number.constructor":373,"../modules/es6.number.epsilon":374,"../modules/es6.number.is-finite":375,"../modules/es6.number.is-integer":376,"../modules/es6.number.is-nan":377,"../modules/es6.number.is-safe-integer":378,"../modules/es6.number.max-safe-integer":379,"../modules/es6.number.min-safe-integer":380,"../modules/es6.number.parse-float":381,"../modules/es6.number.parse-int":382,"../modules/es6.number.to-fixed":383,"../modules/es6.number.to-precision":384,"../modules/es6.object.assign":385,"../modules/es6.object.create":386,"../modules/es6.object.define-properties":387,"../modules/es6.object.define-property":388,"../modules/es6.object.freeze":389,"../modules/es6.object.get-own-property-descriptor":390,"../modules/es6.object.get-own-property-names":391,"../modules/es6.object.get-prototype-of":392,"../modules/es6.object.is":396,"../modules/es6.object.is-extensible":393,"../modules/es6.object.is-frozen":394,"../modules/es6.object.is-sealed":395,"../modules/es6.object.keys":397,"../modules/es6.object.prevent-extensions":398,"../modules/es6.object.seal":399,"../modules/es6.object.set-prototype-of":400,"../modules/es6.object.to-string":401,"../modules/es6.parse-float":402,"../modules/es6.parse-int":403,"../modules/es6.promise":404,"../modules/es6.reflect.apply":405,"../modules/es6.reflect.construct":406,"../modules/es6.reflect.define-property":407,"../modules/es6.reflect.delete-property":408,"../modules/es6.reflect.enumerate":409,"../modules/es6.reflect.get":412,"../modules/es6.reflect.get-own-property-descriptor":410,"../modules/es6.reflect.get-prototype-of":411,"../modules/es6.reflect.has":413,"../modules/es6.reflect.is-extensible":414,"../modules/es6.reflect.own-keys":415,"../modules/es6.reflect.prevent-extensions":416,"../modules/es6.reflect.set":418,"../modules/es6.reflect.set-prototype-of":417,"../modules/es6.regexp.constructor":419,"../modules/es6.regexp.exec":420,"../modules/es6.regexp.flags":421,"../modules/es6.regexp.match":422,"../modules/es6.regexp.replace":423,"../modules/es6.regexp.search":424,"../modules/es6.regexp.split":425,"../modules/es6.regexp.to-string":426,"../modules/es6.set":427,"../modules/es6.string.anchor":428,"../modules/es6.string.big":429,"../modules/es6.string.blink":430,"../modules/es6.string.bold":431,"../modules/es6.string.code-point-at":432,"../modules/es6.string.ends-with":433,"../modules/es6.string.fixed":434,"../modules/es6.string.fontcolor":435,"../modules/es6.string.fontsize":436,"../modules/es6.string.from-code-point":437,"../modules/es6.string.includes":438,"../modules/es6.string.italics":439,"../modules/es6.string.iterator":440,"../modules/es6.string.link":441,"../modules/es6.string.raw":442,"../modules/es6.string.repeat":443,"../modules/es6.string.small":444,"../modules/es6.string.starts-with":445,"../modules/es6.string.strike":446,"../modules/es6.string.sub":447,"../modules/es6.string.sup":448,"../modules/es6.string.trim":449,"../modules/es6.symbol":450,"../modules/es6.typed.array-buffer":451,"../modules/es6.typed.data-view":452,"../modules/es6.typed.float32-array":453,"../modules/es6.typed.float64-array":454,"../modules/es6.typed.int16-array":455,"../modules/es6.typed.int32-array":456,"../modules/es6.typed.int8-array":457,"../modules/es6.typed.uint16-array":458,"../modules/es6.typed.uint32-array":459,"../modules/es6.typed.uint8-array":460,"../modules/es6.typed.uint8-clamped-array":461,"../modules/es6.weak-map":462,"../modules/es6.weak-set":463}],176:[function(require,module,exports){ require('../../modules/es7.array.flat-map'); module.exports = require('../../modules/_core').Array.flatMap; -},{"../../modules/_core":223,"../../modules/es7.array.flat-map":463}],176:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.array.flat-map":464}],177:[function(require,module,exports){ require('../../modules/es7.array.includes'); module.exports = require('../../modules/_core').Array.includes; -},{"../../modules/_core":223,"../../modules/es7.array.includes":464}],177:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.array.includes":465}],178:[function(require,module,exports){ require('../../modules/es7.object.entries'); module.exports = require('../../modules/_core').Object.entries; -},{"../../modules/_core":223,"../../modules/es7.object.entries":465}],178:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.object.entries":466}],179:[function(require,module,exports){ require('../../modules/es7.object.get-own-property-descriptors'); module.exports = require('../../modules/_core').Object.getOwnPropertyDescriptors; -},{"../../modules/_core":223,"../../modules/es7.object.get-own-property-descriptors":466}],179:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.object.get-own-property-descriptors":467}],180:[function(require,module,exports){ require('../../modules/es7.object.values'); module.exports = require('../../modules/_core').Object.values; -},{"../../modules/_core":223,"../../modules/es7.object.values":467}],180:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.object.values":468}],181:[function(require,module,exports){ 'use strict'; require('../../modules/es6.promise'); require('../../modules/es7.promise.finally'); module.exports = require('../../modules/_core').Promise['finally']; -},{"../../modules/_core":223,"../../modules/es6.promise":403,"../../modules/es7.promise.finally":468}],181:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es6.promise":404,"../../modules/es7.promise.finally":469}],182:[function(require,module,exports){ require('../../modules/es7.string.pad-end'); module.exports = require('../../modules/_core').String.padEnd; -},{"../../modules/_core":223,"../../modules/es7.string.pad-end":469}],182:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.string.pad-end":470}],183:[function(require,module,exports){ require('../../modules/es7.string.pad-start'); module.exports = require('../../modules/_core').String.padStart; -},{"../../modules/_core":223,"../../modules/es7.string.pad-start":470}],183:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.string.pad-start":471}],184:[function(require,module,exports){ require('../../modules/es7.string.trim-right'); module.exports = require('../../modules/_core').String.trimRight; -},{"../../modules/_core":223,"../../modules/es7.string.trim-right":472}],184:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.string.trim-right":473}],185:[function(require,module,exports){ require('../../modules/es7.string.trim-left'); module.exports = require('../../modules/_core').String.trimLeft; -},{"../../modules/_core":223,"../../modules/es7.string.trim-left":471}],185:[function(require,module,exports){ +},{"../../modules/_core":224,"../../modules/es7.string.trim-left":472}],186:[function(require,module,exports){ require('../../modules/es7.symbol.async-iterator'); module.exports = require('../../modules/_wks-ext').f('asyncIterator'); -},{"../../modules/_wks-ext":322,"../../modules/es7.symbol.async-iterator":473}],186:[function(require,module,exports){ +},{"../../modules/_wks-ext":323,"../../modules/es7.symbol.async-iterator":474}],187:[function(require,module,exports){ require('../modules/es7.global'); module.exports = require('../modules/_core').global; -},{"../modules/_core":189,"../modules/es7.global":203}],187:[function(require,module,exports){ +},{"../modules/_core":190,"../modules/es7.global":204}],188:[function(require,module,exports){ module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; -},{}],188:[function(require,module,exports){ +},{}],189:[function(require,module,exports){ var isObject = require('./_is-object'); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; -},{"./_is-object":199}],189:[function(require,module,exports){ +},{"./_is-object":200}],190:[function(require,module,exports){ var core = module.exports = { version: '2.6.12' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef -},{}],190:[function(require,module,exports){ +},{}],191:[function(require,module,exports){ // optional / simple context binding var aFunction = require('./_a-function'); module.exports = function (fn, that, length) { @@ -30932,13 +33618,13 @@ module.exports = function (fn, that, length) { }; }; -},{"./_a-function":187}],191:[function(require,module,exports){ +},{"./_a-function":188}],192:[function(require,module,exports){ // Thank's IE8 for his funny defineProperty module.exports = !require('./_fails')(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); -},{"./_fails":194}],192:[function(require,module,exports){ +},{"./_fails":195}],193:[function(require,module,exports){ var isObject = require('./_is-object'); var document = require('./_global').document; // typeof document.createElement is 'object' in old IE @@ -30947,7 +33633,7 @@ module.exports = function (it) { return is ? document.createElement(it) : {}; }; -},{"./_global":195,"./_is-object":199}],193:[function(require,module,exports){ +},{"./_global":196,"./_is-object":200}],194:[function(require,module,exports){ var global = require('./_global'); var core = require('./_core'); var ctx = require('./_ctx'); @@ -31011,7 +33697,7 @@ $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; -},{"./_core":189,"./_ctx":190,"./_global":195,"./_has":196,"./_hide":197}],194:[function(require,module,exports){ +},{"./_core":190,"./_ctx":191,"./_global":196,"./_has":197,"./_hide":198}],195:[function(require,module,exports){ module.exports = function (exec) { try { return !!exec(); @@ -31020,7 +33706,7 @@ module.exports = function (exec) { } }; -},{}],195:[function(require,module,exports){ +},{}],196:[function(require,module,exports){ // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self @@ -31028,13 +33714,13 @@ var global = module.exports = typeof window != 'undefined' && window.Math == Mat : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef -},{}],196:[function(require,module,exports){ +},{}],197:[function(require,module,exports){ var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; -},{}],197:[function(require,module,exports){ +},{}],198:[function(require,module,exports){ var dP = require('./_object-dp'); var createDesc = require('./_property-desc'); module.exports = require('./_descriptors') ? function (object, key, value) { @@ -31044,17 +33730,17 @@ module.exports = require('./_descriptors') ? function (object, key, value) { return object; }; -},{"./_descriptors":191,"./_object-dp":200,"./_property-desc":201}],198:[function(require,module,exports){ +},{"./_descriptors":192,"./_object-dp":201,"./_property-desc":202}],199:[function(require,module,exports){ module.exports = !require('./_descriptors') && !require('./_fails')(function () { return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7; }); -},{"./_descriptors":191,"./_dom-create":192,"./_fails":194}],199:[function(require,module,exports){ +},{"./_descriptors":192,"./_dom-create":193,"./_fails":195}],200:[function(require,module,exports){ module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; -},{}],200:[function(require,module,exports){ +},{}],201:[function(require,module,exports){ var anObject = require('./_an-object'); var IE8_DOM_DEFINE = require('./_ie8-dom-define'); var toPrimitive = require('./_to-primitive'); @@ -31072,7 +33758,7 @@ exports.f = require('./_descriptors') ? Object.defineProperty : function defineP return O; }; -},{"./_an-object":188,"./_descriptors":191,"./_ie8-dom-define":198,"./_to-primitive":202}],201:[function(require,module,exports){ +},{"./_an-object":189,"./_descriptors":192,"./_ie8-dom-define":199,"./_to-primitive":203}],202:[function(require,module,exports){ module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), @@ -31082,7 +33768,7 @@ module.exports = function (bitmap, value) { }; }; -},{}],202:[function(require,module,exports){ +},{}],203:[function(require,module,exports){ // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = require('./_is-object'); // instead of the ES6 spec version, we didn't implement @@toPrimitive case @@ -31096,22 +33782,22 @@ module.exports = function (it, S) { throw TypeError("Can't convert object to primitive value"); }; -},{"./_is-object":199}],203:[function(require,module,exports){ +},{"./_is-object":200}],204:[function(require,module,exports){ // https://github.com/tc39/proposal-global var $export = require('./_export'); $export($export.G, { global: require('./_global') }); -},{"./_export":193,"./_global":195}],204:[function(require,module,exports){ -arguments[4][187][0].apply(exports,arguments) -},{"dup":187}],205:[function(require,module,exports){ +},{"./_export":194,"./_global":196}],205:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188}],206:[function(require,module,exports){ var cof = require('./_cof'); module.exports = function (it, msg) { if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); return +it; }; -},{"./_cof":219}],206:[function(require,module,exports){ +},{"./_cof":220}],207:[function(require,module,exports){ // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = require('./_wks')('unscopables'); var ArrayProto = Array.prototype; @@ -31120,7 +33806,7 @@ module.exports = function (key) { ArrayProto[UNSCOPABLES][key] = true; }; -},{"./_hide":243,"./_wks":323}],207:[function(require,module,exports){ +},{"./_hide":244,"./_wks":324}],208:[function(require,module,exports){ 'use strict'; var at = require('./_string-at')(true); @@ -31130,16 +33816,16 @@ module.exports = function (S, index, unicode) { return index + (unicode ? at(S, index).length : 1); }; -},{"./_string-at":300}],208:[function(require,module,exports){ +},{"./_string-at":301}],209:[function(require,module,exports){ module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { throw TypeError(name + ': incorrect invocation!'); } return it; }; -},{}],209:[function(require,module,exports){ -arguments[4][188][0].apply(exports,arguments) -},{"./_is-object":252,"dup":188}],210:[function(require,module,exports){ +},{}],210:[function(require,module,exports){ +arguments[4][189][0].apply(exports,arguments) +},{"./_is-object":253,"dup":189}],211:[function(require,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) 'use strict'; var toObject = require('./_to-object'); @@ -31167,7 +33853,7 @@ module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* } return O; }; -},{"./_to-absolute-index":308,"./_to-length":312,"./_to-object":313}],211:[function(require,module,exports){ +},{"./_to-absolute-index":309,"./_to-length":313,"./_to-object":314}],212:[function(require,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) 'use strict'; var toObject = require('./_to-object'); @@ -31184,7 +33870,7 @@ module.exports = function fill(value /* , start = 0, end = @length */) { return O; }; -},{"./_to-absolute-index":308,"./_to-length":312,"./_to-object":313}],212:[function(require,module,exports){ +},{"./_to-absolute-index":309,"./_to-length":313,"./_to-object":314}],213:[function(require,module,exports){ // false -> Array#indexOf // true -> Array#includes var toIObject = require('./_to-iobject'); @@ -31209,7 +33895,7 @@ module.exports = function (IS_INCLUDES) { }; }; -},{"./_to-absolute-index":308,"./_to-iobject":311,"./_to-length":312}],213:[function(require,module,exports){ +},{"./_to-absolute-index":309,"./_to-iobject":312,"./_to-length":313}],214:[function(require,module,exports){ // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter @@ -31255,7 +33941,7 @@ module.exports = function (TYPE, $create) { }; }; -},{"./_array-species-create":216,"./_ctx":225,"./_iobject":248,"./_to-length":312,"./_to-object":313}],214:[function(require,module,exports){ +},{"./_array-species-create":217,"./_ctx":226,"./_iobject":249,"./_to-length":313,"./_to-object":314}],215:[function(require,module,exports){ var aFunction = require('./_a-function'); var toObject = require('./_to-object'); var IObject = require('./_iobject'); @@ -31285,7 +33971,7 @@ module.exports = function (that, callbackfn, aLen, memo, isRight) { return memo; }; -},{"./_a-function":204,"./_iobject":248,"./_to-length":312,"./_to-object":313}],215:[function(require,module,exports){ +},{"./_a-function":205,"./_iobject":249,"./_to-length":313,"./_to-object":314}],216:[function(require,module,exports){ var isObject = require('./_is-object'); var isArray = require('./_is-array'); var SPECIES = require('./_wks')('species'); @@ -31303,7 +33989,7 @@ module.exports = function (original) { } return C === undefined ? Array : C; }; -},{"./_is-array":250,"./_is-object":252,"./_wks":323}],216:[function(require,module,exports){ +},{"./_is-array":251,"./_is-object":253,"./_wks":324}],217:[function(require,module,exports){ // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = require('./_array-species-constructor'); @@ -31311,7 +33997,7 @@ module.exports = function (original, length) { return new (speciesConstructor(original))(length); }; -},{"./_array-species-constructor":215}],217:[function(require,module,exports){ +},{"./_array-species-constructor":216}],218:[function(require,module,exports){ 'use strict'; var aFunction = require('./_a-function'); var isObject = require('./_is-object'); @@ -31338,7 +34024,7 @@ module.exports = Function.bind || function bind(that /* , ...args */) { return bound; }; -},{"./_a-function":204,"./_invoke":247,"./_is-object":252}],218:[function(require,module,exports){ +},{"./_a-function":205,"./_invoke":248,"./_is-object":253}],219:[function(require,module,exports){ // getting tag from 19.1.3.6 Object.prototype.toString() var cof = require('./_cof'); var TAG = require('./_wks')('toStringTag'); @@ -31363,14 +34049,14 @@ module.exports = function (it) { : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; -},{"./_cof":219,"./_wks":323}],219:[function(require,module,exports){ +},{"./_cof":220,"./_wks":324}],220:[function(require,module,exports){ var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; -},{}],220:[function(require,module,exports){ +},{}],221:[function(require,module,exports){ 'use strict'; var dP = require('./_object-dp').f; var create = require('./_object-create'); @@ -31516,7 +34202,7 @@ module.exports = { } }; -},{"./_an-instance":208,"./_ctx":225,"./_descriptors":229,"./_for-of":239,"./_iter-define":256,"./_iter-step":258,"./_meta":265,"./_object-create":269,"./_object-dp":270,"./_redefine-all":288,"./_set-species":294,"./_validate-collection":320}],221:[function(require,module,exports){ +},{"./_an-instance":209,"./_ctx":226,"./_descriptors":230,"./_for-of":240,"./_iter-define":257,"./_iter-step":259,"./_meta":266,"./_object-create":270,"./_object-dp":271,"./_redefine-all":289,"./_set-species":295,"./_validate-collection":321}],222:[function(require,module,exports){ 'use strict'; var redefineAll = require('./_redefine-all'); var getWeak = require('./_meta').getWeak; @@ -31603,7 +34289,7 @@ module.exports = { ufstore: uncaughtFrozenStore }; -},{"./_an-instance":208,"./_an-object":209,"./_array-methods":213,"./_for-of":239,"./_has":242,"./_is-object":252,"./_meta":265,"./_redefine-all":288,"./_validate-collection":320}],222:[function(require,module,exports){ +},{"./_an-instance":209,"./_an-object":210,"./_array-methods":214,"./_for-of":240,"./_has":243,"./_is-object":253,"./_meta":266,"./_redefine-all":289,"./_validate-collection":321}],223:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var $export = require('./_export'); @@ -31690,9 +34376,9 @@ module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { return C; }; -},{"./_an-instance":208,"./_export":233,"./_fails":235,"./_for-of":239,"./_global":241,"./_inherit-if-required":246,"./_is-object":252,"./_iter-detect":257,"./_meta":265,"./_redefine":289,"./_redefine-all":288,"./_set-to-string-tag":295}],223:[function(require,module,exports){ -arguments[4][189][0].apply(exports,arguments) -},{"dup":189}],224:[function(require,module,exports){ +},{"./_an-instance":209,"./_export":234,"./_fails":236,"./_for-of":240,"./_global":242,"./_inherit-if-required":247,"./_is-object":253,"./_iter-detect":258,"./_meta":266,"./_redefine":290,"./_redefine-all":289,"./_set-to-string-tag":296}],224:[function(require,module,exports){ +arguments[4][190][0].apply(exports,arguments) +},{"dup":190}],225:[function(require,module,exports){ 'use strict'; var $defineProperty = require('./_object-dp'); var createDesc = require('./_property-desc'); @@ -31702,9 +34388,9 @@ module.exports = function (object, index, value) { else object[index] = value; }; -},{"./_object-dp":270,"./_property-desc":287}],225:[function(require,module,exports){ -arguments[4][190][0].apply(exports,arguments) -},{"./_a-function":204,"dup":190}],226:[function(require,module,exports){ +},{"./_object-dp":271,"./_property-desc":288}],226:[function(require,module,exports){ +arguments[4][191][0].apply(exports,arguments) +},{"./_a-function":205,"dup":191}],227:[function(require,module,exports){ 'use strict'; // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() var fails = require('./_fails'); @@ -31732,7 +34418,7 @@ module.exports = (fails(function () { ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; } : $toISOString; -},{"./_fails":235}],227:[function(require,module,exports){ +},{"./_fails":236}],228:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); var toPrimitive = require('./_to-primitive'); @@ -31743,24 +34429,24 @@ module.exports = function (hint) { return toPrimitive(anObject(this), hint != NUMBER); }; -},{"./_an-object":209,"./_to-primitive":314}],228:[function(require,module,exports){ +},{"./_an-object":210,"./_to-primitive":315}],229:[function(require,module,exports){ // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; -},{}],229:[function(require,module,exports){ -arguments[4][191][0].apply(exports,arguments) -},{"./_fails":235,"dup":191}],230:[function(require,module,exports){ +},{}],230:[function(require,module,exports){ arguments[4][192][0].apply(exports,arguments) -},{"./_global":241,"./_is-object":252,"dup":192}],231:[function(require,module,exports){ +},{"./_fails":236,"dup":192}],231:[function(require,module,exports){ +arguments[4][193][0].apply(exports,arguments) +},{"./_global":242,"./_is-object":253,"dup":193}],232:[function(require,module,exports){ // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); -},{}],232:[function(require,module,exports){ +},{}],233:[function(require,module,exports){ // all enumerable object keys, includes symbols var getKeys = require('./_object-keys'); var gOPS = require('./_object-gops'); @@ -31777,7 +34463,7 @@ module.exports = function (it) { } return result; }; -},{"./_object-gops":275,"./_object-keys":278,"./_object-pie":279}],233:[function(require,module,exports){ +},{"./_object-gops":276,"./_object-keys":279,"./_object-pie":280}],234:[function(require,module,exports){ var global = require('./_global'); var core = require('./_core'); var hide = require('./_hide'); @@ -31822,7 +34508,7 @@ $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; -},{"./_core":223,"./_ctx":225,"./_global":241,"./_hide":243,"./_redefine":289}],234:[function(require,module,exports){ +},{"./_core":224,"./_ctx":226,"./_global":242,"./_hide":244,"./_redefine":290}],235:[function(require,module,exports){ var MATCH = require('./_wks')('match'); module.exports = function (KEY) { var re = /./; @@ -31836,9 +34522,9 @@ module.exports = function (KEY) { } return true; }; -},{"./_wks":323}],235:[function(require,module,exports){ -arguments[4][194][0].apply(exports,arguments) -},{"dup":194}],236:[function(require,module,exports){ +},{"./_wks":324}],236:[function(require,module,exports){ +arguments[4][195][0].apply(exports,arguments) +},{"dup":195}],237:[function(require,module,exports){ 'use strict'; require('./es6.regexp.exec'); var redefine = require('./_redefine'); @@ -31936,7 +34622,7 @@ module.exports = function (KEY, length, exec) { } }; -},{"./_defined":228,"./_fails":235,"./_hide":243,"./_redefine":289,"./_regexp-exec":291,"./_wks":323,"./es6.regexp.exec":419}],237:[function(require,module,exports){ +},{"./_defined":229,"./_fails":236,"./_hide":244,"./_redefine":290,"./_regexp-exec":292,"./_wks":324,"./es6.regexp.exec":420}],238:[function(require,module,exports){ 'use strict'; // 21.2.5.3 get RegExp.prototype.flags var anObject = require('./_an-object'); @@ -31951,7 +34637,7 @@ module.exports = function () { return result; }; -},{"./_an-object":209}],238:[function(require,module,exports){ +},{"./_an-object":210}],239:[function(require,module,exports){ 'use strict'; // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray var isArray = require('./_is-array'); @@ -31992,7 +34678,7 @@ function flattenIntoArray(target, original, source, sourceLen, start, depth, map module.exports = flattenIntoArray; -},{"./_ctx":225,"./_is-array":250,"./_is-object":252,"./_to-length":312,"./_wks":323}],239:[function(require,module,exports){ +},{"./_ctx":226,"./_is-array":251,"./_is-object":253,"./_to-length":313,"./_wks":324}],240:[function(require,module,exports){ var ctx = require('./_ctx'); var call = require('./_iter-call'); var isArrayIter = require('./_is-array-iter'); @@ -32019,22 +34705,22 @@ var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) exports.BREAK = BREAK; exports.RETURN = RETURN; -},{"./_an-object":209,"./_ctx":225,"./_is-array-iter":249,"./_iter-call":254,"./_to-length":312,"./core.get-iterator-method":324}],240:[function(require,module,exports){ +},{"./_an-object":210,"./_ctx":226,"./_is-array-iter":250,"./_iter-call":255,"./_to-length":313,"./core.get-iterator-method":325}],241:[function(require,module,exports){ module.exports = require('./_shared')('native-function-to-string', Function.toString); -},{"./_shared":297}],241:[function(require,module,exports){ -arguments[4][195][0].apply(exports,arguments) -},{"dup":195}],242:[function(require,module,exports){ +},{"./_shared":298}],242:[function(require,module,exports){ arguments[4][196][0].apply(exports,arguments) },{"dup":196}],243:[function(require,module,exports){ arguments[4][197][0].apply(exports,arguments) -},{"./_descriptors":229,"./_object-dp":270,"./_property-desc":287,"dup":197}],244:[function(require,module,exports){ +},{"dup":197}],244:[function(require,module,exports){ +arguments[4][198][0].apply(exports,arguments) +},{"./_descriptors":230,"./_object-dp":271,"./_property-desc":288,"dup":198}],245:[function(require,module,exports){ var document = require('./_global').document; module.exports = document && document.documentElement; -},{"./_global":241}],245:[function(require,module,exports){ -arguments[4][198][0].apply(exports,arguments) -},{"./_descriptors":229,"./_dom-create":230,"./_fails":235,"dup":198}],246:[function(require,module,exports){ +},{"./_global":242}],246:[function(require,module,exports){ +arguments[4][199][0].apply(exports,arguments) +},{"./_descriptors":230,"./_dom-create":231,"./_fails":236,"dup":199}],247:[function(require,module,exports){ var isObject = require('./_is-object'); var setPrototypeOf = require('./_set-proto').set; module.exports = function (that, target, C) { @@ -32045,7 +34731,7 @@ module.exports = function (that, target, C) { } return that; }; -},{"./_is-object":252,"./_set-proto":293}],247:[function(require,module,exports){ +},{"./_is-object":253,"./_set-proto":294}],248:[function(require,module,exports){ // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function (fn, args, that) { var un = that === undefined; @@ -32063,7 +34749,7 @@ module.exports = function (fn, args, that) { } return fn.apply(that, args); }; -},{}],248:[function(require,module,exports){ +},{}],249:[function(require,module,exports){ // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = require('./_cof'); // eslint-disable-next-line no-prototype-builtins @@ -32071,7 +34757,7 @@ module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; -},{"./_cof":219}],249:[function(require,module,exports){ +},{"./_cof":220}],250:[function(require,module,exports){ // check on default Array iterator var Iterators = require('./_iterators'); var ITERATOR = require('./_wks')('iterator'); @@ -32081,14 +34767,14 @@ module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; -},{"./_iterators":259,"./_wks":323}],250:[function(require,module,exports){ +},{"./_iterators":260,"./_wks":324}],251:[function(require,module,exports){ // 7.2.2 IsArray(argument) var cof = require('./_cof'); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; -},{"./_cof":219}],251:[function(require,module,exports){ +},{"./_cof":220}],252:[function(require,module,exports){ // 20.1.2.3 Number.isInteger(number) var isObject = require('./_is-object'); var floor = Math.floor; @@ -32096,9 +34782,9 @@ module.exports = function isInteger(it) { return !isObject(it) && isFinite(it) && floor(it) === it; }; -},{"./_is-object":252}],252:[function(require,module,exports){ -arguments[4][199][0].apply(exports,arguments) -},{"dup":199}],253:[function(require,module,exports){ +},{"./_is-object":253}],253:[function(require,module,exports){ +arguments[4][200][0].apply(exports,arguments) +},{"dup":200}],254:[function(require,module,exports){ // 7.2.8 IsRegExp(argument) var isObject = require('./_is-object'); var cof = require('./_cof'); @@ -32108,7 +34794,7 @@ module.exports = function (it) { return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; -},{"./_cof":219,"./_is-object":252,"./_wks":323}],254:[function(require,module,exports){ +},{"./_cof":220,"./_is-object":253,"./_wks":324}],255:[function(require,module,exports){ // call something on iterator step with safe closing on error var anObject = require('./_an-object'); module.exports = function (iterator, fn, value, entries) { @@ -32122,7 +34808,7 @@ module.exports = function (iterator, fn, value, entries) { } }; -},{"./_an-object":209}],255:[function(require,module,exports){ +},{"./_an-object":210}],256:[function(require,module,exports){ 'use strict'; var create = require('./_object-create'); var descriptor = require('./_property-desc'); @@ -32137,7 +34823,7 @@ module.exports = function (Constructor, NAME, next) { setToStringTag(Constructor, NAME + ' Iterator'); }; -},{"./_hide":243,"./_object-create":269,"./_property-desc":287,"./_set-to-string-tag":295,"./_wks":323}],256:[function(require,module,exports){ +},{"./_hide":244,"./_object-create":270,"./_property-desc":288,"./_set-to-string-tag":296,"./_wks":324}],257:[function(require,module,exports){ 'use strict'; var LIBRARY = require('./_library'); var $export = require('./_export'); @@ -32208,7 +34894,7 @@ module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE return methods; }; -},{"./_export":233,"./_hide":243,"./_iter-create":255,"./_iterators":259,"./_library":260,"./_object-gpo":276,"./_redefine":289,"./_set-to-string-tag":295,"./_wks":323}],257:[function(require,module,exports){ +},{"./_export":234,"./_hide":244,"./_iter-create":256,"./_iterators":260,"./_library":261,"./_object-gpo":277,"./_redefine":290,"./_set-to-string-tag":296,"./_wks":324}],258:[function(require,module,exports){ var ITERATOR = require('./_wks')('iterator'); var SAFE_CLOSING = false; @@ -32232,18 +34918,18 @@ module.exports = function (exec, skipClosing) { return safe; }; -},{"./_wks":323}],258:[function(require,module,exports){ +},{"./_wks":324}],259:[function(require,module,exports){ module.exports = function (done, value) { return { value: value, done: !!done }; }; -},{}],259:[function(require,module,exports){ +},{}],260:[function(require,module,exports){ module.exports = {}; -},{}],260:[function(require,module,exports){ +},{}],261:[function(require,module,exports){ module.exports = false; -},{}],261:[function(require,module,exports){ +},{}],262:[function(require,module,exports){ // 20.2.2.14 Math.expm1(x) var $expm1 = Math.expm1; module.exports = (!$expm1 @@ -32255,7 +34941,7 @@ module.exports = (!$expm1 return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; } : $expm1; -},{}],262:[function(require,module,exports){ +},{}],263:[function(require,module,exports){ // 20.2.2.16 Math.fround(x) var sign = require('./_math-sign'); var pow = Math.pow; @@ -32280,20 +34966,20 @@ module.exports = Math.fround || function fround(x) { return $sign * result; }; -},{"./_math-sign":264}],263:[function(require,module,exports){ +},{"./_math-sign":265}],264:[function(require,module,exports){ // 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x) { return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); }; -},{}],264:[function(require,module,exports){ +},{}],265:[function(require,module,exports){ // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x) { // eslint-disable-next-line no-self-compare return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; -},{}],265:[function(require,module,exports){ +},{}],266:[function(require,module,exports){ var META = require('./_uid')('meta'); var isObject = require('./_is-object'); var has = require('./_has'); @@ -32348,7 +35034,7 @@ var meta = module.exports = { onFreeze: onFreeze }; -},{"./_fails":235,"./_has":242,"./_is-object":252,"./_object-dp":270,"./_uid":318}],266:[function(require,module,exports){ +},{"./_fails":236,"./_has":243,"./_is-object":253,"./_object-dp":271,"./_uid":319}],267:[function(require,module,exports){ var global = require('./_global'); var macrotask = require('./_task').set; var Observer = global.MutationObserver || global.WebKitMutationObserver; @@ -32419,7 +35105,7 @@ module.exports = function () { }; }; -},{"./_cof":219,"./_global":241,"./_task":307}],267:[function(require,module,exports){ +},{"./_cof":220,"./_global":242,"./_task":308}],268:[function(require,module,exports){ 'use strict'; // 25.4.1.5 NewPromiseCapability(C) var aFunction = require('./_a-function'); @@ -32439,7 +35125,7 @@ module.exports.f = function (C) { return new PromiseCapability(C); }; -},{"./_a-function":204}],268:[function(require,module,exports){ +},{"./_a-function":205}],269:[function(require,module,exports){ 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var DESCRIPTORS = require('./_descriptors'); @@ -32479,7 +35165,7 @@ module.exports = !$assign || require('./_fails')(function () { } return T; } : $assign; -},{"./_descriptors":229,"./_fails":235,"./_iobject":248,"./_object-gops":275,"./_object-keys":278,"./_object-pie":279,"./_to-object":313}],269:[function(require,module,exports){ +},{"./_descriptors":230,"./_fails":236,"./_iobject":249,"./_object-gops":276,"./_object-keys":279,"./_object-pie":280,"./_to-object":314}],270:[function(require,module,exports){ // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = require('./_an-object'); var dPs = require('./_object-dps'); @@ -32522,9 +35208,9 @@ module.exports = Object.create || function create(O, Properties) { return Properties === undefined ? result : dPs(result, Properties); }; -},{"./_an-object":209,"./_dom-create":230,"./_enum-bug-keys":231,"./_html":244,"./_object-dps":271,"./_shared-key":296}],270:[function(require,module,exports){ -arguments[4][200][0].apply(exports,arguments) -},{"./_an-object":209,"./_descriptors":229,"./_ie8-dom-define":245,"./_to-primitive":314,"dup":200}],271:[function(require,module,exports){ +},{"./_an-object":210,"./_dom-create":231,"./_enum-bug-keys":232,"./_html":245,"./_object-dps":272,"./_shared-key":297}],271:[function(require,module,exports){ +arguments[4][201][0].apply(exports,arguments) +},{"./_an-object":210,"./_descriptors":230,"./_ie8-dom-define":246,"./_to-primitive":315,"dup":201}],272:[function(require,module,exports){ var dP = require('./_object-dp'); var anObject = require('./_an-object'); var getKeys = require('./_object-keys'); @@ -32539,7 +35225,7 @@ module.exports = require('./_descriptors') ? Object.defineProperties : function return O; }; -},{"./_an-object":209,"./_descriptors":229,"./_object-dp":270,"./_object-keys":278}],272:[function(require,module,exports){ +},{"./_an-object":210,"./_descriptors":230,"./_object-dp":271,"./_object-keys":279}],273:[function(require,module,exports){ var pIE = require('./_object-pie'); var createDesc = require('./_property-desc'); var toIObject = require('./_to-iobject'); @@ -32557,7 +35243,7 @@ exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; -},{"./_descriptors":229,"./_has":242,"./_ie8-dom-define":245,"./_object-pie":279,"./_property-desc":287,"./_to-iobject":311,"./_to-primitive":314}],273:[function(require,module,exports){ +},{"./_descriptors":230,"./_has":243,"./_ie8-dom-define":246,"./_object-pie":280,"./_property-desc":288,"./_to-iobject":312,"./_to-primitive":315}],274:[function(require,module,exports){ // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = require('./_to-iobject'); var gOPN = require('./_object-gopn').f; @@ -32578,7 +35264,7 @@ module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; -},{"./_object-gopn":274,"./_to-iobject":311}],274:[function(require,module,exports){ +},{"./_object-gopn":275,"./_to-iobject":312}],275:[function(require,module,exports){ // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = require('./_object-keys-internal'); var hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype'); @@ -32587,10 +35273,10 @@ exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; -},{"./_enum-bug-keys":231,"./_object-keys-internal":277}],275:[function(require,module,exports){ +},{"./_enum-bug-keys":232,"./_object-keys-internal":278}],276:[function(require,module,exports){ exports.f = Object.getOwnPropertySymbols; -},{}],276:[function(require,module,exports){ +},{}],277:[function(require,module,exports){ // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = require('./_has'); var toObject = require('./_to-object'); @@ -32605,7 +35291,7 @@ module.exports = Object.getPrototypeOf || function (O) { } return O instanceof Object ? ObjectProto : null; }; -},{"./_has":242,"./_shared-key":296,"./_to-object":313}],277:[function(require,module,exports){ +},{"./_has":243,"./_shared-key":297,"./_to-object":314}],278:[function(require,module,exports){ var has = require('./_has'); var toIObject = require('./_to-iobject'); var arrayIndexOf = require('./_array-includes')(false); @@ -32624,7 +35310,7 @@ module.exports = function (object, names) { return result; }; -},{"./_array-includes":212,"./_has":242,"./_shared-key":296,"./_to-iobject":311}],278:[function(require,module,exports){ +},{"./_array-includes":213,"./_has":243,"./_shared-key":297,"./_to-iobject":312}],279:[function(require,module,exports){ // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = require('./_object-keys-internal'); var enumBugKeys = require('./_enum-bug-keys'); @@ -32633,10 +35319,10 @@ module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; -},{"./_enum-bug-keys":231,"./_object-keys-internal":277}],279:[function(require,module,exports){ +},{"./_enum-bug-keys":232,"./_object-keys-internal":278}],280:[function(require,module,exports){ exports.f = {}.propertyIsEnumerable; -},{}],280:[function(require,module,exports){ +},{}],281:[function(require,module,exports){ // most Object methods by ES6 should accept primitives var $export = require('./_export'); var core = require('./_core'); @@ -32648,7 +35334,7 @@ module.exports = function (KEY, exec) { $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); }; -},{"./_core":223,"./_export":233,"./_fails":235}],281:[function(require,module,exports){ +},{"./_core":224,"./_export":234,"./_fails":236}],282:[function(require,module,exports){ var DESCRIPTORS = require('./_descriptors'); var getKeys = require('./_object-keys'); var toIObject = require('./_to-iobject'); @@ -32671,7 +35357,7 @@ module.exports = function (isEntries) { }; }; -},{"./_descriptors":229,"./_object-keys":278,"./_object-pie":279,"./_to-iobject":311}],282:[function(require,module,exports){ +},{"./_descriptors":230,"./_object-keys":279,"./_object-pie":280,"./_to-iobject":312}],283:[function(require,module,exports){ // all object keys, includes non-enumerable and symbols var gOPN = require('./_object-gopn'); var gOPS = require('./_object-gops'); @@ -32683,7 +35369,7 @@ module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { return getSymbols ? keys.concat(getSymbols(it)) : keys; }; -},{"./_an-object":209,"./_global":241,"./_object-gopn":274,"./_object-gops":275}],283:[function(require,module,exports){ +},{"./_an-object":210,"./_global":242,"./_object-gopn":275,"./_object-gops":276}],284:[function(require,module,exports){ var $parseFloat = require('./_global').parseFloat; var $trim = require('./_string-trim').trim; @@ -32693,7 +35379,7 @@ module.exports = 1 / $parseFloat(require('./_string-ws') + '-0') !== -Infinity ? return result === 0 && string.charAt(0) == '-' ? -0 : result; } : $parseFloat; -},{"./_global":241,"./_string-trim":305,"./_string-ws":306}],284:[function(require,module,exports){ +},{"./_global":242,"./_string-trim":306,"./_string-ws":307}],285:[function(require,module,exports){ var $parseInt = require('./_global').parseInt; var $trim = require('./_string-trim').trim; var ws = require('./_string-ws'); @@ -32704,7 +35390,7 @@ module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? f return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); } : $parseInt; -},{"./_global":241,"./_string-trim":305,"./_string-ws":306}],285:[function(require,module,exports){ +},{"./_global":242,"./_string-trim":306,"./_string-ws":307}],286:[function(require,module,exports){ module.exports = function (exec) { try { return { e: false, v: exec() }; @@ -32713,7 +35399,7 @@ module.exports = function (exec) { } }; -},{}],286:[function(require,module,exports){ +},{}],287:[function(require,module,exports){ var anObject = require('./_an-object'); var isObject = require('./_is-object'); var newPromiseCapability = require('./_new-promise-capability'); @@ -32727,16 +35413,16 @@ module.exports = function (C, x) { return promiseCapability.promise; }; -},{"./_an-object":209,"./_is-object":252,"./_new-promise-capability":267}],287:[function(require,module,exports){ -arguments[4][201][0].apply(exports,arguments) -},{"dup":201}],288:[function(require,module,exports){ +},{"./_an-object":210,"./_is-object":253,"./_new-promise-capability":268}],288:[function(require,module,exports){ +arguments[4][202][0].apply(exports,arguments) +},{"dup":202}],289:[function(require,module,exports){ var redefine = require('./_redefine'); module.exports = function (target, src, safe) { for (var key in src) redefine(target, key, src[key], safe); return target; }; -},{"./_redefine":289}],289:[function(require,module,exports){ +},{"./_redefine":290}],290:[function(require,module,exports){ var global = require('./_global'); var hide = require('./_hide'); var has = require('./_has'); @@ -32769,7 +35455,7 @@ require('./_core').inspectSource = function (it) { return typeof this == 'function' && this[SRC] || $toString.call(this); }); -},{"./_core":223,"./_function-to-string":240,"./_global":241,"./_has":242,"./_hide":243,"./_uid":318}],290:[function(require,module,exports){ +},{"./_core":224,"./_function-to-string":241,"./_global":242,"./_has":243,"./_hide":244,"./_uid":319}],291:[function(require,module,exports){ 'use strict'; var classof = require('./_classof'); @@ -32792,7 +35478,7 @@ module.exports = function (R, S) { return builtinExec.call(R, S); }; -},{"./_classof":218}],291:[function(require,module,exports){ +},{"./_classof":219}],292:[function(require,module,exports){ 'use strict'; var regexpFlags = require('./_flags'); @@ -32852,14 +35538,14 @@ if (PATCH) { module.exports = patchedExec; -},{"./_flags":237}],292:[function(require,module,exports){ +},{"./_flags":238}],293:[function(require,module,exports){ // 7.2.9 SameValue(x, y) module.exports = Object.is || function is(x, y) { // eslint-disable-next-line no-self-compare return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; -},{}],293:[function(require,module,exports){ +},{}],294:[function(require,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = require('./_is-object'); @@ -32886,7 +35572,7 @@ module.exports = { check: check }; -},{"./_an-object":209,"./_ctx":225,"./_is-object":252,"./_object-gopd":272}],294:[function(require,module,exports){ +},{"./_an-object":210,"./_ctx":226,"./_is-object":253,"./_object-gopd":273}],295:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var dP = require('./_object-dp'); @@ -32901,7 +35587,7 @@ module.exports = function (KEY) { }); }; -},{"./_descriptors":229,"./_global":241,"./_object-dp":270,"./_wks":323}],295:[function(require,module,exports){ +},{"./_descriptors":230,"./_global":242,"./_object-dp":271,"./_wks":324}],296:[function(require,module,exports){ var def = require('./_object-dp').f; var has = require('./_has'); var TAG = require('./_wks')('toStringTag'); @@ -32910,14 +35596,14 @@ module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; -},{"./_has":242,"./_object-dp":270,"./_wks":323}],296:[function(require,module,exports){ +},{"./_has":243,"./_object-dp":271,"./_wks":324}],297:[function(require,module,exports){ var shared = require('./_shared')('keys'); var uid = require('./_uid'); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; -},{"./_shared":297,"./_uid":318}],297:[function(require,module,exports){ +},{"./_shared":298,"./_uid":319}],298:[function(require,module,exports){ var core = require('./_core'); var global = require('./_global'); var SHARED = '__core-js_shared__'; @@ -32931,7 +35617,7 @@ var store = global[SHARED] || (global[SHARED] = {}); copyright: '© 2020 Denis Pushkarev (zloirock.ru)' }); -},{"./_core":223,"./_global":241,"./_library":260}],298:[function(require,module,exports){ +},{"./_core":224,"./_global":242,"./_library":261}],299:[function(require,module,exports){ // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = require('./_an-object'); var aFunction = require('./_a-function'); @@ -32942,7 +35628,7 @@ module.exports = function (O, D) { return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; -},{"./_a-function":204,"./_an-object":209,"./_wks":323}],299:[function(require,module,exports){ +},{"./_a-function":205,"./_an-object":210,"./_wks":324}],300:[function(require,module,exports){ 'use strict'; var fails = require('./_fails'); @@ -32953,7 +35639,7 @@ module.exports = function (method, arg) { }); }; -},{"./_fails":235}],300:[function(require,module,exports){ +},{"./_fails":236}],301:[function(require,module,exports){ var toInteger = require('./_to-integer'); var defined = require('./_defined'); // true -> String#at @@ -32972,7 +35658,7 @@ module.exports = function (TO_STRING) { }; }; -},{"./_defined":228,"./_to-integer":310}],301:[function(require,module,exports){ +},{"./_defined":229,"./_to-integer":311}],302:[function(require,module,exports){ // helper for String#{startsWith, endsWith, includes} var isRegExp = require('./_is-regexp'); var defined = require('./_defined'); @@ -32982,7 +35668,7 @@ module.exports = function (that, searchString, NAME) { return String(defined(that)); }; -},{"./_defined":228,"./_is-regexp":253}],302:[function(require,module,exports){ +},{"./_defined":229,"./_is-regexp":254}],303:[function(require,module,exports){ var $export = require('./_export'); var fails = require('./_fails'); var defined = require('./_defined'); @@ -33003,7 +35689,7 @@ module.exports = function (NAME, exec) { }), 'String', O); }; -},{"./_defined":228,"./_export":233,"./_fails":235}],303:[function(require,module,exports){ +},{"./_defined":229,"./_export":234,"./_fails":236}],304:[function(require,module,exports){ // https://github.com/tc39/proposal-string-pad-start-end var toLength = require('./_to-length'); var repeat = require('./_string-repeat'); @@ -33021,7 +35707,7 @@ module.exports = function (that, maxLength, fillString, left) { return left ? stringFiller + S : S + stringFiller; }; -},{"./_defined":228,"./_string-repeat":304,"./_to-length":312}],304:[function(require,module,exports){ +},{"./_defined":229,"./_string-repeat":305,"./_to-length":313}],305:[function(require,module,exports){ 'use strict'; var toInteger = require('./_to-integer'); var defined = require('./_defined'); @@ -33035,7 +35721,7 @@ module.exports = function repeat(count) { return res; }; -},{"./_defined":228,"./_to-integer":310}],305:[function(require,module,exports){ +},{"./_defined":229,"./_to-integer":311}],306:[function(require,module,exports){ var $export = require('./_export'); var defined = require('./_defined'); var fails = require('./_fails'); @@ -33067,11 +35753,11 @@ var trim = exporter.trim = function (string, TYPE) { module.exports = exporter; -},{"./_defined":228,"./_export":233,"./_fails":235,"./_string-ws":306}],306:[function(require,module,exports){ +},{"./_defined":229,"./_export":234,"./_fails":236,"./_string-ws":307}],307:[function(require,module,exports){ module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; -},{}],307:[function(require,module,exports){ +},{}],308:[function(require,module,exports){ var ctx = require('./_ctx'); var invoke = require('./_invoke'); var html = require('./_html'); @@ -33157,7 +35843,7 @@ module.exports = { clear: clearTask }; -},{"./_cof":219,"./_ctx":225,"./_dom-create":230,"./_global":241,"./_html":244,"./_invoke":247}],308:[function(require,module,exports){ +},{"./_cof":220,"./_ctx":226,"./_dom-create":231,"./_global":242,"./_html":245,"./_invoke":248}],309:[function(require,module,exports){ var toInteger = require('./_to-integer'); var max = Math.max; var min = Math.min; @@ -33166,7 +35852,7 @@ module.exports = function (index, length) { return index < 0 ? max(index + length, 0) : min(index, length); }; -},{"./_to-integer":310}],309:[function(require,module,exports){ +},{"./_to-integer":311}],310:[function(require,module,exports){ // https://tc39.github.io/ecma262/#sec-toindex var toInteger = require('./_to-integer'); var toLength = require('./_to-length'); @@ -33178,7 +35864,7 @@ module.exports = function (it) { return length; }; -},{"./_to-integer":310,"./_to-length":312}],310:[function(require,module,exports){ +},{"./_to-integer":311,"./_to-length":313}],311:[function(require,module,exports){ // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; @@ -33186,7 +35872,7 @@ module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; -},{}],311:[function(require,module,exports){ +},{}],312:[function(require,module,exports){ // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = require('./_iobject'); var defined = require('./_defined'); @@ -33194,7 +35880,7 @@ module.exports = function (it) { return IObject(defined(it)); }; -},{"./_defined":228,"./_iobject":248}],312:[function(require,module,exports){ +},{"./_defined":229,"./_iobject":249}],313:[function(require,module,exports){ // 7.1.15 ToLength var toInteger = require('./_to-integer'); var min = Math.min; @@ -33202,16 +35888,16 @@ module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; -},{"./_to-integer":310}],313:[function(require,module,exports){ +},{"./_to-integer":311}],314:[function(require,module,exports){ // 7.1.13 ToObject(argument) var defined = require('./_defined'); module.exports = function (it) { return Object(defined(it)); }; -},{"./_defined":228}],314:[function(require,module,exports){ -arguments[4][202][0].apply(exports,arguments) -},{"./_is-object":252,"dup":202}],315:[function(require,module,exports){ +},{"./_defined":229}],315:[function(require,module,exports){ +arguments[4][203][0].apply(exports,arguments) +},{"./_is-object":253,"dup":203}],316:[function(require,module,exports){ 'use strict'; if (require('./_descriptors')) { var LIBRARY = require('./_library'); @@ -33693,7 +36379,7 @@ if (require('./_descriptors')) { }; } else module.exports = function () { /* empty */ }; -},{"./_an-instance":208,"./_array-copy-within":210,"./_array-fill":211,"./_array-includes":212,"./_array-methods":213,"./_classof":218,"./_ctx":225,"./_descriptors":229,"./_export":233,"./_fails":235,"./_global":241,"./_has":242,"./_hide":243,"./_is-array-iter":249,"./_is-object":252,"./_iter-detect":257,"./_iterators":259,"./_library":260,"./_object-create":269,"./_object-dp":270,"./_object-gopd":272,"./_object-gopn":274,"./_object-gpo":276,"./_property-desc":287,"./_redefine-all":288,"./_set-species":294,"./_species-constructor":298,"./_to-absolute-index":308,"./_to-index":309,"./_to-integer":310,"./_to-length":312,"./_to-object":313,"./_to-primitive":314,"./_typed":317,"./_typed-buffer":316,"./_uid":318,"./_wks":323,"./core.get-iterator-method":324,"./es6.array.iterator":335}],316:[function(require,module,exports){ +},{"./_an-instance":209,"./_array-copy-within":211,"./_array-fill":212,"./_array-includes":213,"./_array-methods":214,"./_classof":219,"./_ctx":226,"./_descriptors":230,"./_export":234,"./_fails":236,"./_global":242,"./_has":243,"./_hide":244,"./_is-array-iter":250,"./_is-object":253,"./_iter-detect":258,"./_iterators":260,"./_library":261,"./_object-create":270,"./_object-dp":271,"./_object-gopd":273,"./_object-gopn":275,"./_object-gpo":277,"./_property-desc":288,"./_redefine-all":289,"./_set-species":295,"./_species-constructor":299,"./_to-absolute-index":309,"./_to-index":310,"./_to-integer":311,"./_to-length":313,"./_to-object":314,"./_to-primitive":315,"./_typed":318,"./_typed-buffer":317,"./_uid":319,"./_wks":324,"./core.get-iterator-method":325,"./es6.array.iterator":336}],317:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var DESCRIPTORS = require('./_descriptors'); @@ -33971,7 +36657,7 @@ hide($DataView[PROTOTYPE], $typed.VIEW, true); exports[ARRAY_BUFFER] = $ArrayBuffer; exports[DATA_VIEW] = $DataView; -},{"./_an-instance":208,"./_array-fill":211,"./_descriptors":229,"./_fails":235,"./_global":241,"./_hide":243,"./_library":260,"./_object-dp":270,"./_object-gopn":274,"./_redefine-all":288,"./_set-to-string-tag":295,"./_to-index":309,"./_to-integer":310,"./_to-length":312,"./_typed":317}],317:[function(require,module,exports){ +},{"./_an-instance":209,"./_array-fill":212,"./_descriptors":230,"./_fails":236,"./_global":242,"./_hide":244,"./_library":261,"./_object-dp":271,"./_object-gopn":275,"./_redefine-all":289,"./_set-to-string-tag":296,"./_to-index":310,"./_to-integer":311,"./_to-length":313,"./_typed":318}],318:[function(require,module,exports){ var global = require('./_global'); var hide = require('./_hide'); var uid = require('./_uid'); @@ -34001,27 +36687,27 @@ module.exports = { VIEW: VIEW }; -},{"./_global":241,"./_hide":243,"./_uid":318}],318:[function(require,module,exports){ +},{"./_global":242,"./_hide":244,"./_uid":319}],319:[function(require,module,exports){ var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; -},{}],319:[function(require,module,exports){ +},{}],320:[function(require,module,exports){ var global = require('./_global'); var navigator = global.navigator; module.exports = navigator && navigator.userAgent || ''; -},{"./_global":241}],320:[function(require,module,exports){ +},{"./_global":242}],321:[function(require,module,exports){ var isObject = require('./_is-object'); module.exports = function (it, TYPE) { if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); return it; }; -},{"./_is-object":252}],321:[function(require,module,exports){ +},{"./_is-object":253}],322:[function(require,module,exports){ var global = require('./_global'); var core = require('./_core'); var LIBRARY = require('./_library'); @@ -34032,10 +36718,10 @@ module.exports = function (name) { if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); }; -},{"./_core":223,"./_global":241,"./_library":260,"./_object-dp":270,"./_wks-ext":322}],322:[function(require,module,exports){ +},{"./_core":224,"./_global":242,"./_library":261,"./_object-dp":271,"./_wks-ext":323}],323:[function(require,module,exports){ exports.f = require('./_wks'); -},{"./_wks":323}],323:[function(require,module,exports){ +},{"./_wks":324}],324:[function(require,module,exports){ var store = require('./_shared')('wks'); var uid = require('./_uid'); var Symbol = require('./_global').Symbol; @@ -34048,7 +36734,7 @@ var $exports = module.exports = function (name) { $exports.store = store; -},{"./_global":241,"./_shared":297,"./_uid":318}],324:[function(require,module,exports){ +},{"./_global":242,"./_shared":298,"./_uid":319}],325:[function(require,module,exports){ var classof = require('./_classof'); var ITERATOR = require('./_wks')('iterator'); var Iterators = require('./_iterators'); @@ -34058,7 +36744,7 @@ module.exports = require('./_core').getIteratorMethod = function (it) { || Iterators[classof(it)]; }; -},{"./_classof":218,"./_core":223,"./_iterators":259,"./_wks":323}],325:[function(require,module,exports){ +},{"./_classof":219,"./_core":224,"./_iterators":260,"./_wks":324}],326:[function(require,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) var $export = require('./_export'); @@ -34066,7 +36752,7 @@ $export($export.P, 'Array', { copyWithin: require('./_array-copy-within') }); require('./_add-to-unscopables')('copyWithin'); -},{"./_add-to-unscopables":206,"./_array-copy-within":210,"./_export":233}],326:[function(require,module,exports){ +},{"./_add-to-unscopables":207,"./_array-copy-within":211,"./_export":234}],327:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $every = require('./_array-methods')(4); @@ -34078,7 +36764,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].every, true), 'A } }); -},{"./_array-methods":213,"./_export":233,"./_strict-method":299}],327:[function(require,module,exports){ +},{"./_array-methods":214,"./_export":234,"./_strict-method":300}],328:[function(require,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var $export = require('./_export'); @@ -34086,7 +36772,7 @@ $export($export.P, 'Array', { fill: require('./_array-fill') }); require('./_add-to-unscopables')('fill'); -},{"./_add-to-unscopables":206,"./_array-fill":211,"./_export":233}],328:[function(require,module,exports){ +},{"./_add-to-unscopables":207,"./_array-fill":212,"./_export":234}],329:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $filter = require('./_array-methods')(2); @@ -34098,7 +36784,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].filter, true), ' } }); -},{"./_array-methods":213,"./_export":233,"./_strict-method":299}],329:[function(require,module,exports){ +},{"./_array-methods":214,"./_export":234,"./_strict-method":300}],330:[function(require,module,exports){ 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var $export = require('./_export'); @@ -34114,7 +36800,7 @@ $export($export.P + $export.F * forced, 'Array', { }); require('./_add-to-unscopables')(KEY); -},{"./_add-to-unscopables":206,"./_array-methods":213,"./_export":233}],330:[function(require,module,exports){ +},{"./_add-to-unscopables":207,"./_array-methods":214,"./_export":234}],331:[function(require,module,exports){ 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var $export = require('./_export'); @@ -34130,7 +36816,7 @@ $export($export.P + $export.F * forced, 'Array', { }); require('./_add-to-unscopables')(KEY); -},{"./_add-to-unscopables":206,"./_array-methods":213,"./_export":233}],331:[function(require,module,exports){ +},{"./_add-to-unscopables":207,"./_array-methods":214,"./_export":234}],332:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $forEach = require('./_array-methods')(0); @@ -34143,7 +36829,7 @@ $export($export.P + $export.F * !STRICT, 'Array', { } }); -},{"./_array-methods":213,"./_export":233,"./_strict-method":299}],332:[function(require,module,exports){ +},{"./_array-methods":214,"./_export":234,"./_strict-method":300}],333:[function(require,module,exports){ 'use strict'; var ctx = require('./_ctx'); var $export = require('./_export'); @@ -34182,7 +36868,7 @@ $export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Arr } }); -},{"./_create-property":224,"./_ctx":225,"./_export":233,"./_is-array-iter":249,"./_iter-call":254,"./_iter-detect":257,"./_to-length":312,"./_to-object":313,"./core.get-iterator-method":324}],333:[function(require,module,exports){ +},{"./_create-property":225,"./_ctx":226,"./_export":234,"./_is-array-iter":250,"./_iter-call":255,"./_iter-detect":258,"./_to-length":313,"./_to-object":314,"./core.get-iterator-method":325}],334:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $indexOf = require('./_array-includes')(false); @@ -34199,13 +36885,13 @@ $export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($ } }); -},{"./_array-includes":212,"./_export":233,"./_strict-method":299}],334:[function(require,module,exports){ +},{"./_array-includes":213,"./_export":234,"./_strict-method":300}],335:[function(require,module,exports){ // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = require('./_export'); $export($export.S, 'Array', { isArray: require('./_is-array') }); -},{"./_export":233,"./_is-array":250}],335:[function(require,module,exports){ +},{"./_export":234,"./_is-array":251}],336:[function(require,module,exports){ 'use strict'; var addToUnscopables = require('./_add-to-unscopables'); var step = require('./_iter-step'); @@ -34241,7 +36927,7 @@ addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); -},{"./_add-to-unscopables":206,"./_iter-define":256,"./_iter-step":258,"./_iterators":259,"./_to-iobject":311}],336:[function(require,module,exports){ +},{"./_add-to-unscopables":207,"./_iter-define":257,"./_iter-step":259,"./_iterators":260,"./_to-iobject":312}],337:[function(require,module,exports){ 'use strict'; // 22.1.3.13 Array.prototype.join(separator) var $export = require('./_export'); @@ -34255,7 +36941,7 @@ $export($export.P + $export.F * (require('./_iobject') != Object || !require('./ } }); -},{"./_export":233,"./_iobject":248,"./_strict-method":299,"./_to-iobject":311}],337:[function(require,module,exports){ +},{"./_export":234,"./_iobject":249,"./_strict-method":300,"./_to-iobject":312}],338:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var toIObject = require('./_to-iobject'); @@ -34279,7 +36965,7 @@ $export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($ } }); -},{"./_export":233,"./_strict-method":299,"./_to-integer":310,"./_to-iobject":311,"./_to-length":312}],338:[function(require,module,exports){ +},{"./_export":234,"./_strict-method":300,"./_to-integer":311,"./_to-iobject":312,"./_to-length":313}],339:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $map = require('./_array-methods')(1); @@ -34291,7 +36977,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].map, true), 'Arr } }); -},{"./_array-methods":213,"./_export":233,"./_strict-method":299}],339:[function(require,module,exports){ +},{"./_array-methods":214,"./_export":234,"./_strict-method":300}],340:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var createProperty = require('./_create-property'); @@ -34312,7 +36998,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_create-property":224,"./_export":233,"./_fails":235}],340:[function(require,module,exports){ +},{"./_create-property":225,"./_export":234,"./_fails":236}],341:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $reduce = require('./_array-reduce'); @@ -34324,7 +37010,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].reduceRight, tru } }); -},{"./_array-reduce":214,"./_export":233,"./_strict-method":299}],341:[function(require,module,exports){ +},{"./_array-reduce":215,"./_export":234,"./_strict-method":300}],342:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $reduce = require('./_array-reduce'); @@ -34336,7 +37022,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].reduce, true), ' } }); -},{"./_array-reduce":214,"./_export":233,"./_strict-method":299}],342:[function(require,module,exports){ +},{"./_array-reduce":215,"./_export":234,"./_strict-method":300}],343:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var html = require('./_html'); @@ -34366,7 +37052,7 @@ $export($export.P + $export.F * require('./_fails')(function () { } }); -},{"./_cof":219,"./_export":233,"./_fails":235,"./_html":244,"./_to-absolute-index":308,"./_to-length":312}],343:[function(require,module,exports){ +},{"./_cof":220,"./_export":234,"./_fails":236,"./_html":245,"./_to-absolute-index":309,"./_to-length":313}],344:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $some = require('./_array-methods')(3); @@ -34378,7 +37064,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].some, true), 'Ar } }); -},{"./_array-methods":213,"./_export":233,"./_strict-method":299}],344:[function(require,module,exports){ +},{"./_array-methods":214,"./_export":234,"./_strict-method":300}],345:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var aFunction = require('./_a-function'); @@ -34403,16 +37089,16 @@ $export($export.P + $export.F * (fails(function () { } }); -},{"./_a-function":204,"./_export":233,"./_fails":235,"./_strict-method":299,"./_to-object":313}],345:[function(require,module,exports){ +},{"./_a-function":205,"./_export":234,"./_fails":236,"./_strict-method":300,"./_to-object":314}],346:[function(require,module,exports){ require('./_set-species')('Array'); -},{"./_set-species":294}],346:[function(require,module,exports){ +},{"./_set-species":295}],347:[function(require,module,exports){ // 20.3.3.1 / 15.9.4.4 Date.now() var $export = require('./_export'); $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); -},{"./_export":233}],347:[function(require,module,exports){ +},{"./_export":234}],348:[function(require,module,exports){ // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() var $export = require('./_export'); var toISOString = require('./_date-to-iso-string'); @@ -34422,7 +37108,7 @@ $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'D toISOString: toISOString }); -},{"./_date-to-iso-string":226,"./_export":233}],348:[function(require,module,exports){ +},{"./_date-to-iso-string":227,"./_export":234}],349:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var toObject = require('./_to-object'); @@ -34440,13 +37126,13 @@ $export($export.P + $export.F * require('./_fails')(function () { } }); -},{"./_export":233,"./_fails":235,"./_to-object":313,"./_to-primitive":314}],349:[function(require,module,exports){ +},{"./_export":234,"./_fails":236,"./_to-object":314,"./_to-primitive":315}],350:[function(require,module,exports){ var TO_PRIMITIVE = require('./_wks')('toPrimitive'); var proto = Date.prototype; if (!(TO_PRIMITIVE in proto)) require('./_hide')(proto, TO_PRIMITIVE, require('./_date-to-primitive')); -},{"./_date-to-primitive":227,"./_hide":243,"./_wks":323}],350:[function(require,module,exports){ +},{"./_date-to-primitive":228,"./_hide":244,"./_wks":324}],351:[function(require,module,exports){ var DateProto = Date.prototype; var INVALID_DATE = 'Invalid Date'; var TO_STRING = 'toString'; @@ -34460,13 +37146,13 @@ if (new Date(NaN) + '' != INVALID_DATE) { }); } -},{"./_redefine":289}],351:[function(require,module,exports){ +},{"./_redefine":290}],352:[function(require,module,exports){ // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) var $export = require('./_export'); $export($export.P, 'Function', { bind: require('./_bind') }); -},{"./_bind":217,"./_export":233}],352:[function(require,module,exports){ +},{"./_bind":218,"./_export":234}],353:[function(require,module,exports){ 'use strict'; var isObject = require('./_is-object'); var getPrototypeOf = require('./_object-gpo'); @@ -34481,7 +37167,7 @@ if (!(HAS_INSTANCE in FunctionProto)) require('./_object-dp').f(FunctionProto, H return false; } }); -},{"./_is-object":252,"./_object-dp":270,"./_object-gpo":276,"./_wks":323}],353:[function(require,module,exports){ +},{"./_is-object":253,"./_object-dp":271,"./_object-gpo":277,"./_wks":324}],354:[function(require,module,exports){ var dP = require('./_object-dp').f; var FProto = Function.prototype; var nameRE = /^\s*function ([^ (]*)/; @@ -34499,7 +37185,7 @@ NAME in FProto || require('./_descriptors') && dP(FProto, NAME, { } }); -},{"./_descriptors":229,"./_object-dp":270}],354:[function(require,module,exports){ +},{"./_descriptors":230,"./_object-dp":271}],355:[function(require,module,exports){ 'use strict'; var strong = require('./_collection-strong'); var validate = require('./_validate-collection'); @@ -34520,7 +37206,7 @@ module.exports = require('./_collection')(MAP, function (get) { } }, strong, true); -},{"./_collection":222,"./_collection-strong":220,"./_validate-collection":320}],355:[function(require,module,exports){ +},{"./_collection":223,"./_collection-strong":221,"./_validate-collection":321}],356:[function(require,module,exports){ // 20.2.2.3 Math.acosh(x) var $export = require('./_export'); var log1p = require('./_math-log1p'); @@ -34540,7 +37226,7 @@ $export($export.S + $export.F * !($acosh } }); -},{"./_export":233,"./_math-log1p":263}],356:[function(require,module,exports){ +},{"./_export":234,"./_math-log1p":264}],357:[function(require,module,exports){ // 20.2.2.5 Math.asinh(x) var $export = require('./_export'); var $asinh = Math.asinh; @@ -34552,7 +37238,7 @@ function asinh(x) { // Tor Browser bug: Math.asinh(0) -> -0 $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); -},{"./_export":233}],357:[function(require,module,exports){ +},{"./_export":234}],358:[function(require,module,exports){ // 20.2.2.7 Math.atanh(x) var $export = require('./_export'); var $atanh = Math.atanh; @@ -34564,7 +37250,7 @@ $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { } }); -},{"./_export":233}],358:[function(require,module,exports){ +},{"./_export":234}],359:[function(require,module,exports){ // 20.2.2.9 Math.cbrt(x) var $export = require('./_export'); var sign = require('./_math-sign'); @@ -34575,7 +37261,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":233,"./_math-sign":264}],359:[function(require,module,exports){ +},{"./_export":234,"./_math-sign":265}],360:[function(require,module,exports){ // 20.2.2.11 Math.clz32(x) var $export = require('./_export'); @@ -34585,7 +37271,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":233}],360:[function(require,module,exports){ +},{"./_export":234}],361:[function(require,module,exports){ // 20.2.2.12 Math.cosh(x) var $export = require('./_export'); var exp = Math.exp; @@ -34596,20 +37282,20 @@ $export($export.S, 'Math', { } }); -},{"./_export":233}],361:[function(require,module,exports){ +},{"./_export":234}],362:[function(require,module,exports){ // 20.2.2.14 Math.expm1(x) var $export = require('./_export'); var $expm1 = require('./_math-expm1'); $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); -},{"./_export":233,"./_math-expm1":261}],362:[function(require,module,exports){ +},{"./_export":234,"./_math-expm1":262}],363:[function(require,module,exports){ // 20.2.2.16 Math.fround(x) var $export = require('./_export'); $export($export.S, 'Math', { fround: require('./_math-fround') }); -},{"./_export":233,"./_math-fround":262}],363:[function(require,module,exports){ +},{"./_export":234,"./_math-fround":263}],364:[function(require,module,exports){ // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = require('./_export'); var abs = Math.abs; @@ -34636,7 +37322,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":233}],364:[function(require,module,exports){ +},{"./_export":234}],365:[function(require,module,exports){ // 20.2.2.18 Math.imul(x, y) var $export = require('./_export'); var $imul = Math.imul; @@ -34655,7 +37341,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_export":233,"./_fails":235}],365:[function(require,module,exports){ +},{"./_export":234,"./_fails":236}],366:[function(require,module,exports){ // 20.2.2.21 Math.log10(x) var $export = require('./_export'); @@ -34665,13 +37351,13 @@ $export($export.S, 'Math', { } }); -},{"./_export":233}],366:[function(require,module,exports){ +},{"./_export":234}],367:[function(require,module,exports){ // 20.2.2.20 Math.log1p(x) var $export = require('./_export'); $export($export.S, 'Math', { log1p: require('./_math-log1p') }); -},{"./_export":233,"./_math-log1p":263}],367:[function(require,module,exports){ +},{"./_export":234,"./_math-log1p":264}],368:[function(require,module,exports){ // 20.2.2.22 Math.log2(x) var $export = require('./_export'); @@ -34681,13 +37367,13 @@ $export($export.S, 'Math', { } }); -},{"./_export":233}],368:[function(require,module,exports){ +},{"./_export":234}],369:[function(require,module,exports){ // 20.2.2.28 Math.sign(x) var $export = require('./_export'); $export($export.S, 'Math', { sign: require('./_math-sign') }); -},{"./_export":233,"./_math-sign":264}],369:[function(require,module,exports){ +},{"./_export":234,"./_math-sign":265}],370:[function(require,module,exports){ // 20.2.2.30 Math.sinh(x) var $export = require('./_export'); var expm1 = require('./_math-expm1'); @@ -34704,7 +37390,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_export":233,"./_fails":235,"./_math-expm1":261}],370:[function(require,module,exports){ +},{"./_export":234,"./_fails":236,"./_math-expm1":262}],371:[function(require,module,exports){ // 20.2.2.33 Math.tanh(x) var $export = require('./_export'); var expm1 = require('./_math-expm1'); @@ -34718,7 +37404,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":233,"./_math-expm1":261}],371:[function(require,module,exports){ +},{"./_export":234,"./_math-expm1":262}],372:[function(require,module,exports){ // 20.2.2.34 Math.trunc(x) var $export = require('./_export'); @@ -34728,7 +37414,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":233}],372:[function(require,module,exports){ +},{"./_export":234}],373:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var has = require('./_has'); @@ -34799,13 +37485,13 @@ if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { require('./_redefine')(global, NUMBER, $Number); } -},{"./_cof":219,"./_descriptors":229,"./_fails":235,"./_global":241,"./_has":242,"./_inherit-if-required":246,"./_object-create":269,"./_object-dp":270,"./_object-gopd":272,"./_object-gopn":274,"./_redefine":289,"./_string-trim":305,"./_to-primitive":314}],373:[function(require,module,exports){ +},{"./_cof":220,"./_descriptors":230,"./_fails":236,"./_global":242,"./_has":243,"./_inherit-if-required":247,"./_object-create":270,"./_object-dp":271,"./_object-gopd":273,"./_object-gopn":275,"./_redefine":290,"./_string-trim":306,"./_to-primitive":315}],374:[function(require,module,exports){ // 20.1.2.1 Number.EPSILON var $export = require('./_export'); $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); -},{"./_export":233}],374:[function(require,module,exports){ +},{"./_export":234}],375:[function(require,module,exports){ // 20.1.2.2 Number.isFinite(number) var $export = require('./_export'); var _isFinite = require('./_global').isFinite; @@ -34816,13 +37502,13 @@ $export($export.S, 'Number', { } }); -},{"./_export":233,"./_global":241}],375:[function(require,module,exports){ +},{"./_export":234,"./_global":242}],376:[function(require,module,exports){ // 20.1.2.3 Number.isInteger(number) var $export = require('./_export'); $export($export.S, 'Number', { isInteger: require('./_is-integer') }); -},{"./_export":233,"./_is-integer":251}],376:[function(require,module,exports){ +},{"./_export":234,"./_is-integer":252}],377:[function(require,module,exports){ // 20.1.2.4 Number.isNaN(number) var $export = require('./_export'); @@ -34833,7 +37519,7 @@ $export($export.S, 'Number', { } }); -},{"./_export":233}],377:[function(require,module,exports){ +},{"./_export":234}],378:[function(require,module,exports){ // 20.1.2.5 Number.isSafeInteger(number) var $export = require('./_export'); var isInteger = require('./_is-integer'); @@ -34845,31 +37531,31 @@ $export($export.S, 'Number', { } }); -},{"./_export":233,"./_is-integer":251}],378:[function(require,module,exports){ +},{"./_export":234,"./_is-integer":252}],379:[function(require,module,exports){ // 20.1.2.6 Number.MAX_SAFE_INTEGER var $export = require('./_export'); $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); -},{"./_export":233}],379:[function(require,module,exports){ +},{"./_export":234}],380:[function(require,module,exports){ // 20.1.2.10 Number.MIN_SAFE_INTEGER var $export = require('./_export'); $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); -},{"./_export":233}],380:[function(require,module,exports){ +},{"./_export":234}],381:[function(require,module,exports){ var $export = require('./_export'); var $parseFloat = require('./_parse-float'); // 20.1.2.12 Number.parseFloat(string) $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); -},{"./_export":233,"./_parse-float":283}],381:[function(require,module,exports){ +},{"./_export":234,"./_parse-float":284}],382:[function(require,module,exports){ var $export = require('./_export'); var $parseInt = require('./_parse-int'); // 20.1.2.13 Number.parseInt(string, radix) $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); -},{"./_export":233,"./_parse-int":284}],382:[function(require,module,exports){ +},{"./_export":234,"./_parse-int":285}],383:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var toInteger = require('./_to-integer'); @@ -34985,7 +37671,7 @@ $export($export.P + $export.F * (!!$toFixed && ( } }); -},{"./_a-number-value":205,"./_export":233,"./_fails":235,"./_string-repeat":304,"./_to-integer":310}],383:[function(require,module,exports){ +},{"./_a-number-value":206,"./_export":234,"./_fails":236,"./_string-repeat":305,"./_to-integer":311}],384:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $fails = require('./_fails'); @@ -35005,28 +37691,28 @@ $export($export.P + $export.F * ($fails(function () { } }); -},{"./_a-number-value":205,"./_export":233,"./_fails":235}],384:[function(require,module,exports){ +},{"./_a-number-value":206,"./_export":234,"./_fails":236}],385:[function(require,module,exports){ // 19.1.3.1 Object.assign(target, source) var $export = require('./_export'); $export($export.S + $export.F, 'Object', { assign: require('./_object-assign') }); -},{"./_export":233,"./_object-assign":268}],385:[function(require,module,exports){ +},{"./_export":234,"./_object-assign":269}],386:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', { create: require('./_object-create') }); -},{"./_export":233,"./_object-create":269}],386:[function(require,module,exports){ +},{"./_export":234,"./_object-create":270}],387:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) $export($export.S + $export.F * !require('./_descriptors'), 'Object', { defineProperties: require('./_object-dps') }); -},{"./_descriptors":229,"./_export":233,"./_object-dps":271}],387:[function(require,module,exports){ +},{"./_descriptors":230,"./_export":234,"./_object-dps":272}],388:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !require('./_descriptors'), 'Object', { defineProperty: require('./_object-dp').f }); -},{"./_descriptors":229,"./_export":233,"./_object-dp":270}],388:[function(require,module,exports){ +},{"./_descriptors":230,"./_export":234,"./_object-dp":271}],389:[function(require,module,exports){ // 19.1.2.5 Object.freeze(O) var isObject = require('./_is-object'); var meta = require('./_meta').onFreeze; @@ -35037,7 +37723,7 @@ require('./_object-sap')('freeze', function ($freeze) { }; }); -},{"./_is-object":252,"./_meta":265,"./_object-sap":280}],389:[function(require,module,exports){ +},{"./_is-object":253,"./_meta":266,"./_object-sap":281}],390:[function(require,module,exports){ // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = require('./_to-iobject'); var $getOwnPropertyDescriptor = require('./_object-gopd').f; @@ -35048,13 +37734,13 @@ require('./_object-sap')('getOwnPropertyDescriptor', function () { }; }); -},{"./_object-gopd":272,"./_object-sap":280,"./_to-iobject":311}],390:[function(require,module,exports){ +},{"./_object-gopd":273,"./_object-sap":281,"./_to-iobject":312}],391:[function(require,module,exports){ // 19.1.2.7 Object.getOwnPropertyNames(O) require('./_object-sap')('getOwnPropertyNames', function () { return require('./_object-gopn-ext').f; }); -},{"./_object-gopn-ext":273,"./_object-sap":280}],391:[function(require,module,exports){ +},{"./_object-gopn-ext":274,"./_object-sap":281}],392:[function(require,module,exports){ // 19.1.2.9 Object.getPrototypeOf(O) var toObject = require('./_to-object'); var $getPrototypeOf = require('./_object-gpo'); @@ -35065,7 +37751,7 @@ require('./_object-sap')('getPrototypeOf', function () { }; }); -},{"./_object-gpo":276,"./_object-sap":280,"./_to-object":313}],392:[function(require,module,exports){ +},{"./_object-gpo":277,"./_object-sap":281,"./_to-object":314}],393:[function(require,module,exports){ // 19.1.2.11 Object.isExtensible(O) var isObject = require('./_is-object'); @@ -35075,7 +37761,7 @@ require('./_object-sap')('isExtensible', function ($isExtensible) { }; }); -},{"./_is-object":252,"./_object-sap":280}],393:[function(require,module,exports){ +},{"./_is-object":253,"./_object-sap":281}],394:[function(require,module,exports){ // 19.1.2.12 Object.isFrozen(O) var isObject = require('./_is-object'); @@ -35085,7 +37771,7 @@ require('./_object-sap')('isFrozen', function ($isFrozen) { }; }); -},{"./_is-object":252,"./_object-sap":280}],394:[function(require,module,exports){ +},{"./_is-object":253,"./_object-sap":281}],395:[function(require,module,exports){ // 19.1.2.13 Object.isSealed(O) var isObject = require('./_is-object'); @@ -35095,12 +37781,12 @@ require('./_object-sap')('isSealed', function ($isSealed) { }; }); -},{"./_is-object":252,"./_object-sap":280}],395:[function(require,module,exports){ +},{"./_is-object":253,"./_object-sap":281}],396:[function(require,module,exports){ // 19.1.3.10 Object.is(value1, value2) var $export = require('./_export'); $export($export.S, 'Object', { is: require('./_same-value') }); -},{"./_export":233,"./_same-value":292}],396:[function(require,module,exports){ +},{"./_export":234,"./_same-value":293}],397:[function(require,module,exports){ // 19.1.2.14 Object.keys(O) var toObject = require('./_to-object'); var $keys = require('./_object-keys'); @@ -35111,7 +37797,7 @@ require('./_object-sap')('keys', function () { }; }); -},{"./_object-keys":278,"./_object-sap":280,"./_to-object":313}],397:[function(require,module,exports){ +},{"./_object-keys":279,"./_object-sap":281,"./_to-object":314}],398:[function(require,module,exports){ // 19.1.2.15 Object.preventExtensions(O) var isObject = require('./_is-object'); var meta = require('./_meta').onFreeze; @@ -35122,7 +37808,7 @@ require('./_object-sap')('preventExtensions', function ($preventExtensions) { }; }); -},{"./_is-object":252,"./_meta":265,"./_object-sap":280}],398:[function(require,module,exports){ +},{"./_is-object":253,"./_meta":266,"./_object-sap":281}],399:[function(require,module,exports){ // 19.1.2.17 Object.seal(O) var isObject = require('./_is-object'); var meta = require('./_meta').onFreeze; @@ -35133,12 +37819,12 @@ require('./_object-sap')('seal', function ($seal) { }; }); -},{"./_is-object":252,"./_meta":265,"./_object-sap":280}],399:[function(require,module,exports){ +},{"./_is-object":253,"./_meta":266,"./_object-sap":281}],400:[function(require,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = require('./_export'); $export($export.S, 'Object', { setPrototypeOf: require('./_set-proto').set }); -},{"./_export":233,"./_set-proto":293}],400:[function(require,module,exports){ +},{"./_export":234,"./_set-proto":294}],401:[function(require,module,exports){ 'use strict'; // 19.1.3.6 Object.prototype.toString() var classof = require('./_classof'); @@ -35150,19 +37836,19 @@ if (test + '' != '[object z]') { }, true); } -},{"./_classof":218,"./_redefine":289,"./_wks":323}],401:[function(require,module,exports){ +},{"./_classof":219,"./_redefine":290,"./_wks":324}],402:[function(require,module,exports){ var $export = require('./_export'); var $parseFloat = require('./_parse-float'); // 18.2.4 parseFloat(string) $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); -},{"./_export":233,"./_parse-float":283}],402:[function(require,module,exports){ +},{"./_export":234,"./_parse-float":284}],403:[function(require,module,exports){ var $export = require('./_export'); var $parseInt = require('./_parse-int'); // 18.2.5 parseInt(string, radix) $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); -},{"./_export":233,"./_parse-int":284}],403:[function(require,module,exports){ +},{"./_export":234,"./_parse-int":285}],404:[function(require,module,exports){ 'use strict'; var LIBRARY = require('./_library'); var global = require('./_global'); @@ -35450,7 +38136,7 @@ $export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(functi } }); -},{"./_a-function":204,"./_an-instance":208,"./_classof":218,"./_core":223,"./_ctx":225,"./_export":233,"./_for-of":239,"./_global":241,"./_is-object":252,"./_iter-detect":257,"./_library":260,"./_microtask":266,"./_new-promise-capability":267,"./_perform":285,"./_promise-resolve":286,"./_redefine-all":288,"./_set-species":294,"./_set-to-string-tag":295,"./_species-constructor":298,"./_task":307,"./_user-agent":319,"./_wks":323}],404:[function(require,module,exports){ +},{"./_a-function":205,"./_an-instance":209,"./_classof":219,"./_core":224,"./_ctx":226,"./_export":234,"./_for-of":240,"./_global":242,"./_is-object":253,"./_iter-detect":258,"./_library":261,"./_microtask":267,"./_new-promise-capability":268,"./_perform":286,"./_promise-resolve":287,"./_redefine-all":289,"./_set-species":295,"./_set-to-string-tag":296,"./_species-constructor":299,"./_task":308,"./_user-agent":320,"./_wks":324}],405:[function(require,module,exports){ // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) var $export = require('./_export'); var aFunction = require('./_a-function'); @@ -35468,7 +38154,7 @@ $export($export.S + $export.F * !require('./_fails')(function () { } }); -},{"./_a-function":204,"./_an-object":209,"./_export":233,"./_fails":235,"./_global":241}],405:[function(require,module,exports){ +},{"./_a-function":205,"./_an-object":210,"./_export":234,"./_fails":236,"./_global":242}],406:[function(require,module,exports){ // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $export = require('./_export'); var create = require('./_object-create'); @@ -35517,7 +38203,7 @@ $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { } }); -},{"./_a-function":204,"./_an-object":209,"./_bind":217,"./_export":233,"./_fails":235,"./_global":241,"./_is-object":252,"./_object-create":269}],406:[function(require,module,exports){ +},{"./_a-function":205,"./_an-object":210,"./_bind":218,"./_export":234,"./_fails":236,"./_global":242,"./_is-object":253,"./_object-create":270}],407:[function(require,module,exports){ // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) var dP = require('./_object-dp'); var $export = require('./_export'); @@ -35542,7 +38228,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_an-object":209,"./_export":233,"./_fails":235,"./_object-dp":270,"./_to-primitive":314}],407:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_fails":236,"./_object-dp":271,"./_to-primitive":315}],408:[function(require,module,exports){ // 26.1.4 Reflect.deleteProperty(target, propertyKey) var $export = require('./_export'); var gOPD = require('./_object-gopd').f; @@ -35555,7 +38241,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":209,"./_export":233,"./_object-gopd":272}],408:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_object-gopd":273}],409:[function(require,module,exports){ 'use strict'; // 26.1.5 Reflect.enumerate(target) var $export = require('./_export'); @@ -35583,7 +38269,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":209,"./_export":233,"./_iter-create":255}],409:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_iter-create":256}],410:[function(require,module,exports){ // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) var gOPD = require('./_object-gopd'); var $export = require('./_export'); @@ -35595,7 +38281,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":209,"./_export":233,"./_object-gopd":272}],410:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_object-gopd":273}],411:[function(require,module,exports){ // 26.1.8 Reflect.getPrototypeOf(target) var $export = require('./_export'); var getProto = require('./_object-gpo'); @@ -35607,7 +38293,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":209,"./_export":233,"./_object-gpo":276}],411:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_object-gpo":277}],412:[function(require,module,exports){ // 26.1.6 Reflect.get(target, propertyKey [, receiver]) var gOPD = require('./_object-gopd'); var getPrototypeOf = require('./_object-gpo'); @@ -35630,7 +38316,7 @@ function get(target, propertyKey /* , receiver */) { $export($export.S, 'Reflect', { get: get }); -},{"./_an-object":209,"./_export":233,"./_has":242,"./_is-object":252,"./_object-gopd":272,"./_object-gpo":276}],412:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_has":243,"./_is-object":253,"./_object-gopd":273,"./_object-gpo":277}],413:[function(require,module,exports){ // 26.1.9 Reflect.has(target, propertyKey) var $export = require('./_export'); @@ -35640,7 +38326,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_export":233}],413:[function(require,module,exports){ +},{"./_export":234}],414:[function(require,module,exports){ // 26.1.10 Reflect.isExtensible(target) var $export = require('./_export'); var anObject = require('./_an-object'); @@ -35653,13 +38339,13 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":209,"./_export":233}],414:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234}],415:[function(require,module,exports){ // 26.1.11 Reflect.ownKeys(target) var $export = require('./_export'); $export($export.S, 'Reflect', { ownKeys: require('./_own-keys') }); -},{"./_export":233,"./_own-keys":282}],415:[function(require,module,exports){ +},{"./_export":234,"./_own-keys":283}],416:[function(require,module,exports){ // 26.1.12 Reflect.preventExtensions(target) var $export = require('./_export'); var anObject = require('./_an-object'); @@ -35677,7 +38363,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":209,"./_export":233}],416:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234}],417:[function(require,module,exports){ // 26.1.14 Reflect.setPrototypeOf(target, proto) var $export = require('./_export'); var setProto = require('./_set-proto'); @@ -35694,7 +38380,7 @@ if (setProto) $export($export.S, 'Reflect', { } }); -},{"./_export":233,"./_set-proto":293}],417:[function(require,module,exports){ +},{"./_export":234,"./_set-proto":294}],418:[function(require,module,exports){ // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) var dP = require('./_object-dp'); var gOPD = require('./_object-gopd'); @@ -35729,7 +38415,7 @@ function set(target, propertyKey, V /* , receiver */) { $export($export.S, 'Reflect', { set: set }); -},{"./_an-object":209,"./_export":233,"./_has":242,"./_is-object":252,"./_object-dp":270,"./_object-gopd":272,"./_object-gpo":276,"./_property-desc":287}],418:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_has":243,"./_is-object":253,"./_object-dp":271,"./_object-gopd":273,"./_object-gpo":277,"./_property-desc":288}],419:[function(require,module,exports){ var global = require('./_global'); var inheritIfRequired = require('./_inherit-if-required'); var dP = require('./_object-dp').f; @@ -35774,7 +38460,7 @@ if (require('./_descriptors') && (!CORRECT_NEW || require('./_fails')(function ( require('./_set-species')('RegExp'); -},{"./_descriptors":229,"./_fails":235,"./_flags":237,"./_global":241,"./_inherit-if-required":246,"./_is-regexp":253,"./_object-dp":270,"./_object-gopn":274,"./_redefine":289,"./_set-species":294,"./_wks":323}],419:[function(require,module,exports){ +},{"./_descriptors":230,"./_fails":236,"./_flags":238,"./_global":242,"./_inherit-if-required":247,"./_is-regexp":254,"./_object-dp":271,"./_object-gopn":275,"./_redefine":290,"./_set-species":295,"./_wks":324}],420:[function(require,module,exports){ 'use strict'; var regexpExec = require('./_regexp-exec'); require('./_export')({ @@ -35785,14 +38471,14 @@ require('./_export')({ exec: regexpExec }); -},{"./_export":233,"./_regexp-exec":291}],420:[function(require,module,exports){ +},{"./_export":234,"./_regexp-exec":292}],421:[function(require,module,exports){ // 21.2.5.3 get RegExp.prototype.flags() if (require('./_descriptors') && /./g.flags != 'g') require('./_object-dp').f(RegExp.prototype, 'flags', { configurable: true, get: require('./_flags') }); -},{"./_descriptors":229,"./_flags":237,"./_object-dp":270}],421:[function(require,module,exports){ +},{"./_descriptors":230,"./_flags":238,"./_object-dp":271}],422:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); @@ -35834,7 +38520,7 @@ require('./_fix-re-wks')('match', 1, function (defined, MATCH, $match, maybeCall ]; }); -},{"./_advance-string-index":207,"./_an-object":209,"./_fix-re-wks":236,"./_regexp-exec-abstract":290,"./_to-length":312}],422:[function(require,module,exports){ +},{"./_advance-string-index":208,"./_an-object":210,"./_fix-re-wks":237,"./_regexp-exec-abstract":291,"./_to-length":313}],423:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); @@ -35954,7 +38640,7 @@ require('./_fix-re-wks')('replace', 2, function (defined, REPLACE, $replace, may } }); -},{"./_advance-string-index":207,"./_an-object":209,"./_fix-re-wks":236,"./_regexp-exec-abstract":290,"./_to-integer":310,"./_to-length":312,"./_to-object":313}],423:[function(require,module,exports){ +},{"./_advance-string-index":208,"./_an-object":210,"./_fix-re-wks":237,"./_regexp-exec-abstract":291,"./_to-integer":311,"./_to-length":313,"./_to-object":314}],424:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); @@ -35987,7 +38673,7 @@ require('./_fix-re-wks')('search', 1, function (defined, SEARCH, $search, maybeC ]; }); -},{"./_an-object":209,"./_fix-re-wks":236,"./_regexp-exec-abstract":290,"./_same-value":292}],424:[function(require,module,exports){ +},{"./_an-object":210,"./_fix-re-wks":237,"./_regexp-exec-abstract":291,"./_same-value":293}],425:[function(require,module,exports){ 'use strict'; var isRegExp = require('./_is-regexp'); @@ -36123,7 +38809,7 @@ require('./_fix-re-wks')('split', 2, function (defined, SPLIT, $split, maybeCall ]; }); -},{"./_advance-string-index":207,"./_an-object":209,"./_fails":235,"./_fix-re-wks":236,"./_is-regexp":253,"./_regexp-exec":291,"./_regexp-exec-abstract":290,"./_species-constructor":298,"./_to-length":312}],425:[function(require,module,exports){ +},{"./_advance-string-index":208,"./_an-object":210,"./_fails":236,"./_fix-re-wks":237,"./_is-regexp":254,"./_regexp-exec":292,"./_regexp-exec-abstract":291,"./_species-constructor":299,"./_to-length":313}],426:[function(require,module,exports){ 'use strict'; require('./es6.regexp.flags'); var anObject = require('./_an-object'); @@ -36150,7 +38836,7 @@ if (require('./_fails')(function () { return $toString.call({ source: 'a', flags }); } -},{"./_an-object":209,"./_descriptors":229,"./_fails":235,"./_flags":237,"./_redefine":289,"./es6.regexp.flags":420}],426:[function(require,module,exports){ +},{"./_an-object":210,"./_descriptors":230,"./_fails":236,"./_flags":238,"./_redefine":290,"./es6.regexp.flags":421}],427:[function(require,module,exports){ 'use strict'; var strong = require('./_collection-strong'); var validate = require('./_validate-collection'); @@ -36166,7 +38852,7 @@ module.exports = require('./_collection')(SET, function (get) { } }, strong); -},{"./_collection":222,"./_collection-strong":220,"./_validate-collection":320}],427:[function(require,module,exports){ +},{"./_collection":223,"./_collection-strong":221,"./_validate-collection":321}],428:[function(require,module,exports){ 'use strict'; // B.2.3.2 String.prototype.anchor(name) require('./_string-html')('anchor', function (createHTML) { @@ -36175,7 +38861,7 @@ require('./_string-html')('anchor', function (createHTML) { }; }); -},{"./_string-html":302}],428:[function(require,module,exports){ +},{"./_string-html":303}],429:[function(require,module,exports){ 'use strict'; // B.2.3.3 String.prototype.big() require('./_string-html')('big', function (createHTML) { @@ -36184,7 +38870,7 @@ require('./_string-html')('big', function (createHTML) { }; }); -},{"./_string-html":302}],429:[function(require,module,exports){ +},{"./_string-html":303}],430:[function(require,module,exports){ 'use strict'; // B.2.3.4 String.prototype.blink() require('./_string-html')('blink', function (createHTML) { @@ -36193,7 +38879,7 @@ require('./_string-html')('blink', function (createHTML) { }; }); -},{"./_string-html":302}],430:[function(require,module,exports){ +},{"./_string-html":303}],431:[function(require,module,exports){ 'use strict'; // B.2.3.5 String.prototype.bold() require('./_string-html')('bold', function (createHTML) { @@ -36202,7 +38888,7 @@ require('./_string-html')('bold', function (createHTML) { }; }); -},{"./_string-html":302}],431:[function(require,module,exports){ +},{"./_string-html":303}],432:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $at = require('./_string-at')(false); @@ -36213,7 +38899,7 @@ $export($export.P, 'String', { } }); -},{"./_export":233,"./_string-at":300}],432:[function(require,module,exports){ +},{"./_export":234,"./_string-at":301}],433:[function(require,module,exports){ // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) 'use strict'; var $export = require('./_export'); @@ -36235,7 +38921,7 @@ $export($export.P + $export.F * require('./_fails-is-regexp')(ENDS_WITH), 'Strin } }); -},{"./_export":233,"./_fails-is-regexp":234,"./_string-context":301,"./_to-length":312}],433:[function(require,module,exports){ +},{"./_export":234,"./_fails-is-regexp":235,"./_string-context":302,"./_to-length":313}],434:[function(require,module,exports){ 'use strict'; // B.2.3.6 String.prototype.fixed() require('./_string-html')('fixed', function (createHTML) { @@ -36244,7 +38930,7 @@ require('./_string-html')('fixed', function (createHTML) { }; }); -},{"./_string-html":302}],434:[function(require,module,exports){ +},{"./_string-html":303}],435:[function(require,module,exports){ 'use strict'; // B.2.3.7 String.prototype.fontcolor(color) require('./_string-html')('fontcolor', function (createHTML) { @@ -36253,7 +38939,7 @@ require('./_string-html')('fontcolor', function (createHTML) { }; }); -},{"./_string-html":302}],435:[function(require,module,exports){ +},{"./_string-html":303}],436:[function(require,module,exports){ 'use strict'; // B.2.3.8 String.prototype.fontsize(size) require('./_string-html')('fontsize', function (createHTML) { @@ -36262,7 +38948,7 @@ require('./_string-html')('fontsize', function (createHTML) { }; }); -},{"./_string-html":302}],436:[function(require,module,exports){ +},{"./_string-html":303}],437:[function(require,module,exports){ var $export = require('./_export'); var toAbsoluteIndex = require('./_to-absolute-index'); var fromCharCode = String.fromCharCode; @@ -36287,7 +38973,7 @@ $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1) } }); -},{"./_export":233,"./_to-absolute-index":308}],437:[function(require,module,exports){ +},{"./_export":234,"./_to-absolute-index":309}],438:[function(require,module,exports){ // 21.1.3.7 String.prototype.includes(searchString, position = 0) 'use strict'; var $export = require('./_export'); @@ -36301,7 +38987,7 @@ $export($export.P + $export.F * require('./_fails-is-regexp')(INCLUDES), 'String } }); -},{"./_export":233,"./_fails-is-regexp":234,"./_string-context":301}],438:[function(require,module,exports){ +},{"./_export":234,"./_fails-is-regexp":235,"./_string-context":302}],439:[function(require,module,exports){ 'use strict'; // B.2.3.9 String.prototype.italics() require('./_string-html')('italics', function (createHTML) { @@ -36310,7 +38996,7 @@ require('./_string-html')('italics', function (createHTML) { }; }); -},{"./_string-html":302}],439:[function(require,module,exports){ +},{"./_string-html":303}],440:[function(require,module,exports){ 'use strict'; var $at = require('./_string-at')(true); @@ -36329,7 +39015,7 @@ require('./_iter-define')(String, 'String', function (iterated) { return { value: point, done: false }; }); -},{"./_iter-define":256,"./_string-at":300}],440:[function(require,module,exports){ +},{"./_iter-define":257,"./_string-at":301}],441:[function(require,module,exports){ 'use strict'; // B.2.3.10 String.prototype.link(url) require('./_string-html')('link', function (createHTML) { @@ -36338,7 +39024,7 @@ require('./_string-html')('link', function (createHTML) { }; }); -},{"./_string-html":302}],441:[function(require,module,exports){ +},{"./_string-html":303}],442:[function(require,module,exports){ var $export = require('./_export'); var toIObject = require('./_to-iobject'); var toLength = require('./_to-length'); @@ -36358,7 +39044,7 @@ $export($export.S, 'String', { } }); -},{"./_export":233,"./_to-iobject":311,"./_to-length":312}],442:[function(require,module,exports){ +},{"./_export":234,"./_to-iobject":312,"./_to-length":313}],443:[function(require,module,exports){ var $export = require('./_export'); $export($export.P, 'String', { @@ -36366,7 +39052,7 @@ $export($export.P, 'String', { repeat: require('./_string-repeat') }); -},{"./_export":233,"./_string-repeat":304}],443:[function(require,module,exports){ +},{"./_export":234,"./_string-repeat":305}],444:[function(require,module,exports){ 'use strict'; // B.2.3.11 String.prototype.small() require('./_string-html')('small', function (createHTML) { @@ -36375,7 +39061,7 @@ require('./_string-html')('small', function (createHTML) { }; }); -},{"./_string-html":302}],444:[function(require,module,exports){ +},{"./_string-html":303}],445:[function(require,module,exports){ // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) 'use strict'; var $export = require('./_export'); @@ -36395,7 +39081,7 @@ $export($export.P + $export.F * require('./_fails-is-regexp')(STARTS_WITH), 'Str } }); -},{"./_export":233,"./_fails-is-regexp":234,"./_string-context":301,"./_to-length":312}],445:[function(require,module,exports){ +},{"./_export":234,"./_fails-is-regexp":235,"./_string-context":302,"./_to-length":313}],446:[function(require,module,exports){ 'use strict'; // B.2.3.12 String.prototype.strike() require('./_string-html')('strike', function (createHTML) { @@ -36404,7 +39090,7 @@ require('./_string-html')('strike', function (createHTML) { }; }); -},{"./_string-html":302}],446:[function(require,module,exports){ +},{"./_string-html":303}],447:[function(require,module,exports){ 'use strict'; // B.2.3.13 String.prototype.sub() require('./_string-html')('sub', function (createHTML) { @@ -36413,7 +39099,7 @@ require('./_string-html')('sub', function (createHTML) { }; }); -},{"./_string-html":302}],447:[function(require,module,exports){ +},{"./_string-html":303}],448:[function(require,module,exports){ 'use strict'; // B.2.3.14 String.prototype.sup() require('./_string-html')('sup', function (createHTML) { @@ -36422,7 +39108,7 @@ require('./_string-html')('sup', function (createHTML) { }; }); -},{"./_string-html":302}],448:[function(require,module,exports){ +},{"./_string-html":303}],449:[function(require,module,exports){ 'use strict'; // 21.1.3.25 String.prototype.trim() require('./_string-trim')('trim', function ($trim) { @@ -36431,7 +39117,7 @@ require('./_string-trim')('trim', function ($trim) { }; }); -},{"./_string-trim":305}],449:[function(require,module,exports){ +},{"./_string-trim":306}],450:[function(require,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var global = require('./_global'); @@ -36679,7 +39365,7 @@ setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); -},{"./_an-object":209,"./_descriptors":229,"./_enum-keys":232,"./_export":233,"./_fails":235,"./_global":241,"./_has":242,"./_hide":243,"./_is-array":250,"./_is-object":252,"./_library":260,"./_meta":265,"./_object-create":269,"./_object-dp":270,"./_object-gopd":272,"./_object-gopn":274,"./_object-gopn-ext":273,"./_object-gops":275,"./_object-keys":278,"./_object-pie":279,"./_property-desc":287,"./_redefine":289,"./_set-to-string-tag":295,"./_shared":297,"./_to-iobject":311,"./_to-object":313,"./_to-primitive":314,"./_uid":318,"./_wks":323,"./_wks-define":321,"./_wks-ext":322}],450:[function(require,module,exports){ +},{"./_an-object":210,"./_descriptors":230,"./_enum-keys":233,"./_export":234,"./_fails":236,"./_global":242,"./_has":243,"./_hide":244,"./_is-array":251,"./_is-object":253,"./_library":261,"./_meta":266,"./_object-create":270,"./_object-dp":271,"./_object-gopd":273,"./_object-gopn":275,"./_object-gopn-ext":274,"./_object-gops":276,"./_object-keys":279,"./_object-pie":280,"./_property-desc":288,"./_redefine":290,"./_set-to-string-tag":296,"./_shared":298,"./_to-iobject":312,"./_to-object":314,"./_to-primitive":315,"./_uid":319,"./_wks":324,"./_wks-define":322,"./_wks-ext":323}],451:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $typed = require('./_typed'); @@ -36727,76 +39413,76 @@ $export($export.P + $export.U + $export.F * require('./_fails')(function () { require('./_set-species')(ARRAY_BUFFER); -},{"./_an-object":209,"./_export":233,"./_fails":235,"./_global":241,"./_is-object":252,"./_set-species":294,"./_species-constructor":298,"./_to-absolute-index":308,"./_to-length":312,"./_typed":317,"./_typed-buffer":316}],451:[function(require,module,exports){ +},{"./_an-object":210,"./_export":234,"./_fails":236,"./_global":242,"./_is-object":253,"./_set-species":295,"./_species-constructor":299,"./_to-absolute-index":309,"./_to-length":313,"./_typed":318,"./_typed-buffer":317}],452:[function(require,module,exports){ var $export = require('./_export'); $export($export.G + $export.W + $export.F * !require('./_typed').ABV, { DataView: require('./_typed-buffer').DataView }); -},{"./_export":233,"./_typed":317,"./_typed-buffer":316}],452:[function(require,module,exports){ +},{"./_export":234,"./_typed":318,"./_typed-buffer":317}],453:[function(require,module,exports){ require('./_typed-array')('Float32', 4, function (init) { return function Float32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],453:[function(require,module,exports){ +},{"./_typed-array":316}],454:[function(require,module,exports){ require('./_typed-array')('Float64', 8, function (init) { return function Float64Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],454:[function(require,module,exports){ +},{"./_typed-array":316}],455:[function(require,module,exports){ require('./_typed-array')('Int16', 2, function (init) { return function Int16Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],455:[function(require,module,exports){ +},{"./_typed-array":316}],456:[function(require,module,exports){ require('./_typed-array')('Int32', 4, function (init) { return function Int32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],456:[function(require,module,exports){ +},{"./_typed-array":316}],457:[function(require,module,exports){ require('./_typed-array')('Int8', 1, function (init) { return function Int8Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],457:[function(require,module,exports){ +},{"./_typed-array":316}],458:[function(require,module,exports){ require('./_typed-array')('Uint16', 2, function (init) { return function Uint16Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],458:[function(require,module,exports){ +},{"./_typed-array":316}],459:[function(require,module,exports){ require('./_typed-array')('Uint32', 4, function (init) { return function Uint32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],459:[function(require,module,exports){ +},{"./_typed-array":316}],460:[function(require,module,exports){ require('./_typed-array')('Uint8', 1, function (init) { return function Uint8Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":315}],460:[function(require,module,exports){ +},{"./_typed-array":316}],461:[function(require,module,exports){ require('./_typed-array')('Uint8', 1, function (init) { return function Uint8ClampedArray(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }, true); -},{"./_typed-array":315}],461:[function(require,module,exports){ +},{"./_typed-array":316}],462:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var each = require('./_array-methods')(0); @@ -36858,7 +39544,7 @@ if (NATIVE_WEAK_MAP && IS_IE11) { }); } -},{"./_array-methods":213,"./_collection":222,"./_collection-weak":221,"./_global":241,"./_is-object":252,"./_meta":265,"./_object-assign":268,"./_redefine":289,"./_validate-collection":320}],462:[function(require,module,exports){ +},{"./_array-methods":214,"./_collection":223,"./_collection-weak":222,"./_global":242,"./_is-object":253,"./_meta":266,"./_object-assign":269,"./_redefine":290,"./_validate-collection":321}],463:[function(require,module,exports){ 'use strict'; var weak = require('./_collection-weak'); var validate = require('./_validate-collection'); @@ -36874,7 +39560,7 @@ require('./_collection')(WEAK_SET, function (get) { } }, weak, false, true); -},{"./_collection":222,"./_collection-weak":221,"./_validate-collection":320}],463:[function(require,module,exports){ +},{"./_collection":223,"./_collection-weak":222,"./_validate-collection":321}],464:[function(require,module,exports){ 'use strict'; // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap var $export = require('./_export'); @@ -36898,7 +39584,7 @@ $export($export.P, 'Array', { require('./_add-to-unscopables')('flatMap'); -},{"./_a-function":204,"./_add-to-unscopables":206,"./_array-species-create":216,"./_export":233,"./_flatten-into-array":238,"./_to-length":312,"./_to-object":313}],464:[function(require,module,exports){ +},{"./_a-function":205,"./_add-to-unscopables":207,"./_array-species-create":217,"./_export":234,"./_flatten-into-array":239,"./_to-length":313,"./_to-object":314}],465:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/Array.prototype.includes var $export = require('./_export'); @@ -36912,7 +39598,7 @@ $export($export.P, 'Array', { require('./_add-to-unscopables')('includes'); -},{"./_add-to-unscopables":206,"./_array-includes":212,"./_export":233}],465:[function(require,module,exports){ +},{"./_add-to-unscopables":207,"./_array-includes":213,"./_export":234}],466:[function(require,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = require('./_export'); var $entries = require('./_object-to-array')(true); @@ -36923,7 +39609,7 @@ $export($export.S, 'Object', { } }); -},{"./_export":233,"./_object-to-array":281}],466:[function(require,module,exports){ +},{"./_export":234,"./_object-to-array":282}],467:[function(require,module,exports){ // https://github.com/tc39/proposal-object-getownpropertydescriptors var $export = require('./_export'); var ownKeys = require('./_own-keys'); @@ -36947,7 +39633,7 @@ $export($export.S, 'Object', { } }); -},{"./_create-property":224,"./_export":233,"./_object-gopd":272,"./_own-keys":282,"./_to-iobject":311}],467:[function(require,module,exports){ +},{"./_create-property":225,"./_export":234,"./_object-gopd":273,"./_own-keys":283,"./_to-iobject":312}],468:[function(require,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = require('./_export'); var $values = require('./_object-to-array')(false); @@ -36958,7 +39644,7 @@ $export($export.S, 'Object', { } }); -},{"./_export":233,"./_object-to-array":281}],468:[function(require,module,exports){ +},{"./_export":234,"./_object-to-array":282}],469:[function(require,module,exports){ // https://github.com/tc39/proposal-promise-finally 'use strict'; var $export = require('./_export'); @@ -36980,7 +39666,7 @@ $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { ); } }); -},{"./_core":223,"./_export":233,"./_global":241,"./_promise-resolve":286,"./_species-constructor":298}],469:[function(require,module,exports){ +},{"./_core":224,"./_export":234,"./_global":242,"./_promise-resolve":287,"./_species-constructor":299}],470:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = require('./_export'); @@ -36996,7 +39682,7 @@ $export($export.P + $export.F * WEBKIT_BUG, 'String', { } }); -},{"./_export":233,"./_string-pad":303,"./_user-agent":319}],470:[function(require,module,exports){ +},{"./_export":234,"./_string-pad":304,"./_user-agent":320}],471:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = require('./_export'); @@ -37012,7 +39698,7 @@ $export($export.P + $export.F * WEBKIT_BUG, 'String', { } }); -},{"./_export":233,"./_string-pad":303,"./_user-agent":319}],471:[function(require,module,exports){ +},{"./_export":234,"./_string-pad":304,"./_user-agent":320}],472:[function(require,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim require('./_string-trim')('trimLeft', function ($trim) { @@ -37021,7 +39707,7 @@ require('./_string-trim')('trimLeft', function ($trim) { }; }, 'trimStart'); -},{"./_string-trim":305}],472:[function(require,module,exports){ +},{"./_string-trim":306}],473:[function(require,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim require('./_string-trim')('trimRight', function ($trim) { @@ -37030,10 +39716,10 @@ require('./_string-trim')('trimRight', function ($trim) { }; }, 'trimEnd'); -},{"./_string-trim":305}],473:[function(require,module,exports){ +},{"./_string-trim":306}],474:[function(require,module,exports){ require('./_wks-define')('asyncIterator'); -},{"./_wks-define":321}],474:[function(require,module,exports){ +},{"./_wks-define":322}],475:[function(require,module,exports){ var $iterators = require('./es6.array.iterator'); var getKeys = require('./_object-keys'); var redefine = require('./_redefine'); @@ -37093,7 +39779,7 @@ for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++ } } -},{"./_global":241,"./_hide":243,"./_iterators":259,"./_object-keys":278,"./_redefine":289,"./_wks":323,"./es6.array.iterator":335}],475:[function(require,module,exports){ +},{"./_global":242,"./_hide":244,"./_iterators":260,"./_object-keys":279,"./_redefine":290,"./_wks":324,"./es6.array.iterator":336}],476:[function(require,module,exports){ var $export = require('./_export'); var $task = require('./_task'); $export($export.G + $export.B, { @@ -37101,7 +39787,7 @@ $export($export.G + $export.B, { clearImmediate: $task.clear }); -},{"./_export":233,"./_task":307}],476:[function(require,module,exports){ +},{"./_export":234,"./_task":308}],477:[function(require,module,exports){ // ie9- setTimeout & setInterval additional parameters fix var global = require('./_global'); var $export = require('./_export'); @@ -37123,13 +39809,13 @@ $export($export.G + $export.B + $export.F * MSIE, { setInterval: wrap(global.setInterval) }); -},{"./_export":233,"./_global":241,"./_user-agent":319}],477:[function(require,module,exports){ +},{"./_export":234,"./_global":242,"./_user-agent":320}],478:[function(require,module,exports){ require('../modules/web.timers'); require('../modules/web.immediate'); require('../modules/web.dom.iterable'); module.exports = require('../modules/_core'); -},{"../modules/_core":223,"../modules/web.dom.iterable":474,"../modules/web.immediate":475,"../modules/web.timers":476}],478:[function(require,module,exports){ +},{"../modules/_core":224,"../modules/web.dom.iterable":475,"../modules/web.immediate":476,"../modules/web.timers":477}],479:[function(require,module,exports){ (function (Buffer){(function (){ var elliptic = require('elliptic') var BN = require('bn.js') @@ -37257,9 +39943,9 @@ function formatReturnValue (bn, enc, len) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"bn.js":479,"buffer":169,"elliptic":510}],479:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"buffer":124,"dup":88}],480:[function(require,module,exports){ +},{"bn.js":480,"buffer":170,"elliptic":512}],480:[function(require,module,exports){ +arguments[4][89][0].apply(exports,arguments) +},{"buffer":125,"dup":89}],481:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var MD5 = require('md5.js') @@ -37291,14 +39977,14 @@ module.exports = function createHash (alg) { return new Hash(sha(alg)) } -},{"cipher-base":172,"inherits":587,"md5.js":615,"ripemd160":683,"sha.js":912}],481:[function(require,module,exports){ +},{"cipher-base":173,"inherits":586,"md5.js":614,"ripemd160":683,"sha.js":912}],482:[function(require,module,exports){ var MD5 = require('md5.js') module.exports = function (buffer) { return new MD5().update(buffer).digest() } -},{"md5.js":615}],482:[function(require,module,exports){ +},{"md5.js":614}],483:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var Legacy = require('./legacy') @@ -37362,7 +40048,7 @@ module.exports = function createHmac (alg, key) { return new Hmac(alg, key) } -},{"./legacy":483,"cipher-base":172,"create-hash/md5":481,"inherits":587,"ripemd160":683,"safe-buffer":909,"sha.js":912}],483:[function(require,module,exports){ +},{"./legacy":484,"cipher-base":173,"create-hash/md5":482,"inherits":586,"ripemd160":683,"safe-buffer":909,"sha.js":912}],484:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var Buffer = require('safe-buffer').Buffer @@ -37410,7 +40096,7 @@ Hmac.prototype._final = function () { } module.exports = Hmac -},{"cipher-base":172,"inherits":587,"safe-buffer":909}],484:[function(require,module,exports){ +},{"cipher-base":173,"inherits":586,"safe-buffer":909}],485:[function(require,module,exports){ 'use strict' exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') @@ -37509,7 +40195,7 @@ exports.constants = { 'POINT_CONVERSION_HYBRID': 6 } -},{"browserify-cipher":142,"browserify-sign":149,"browserify-sign/algos":146,"create-ecdh":478,"create-hash":480,"create-hmac":482,"diffie-hellman":505,"pbkdf2":640,"public-encrypt":668,"randombytes":676,"randomfill":677}],485:[function(require,module,exports){ +},{"browserify-cipher":143,"browserify-sign":150,"browserify-sign/algos":147,"create-ecdh":479,"create-hash":481,"create-hmac":483,"diffie-hellman":507,"pbkdf2":640,"public-encrypt":668,"randombytes":676,"randomfill":677}],486:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -37744,7 +40430,7 @@ exports.constants = { return CryptoJS.AES; })); -},{"./cipher-core":486,"./core":487,"./enc-base64":488,"./evpkdf":490,"./md5":492}],486:[function(require,module,exports){ +},{"./cipher-core":487,"./core":488,"./enc-base64":489,"./evpkdf":491,"./md5":493}],487:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -38635,7 +41321,7 @@ exports.constants = { })); -},{"./core":487,"./evpkdf":490}],487:[function(require,module,exports){ +},{"./core":488,"./evpkdf":491}],488:[function(require,module,exports){ (function (global){(function (){ ;(function (root, factory) { if (typeof exports === "object") { @@ -39435,7 +42121,7 @@ exports.constants = { })); }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"crypto":484}],488:[function(require,module,exports){ +},{"crypto":485}],489:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -39572,7 +42258,7 @@ exports.constants = { return CryptoJS.enc.Base64; })); -},{"./core":487}],489:[function(require,module,exports){ +},{"./core":488}],490:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -39591,7 +42277,7 @@ exports.constants = { return CryptoJS.enc.Utf8; })); -},{"./core":487}],490:[function(require,module,exports){ +},{"./core":488}],491:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -39726,7 +42412,7 @@ exports.constants = { return CryptoJS.EvpKDF; })); -},{"./core":487,"./hmac":491,"./sha1":493}],491:[function(require,module,exports){ +},{"./core":488,"./hmac":492,"./sha1":494}],492:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -39870,7 +42556,7 @@ exports.constants = { })); -},{"./core":487}],492:[function(require,module,exports){ +},{"./core":488}],493:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -40139,7 +42825,7 @@ exports.constants = { return CryptoJS.MD5; })); -},{"./core":487}],493:[function(require,module,exports){ +},{"./core":488}],494:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -40290,7 +42976,7 @@ exports.constants = { return CryptoJS.SHA1; })); -},{"./core":487}],494:[function(require,module,exports){ +},{"./core":488}],495:[function(require,module,exports){ "use strict"; var _index = require("./index.js"); @@ -40306,7 +42992,7 @@ var _index = require("./index.js"); module.exports = { IdleQueue: _index.IdleQueue }; -},{"./index.js":495}],495:[function(require,module,exports){ +},{"./index.js":496}],496:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -40597,7 +43283,7 @@ function _tryIdleCall(idleQueue) { }, 0); }, 0); } -},{}],496:[function(require,module,exports){ +},{}],497:[function(require,module,exports){ 'use strict'; var objectKeys = require('object-keys'); @@ -40961,7 +43647,23 @@ module.exports = function deepEqual(a, b, opts) { return internalDeepEqual(a, b, opts, getSideChannel()); }; -},{"call-bind/callBound":170,"es-get-iterator":528,"get-intrinsic":546,"is-arguments":588,"is-date-object":591,"is-regex":600,"isarray":607,"object-is":624,"object-keys":628,"object.assign":632,"regexp.prototype.flags":680,"side-channel":919,"which-boxed-primitive":954,"which-collection":955,"which-typed-array":956}],497:[function(require,module,exports){ +},{"call-bind/callBound":171,"es-get-iterator":530,"get-intrinsic":545,"is-arguments":587,"is-date-object":590,"is-regex":599,"isarray":606,"object-is":623,"object-keys":627,"object.assign":631,"regexp.prototype.flags":680,"side-channel":919,"which-boxed-primitive":954,"which-collection":955,"which-typed-array":956}],498:[function(require,module,exports){ +module.exports = function deepFreeze (o) { + Object.freeze(o); + + Object.getOwnPropertyNames(o).forEach(function (prop) { + if (o.hasOwnProperty(prop) + && o[prop] !== null + && (typeof o[prop] === "object" || typeof o[prop] === "function") + && !Object.isFrozen(o[prop])) { + deepFreeze(o[prop]); + } + }); + + return o; +}; + +},{}],499:[function(require,module,exports){ 'use strict'; var keys = require('object-keys'); @@ -41021,7 +43723,7 @@ defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; -},{"object-keys":628}],498:[function(require,module,exports){ +},{"object-keys":627}],500:[function(require,module,exports){ 'use strict'; exports.utils = require('./des/utils'); @@ -41030,7 +43732,7 @@ exports.DES = require('./des/des'); exports.CBC = require('./des/cbc'); exports.EDE = require('./des/ede'); -},{"./des/cbc":499,"./des/cipher":500,"./des/des":501,"./des/ede":502,"./des/utils":503}],499:[function(require,module,exports){ +},{"./des/cbc":501,"./des/cipher":502,"./des/des":503,"./des/ede":504,"./des/utils":505}],501:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -41097,7 +43799,7 @@ proto._update = function _update(inp, inOff, out, outOff) { } }; -},{"inherits":587,"minimalistic-assert":618}],500:[function(require,module,exports){ +},{"inherits":586,"minimalistic-assert":617}],502:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -41240,7 +43942,7 @@ Cipher.prototype._finalDecrypt = function _finalDecrypt() { return this._unpad(out); }; -},{"minimalistic-assert":618}],501:[function(require,module,exports){ +},{"minimalistic-assert":617}],503:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -41384,7 +44086,7 @@ DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { utils.rip(l, r, out, off); }; -},{"./cipher":500,"./utils":503,"inherits":587,"minimalistic-assert":618}],502:[function(require,module,exports){ +},{"./cipher":502,"./utils":505,"inherits":586,"minimalistic-assert":617}],504:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -41440,7 +44142,7 @@ EDE.prototype._update = function _update(inp, inOff, out, outOff) { EDE.prototype._pad = DES.prototype._pad; EDE.prototype._unpad = DES.prototype._unpad; -},{"./cipher":500,"./des":501,"inherits":587,"minimalistic-assert":618}],503:[function(require,module,exports){ +},{"./cipher":502,"./des":503,"inherits":586,"minimalistic-assert":617}],505:[function(require,module,exports){ 'use strict'; exports.readUInt32BE = function readUInt32BE(bytes, off) { @@ -41698,11 +44400,11 @@ exports.padSplit = function padSplit(num, size, group) { return out.join(' '); }; -},{}],504:[function(require,module,exports){ +},{}],506:[function(require,module,exports){ module.exports = false; -},{}],505:[function(require,module,exports){ +},{}],507:[function(require,module,exports){ (function (Buffer){(function (){ var generatePrime = require('./lib/generatePrime') var primes = require('./lib/primes.json') @@ -41748,7 +44450,7 @@ exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffi exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman }).call(this)}).call(this,require("buffer").Buffer) -},{"./lib/dh":506,"./lib/generatePrime":507,"./lib/primes.json":508,"buffer":169}],506:[function(require,module,exports){ +},{"./lib/dh":508,"./lib/generatePrime":509,"./lib/primes.json":510,"buffer":170}],508:[function(require,module,exports){ (function (Buffer){(function (){ var BN = require('bn.js'); var MillerRabin = require('miller-rabin'); @@ -41916,7 +44618,7 @@ function formatReturnValue(bn, enc) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"./generatePrime":507,"bn.js":509,"buffer":169,"miller-rabin":616,"randombytes":676}],507:[function(require,module,exports){ +},{"./generatePrime":509,"bn.js":511,"buffer":170,"miller-rabin":615,"randombytes":676}],509:[function(require,module,exports){ var randomBytes = require('randombytes'); module.exports = findPrime; findPrime.simpleSieve = simpleSieve; @@ -42023,7 +44725,7 @@ function findPrime(bits, gen) { } -},{"bn.js":509,"miller-rabin":616,"randombytes":676}],508:[function(require,module,exports){ +},{"bn.js":511,"miller-rabin":615,"randombytes":676}],510:[function(require,module,exports){ module.exports={ "modp1": { "gen": "02", @@ -42058,9 +44760,9 @@ module.exports={ "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" } } -},{}],509:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"buffer":124,"dup":88}],510:[function(require,module,exports){ +},{}],511:[function(require,module,exports){ +arguments[4][89][0].apply(exports,arguments) +},{"buffer":125,"dup":89}],512:[function(require,module,exports){ 'use strict'; var elliptic = exports; @@ -42075,7 +44777,7 @@ elliptic.curves = require('./elliptic/curves'); elliptic.ec = require('./elliptic/ec'); elliptic.eddsa = require('./elliptic/eddsa'); -},{"../package.json":526,"./elliptic/curve":513,"./elliptic/curves":516,"./elliptic/ec":517,"./elliptic/eddsa":520,"./elliptic/utils":524,"brorand":123}],511:[function(require,module,exports){ +},{"../package.json":528,"./elliptic/curve":515,"./elliptic/curves":518,"./elliptic/ec":519,"./elliptic/eddsa":522,"./elliptic/utils":526,"brorand":124}],513:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -42458,7 +45160,7 @@ BasePoint.prototype.dblp = function dblp(k) { return r; }; -},{"../utils":524,"bn.js":525}],512:[function(require,module,exports){ +},{"../utils":526,"bn.js":527}],514:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -42895,7 +45597,7 @@ Point.prototype.eqXToP = function eqXToP(x) { Point.prototype.toP = Point.prototype.normalize; Point.prototype.mixedAdd = Point.prototype.add; -},{"../utils":524,"./base":511,"bn.js":525,"inherits":587}],513:[function(require,module,exports){ +},{"../utils":526,"./base":513,"bn.js":527,"inherits":586}],515:[function(require,module,exports){ 'use strict'; var curve = exports; @@ -42905,7 +45607,7 @@ curve.short = require('./short'); curve.mont = require('./mont'); curve.edwards = require('./edwards'); -},{"./base":511,"./edwards":512,"./mont":514,"./short":515}],514:[function(require,module,exports){ +},{"./base":513,"./edwards":514,"./mont":516,"./short":517}],516:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -43085,7 +45787,7 @@ Point.prototype.getX = function getX() { return this.x.fromRed(); }; -},{"../utils":524,"./base":511,"bn.js":525,"inherits":587}],515:[function(require,module,exports){ +},{"../utils":526,"./base":513,"bn.js":527,"inherits":586}],517:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -44025,7 +46727,7 @@ JPoint.prototype.isInfinity = function isInfinity() { return this.z.cmpn(0) === 0; }; -},{"../utils":524,"./base":511,"bn.js":525,"inherits":587}],516:[function(require,module,exports){ +},{"../utils":526,"./base":513,"bn.js":527,"inherits":586}],518:[function(require,module,exports){ 'use strict'; var curves = exports; @@ -44233,7 +46935,7 @@ defineCurve('secp256k1', { ], }); -},{"./curve":513,"./precomputed/secp256k1":523,"./utils":524,"hash.js":567}],517:[function(require,module,exports){ +},{"./curve":515,"./precomputed/secp256k1":525,"./utils":526,"hash.js":566}],519:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -44478,7 +47180,7 @@ EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { throw new Error('Unable to find valid recovery factor'); }; -},{"../curves":516,"../utils":524,"./key":518,"./signature":519,"bn.js":525,"brorand":123,"hmac-drbg":579}],518:[function(require,module,exports){ +},{"../curves":518,"../utils":526,"./key":520,"./signature":521,"bn.js":527,"brorand":124,"hmac-drbg":578}],520:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -44601,7 +47303,7 @@ KeyPair.prototype.inspect = function inspect() { ' pub: ' + (this.pub && this.pub.inspect()) + ' >'; }; -},{"../utils":524,"bn.js":525}],519:[function(require,module,exports){ +},{"../utils":526,"bn.js":527}],521:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -44769,7 +47471,7 @@ Signature.prototype.toDER = function toDER(enc) { return utils.encode(res, enc); }; -},{"../utils":524,"bn.js":525}],520:[function(require,module,exports){ +},{"../utils":526,"bn.js":527}],522:[function(require,module,exports){ 'use strict'; var hash = require('hash.js'); @@ -44889,7 +47591,7 @@ EDDSA.prototype.isPoint = function isPoint(val) { return val instanceof this.pointClass; }; -},{"../curves":516,"../utils":524,"./key":521,"./signature":522,"hash.js":567}],521:[function(require,module,exports){ +},{"../curves":518,"../utils":526,"./key":523,"./signature":524,"hash.js":566}],523:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -44986,7 +47688,7 @@ KeyPair.prototype.getPublic = function getPublic(enc) { module.exports = KeyPair; -},{"../utils":524}],522:[function(require,module,exports){ +},{"../utils":526}],524:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -45053,7 +47755,7 @@ Signature.prototype.toHex = function toHex() { module.exports = Signature; -},{"../utils":524,"bn.js":525}],523:[function(require,module,exports){ +},{"../utils":526,"bn.js":527}],525:[function(require,module,exports){ module.exports = { doubles: { step: 4, @@ -45835,7 +48537,7 @@ module.exports = { }, }; -},{}],524:[function(require,module,exports){ +},{}],526:[function(require,module,exports){ 'use strict'; var utils = exports; @@ -45956,9 +48658,9 @@ function intFromLE(bytes) { utils.intFromLE = intFromLE; -},{"bn.js":525,"minimalistic-assert":618,"minimalistic-crypto-utils":619}],525:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"buffer":124,"dup":88}],526:[function(require,module,exports){ +},{"bn.js":527,"minimalistic-assert":617,"minimalistic-crypto-utils":618}],527:[function(require,module,exports){ +arguments[4][89][0].apply(exports,arguments) +},{"buffer":125,"dup":89}],528:[function(require,module,exports){ module.exports={ "_from": "elliptic@^6.5.3", "_id": "elliptic@6.5.4", @@ -45983,7 +48685,7 @@ module.exports={ "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", "_shasum": "da37cebd31e79a1367e941b592ed1fbebd58abbb", "_spec": "elliptic@^6.5.3", - "_where": "/home/runner/work/rxdb/rxdb/node_modules/browserify-sign", + "_where": "/home/dnl/workspace/rxdb/node_modules/browserify-sign", "author": { "name": "Fedor Indutny", "email": "fedor@indutny.com" @@ -46045,7 +48747,7 @@ module.exports={ "version": "6.5.4" } -},{}],527:[function(require,module,exports){ +},{}],529:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('get-intrinsic'); @@ -46062,7 +48764,7 @@ if ($gOPD) { module.exports = $gOPD; -},{"get-intrinsic":546}],528:[function(require,module,exports){ +},{"get-intrinsic":545}],530:[function(require,module,exports){ (function (process){(function (){ 'use strict'; @@ -46273,45 +48975,52 @@ if (require('has-symbols')() || require('has-symbols/shams')()) { } }).call(this)}).call(this,require('_process')) -},{"_process":667,"call-bind/callBound":170,"get-intrinsic":546,"has-symbols":547,"has-symbols/shams":548,"is-arguments":588,"is-map":594,"is-set":601,"is-string":602,"isarray":607}],529:[function(require,module,exports){ +},{"_process":667,"call-bind/callBound":171,"get-intrinsic":545,"has-symbols":546,"has-symbols/shams":547,"is-arguments":587,"is-map":593,"is-set":600,"is-string":601,"isarray":606}],531:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unknownAction = exports.runFullQueryAgain = exports.removeExistingAndInsertAtSortPosition = exports.insertAtSortPosition = exports.alwaysWrong = exports.replaceExisting = exports.removeExisting = exports.removeLastInsertFirst = exports.removeFirstInsertLast = exports.removeLastItem = exports.removeFirstItem = exports.insertLast = exports.insertFirst = exports.doNothing = void 0; var array_push_at_sort_position_1 = require("array-push-at-sort-position"); -exports.doNothing = function (_input) { }; -exports.insertFirst = function (input) { +var doNothing = function (_input) { }; +exports.doNothing = doNothing; +var insertFirst = function (input) { input.previousResults.unshift(input.changeEvent.doc); if (input.keyDocumentMap) { input.keyDocumentMap.set(input.changeEvent.id, input.changeEvent.doc); } }; -exports.insertLast = function (input) { +exports.insertFirst = insertFirst; +var insertLast = function (input) { input.previousResults.push(input.changeEvent.doc); if (input.keyDocumentMap) { input.keyDocumentMap.set(input.changeEvent.id, input.changeEvent.doc); } }; -exports.removeFirstItem = function (input) { +exports.insertLast = insertLast; +var removeFirstItem = function (input) { var first = input.previousResults.shift(); if (input.keyDocumentMap && first) { input.keyDocumentMap.delete(first[input.queryParams.primaryKey]); } }; -exports.removeLastItem = function (input) { +exports.removeFirstItem = removeFirstItem; +var removeLastItem = function (input) { var last = input.previousResults.pop(); if (input.keyDocumentMap && last) { input.keyDocumentMap.delete(last[input.queryParams.primaryKey]); } }; -exports.removeFirstInsertLast = function (input) { +exports.removeLastItem = removeLastItem; +var removeFirstInsertLast = function (input) { exports.removeFirstItem(input); exports.insertLast(input); }; -exports.removeLastInsertFirst = function (input) { +exports.removeFirstInsertLast = removeFirstInsertLast; +var removeLastInsertFirst = function (input) { exports.removeLastItem(input); exports.insertFirst(input); }; -exports.removeExisting = function (input) { +exports.removeLastInsertFirst = removeLastInsertFirst; +var removeExisting = function (input) { if (input.keyDocumentMap) { input.keyDocumentMap.delete(input.changeEvent.id); } @@ -46328,7 +49037,8 @@ exports.removeExisting = function (input) { } } }; -exports.replaceExisting = function (input) { +exports.removeExisting = removeExisting; +var replaceExisting = function (input) { // find index of document var doc = input.changeEvent.doc; var primary = input.queryParams.primaryKey; @@ -46345,12 +49055,13 @@ exports.replaceExisting = function (input) { } } }; +exports.replaceExisting = replaceExisting; /** * this function always returns wrong results * it must be later optimised out * otherwise there is something broken */ -exports.alwaysWrong = function (input) { +var alwaysWrong = function (input) { var wrongHuman = { _id: 'wrongHuman' + new Date().getTime() }; @@ -46361,25 +49072,30 @@ exports.alwaysWrong = function (input) { input.keyDocumentMap.set(wrongHuman._id, wrongHuman); } }; -exports.insertAtSortPosition = function (input) { +exports.alwaysWrong = alwaysWrong; +var insertAtSortPosition = function (input) { var doc = input.changeEvent.doc; if (input.keyDocumentMap) { input.keyDocumentMap.set(input.changeEvent.id, doc); } array_push_at_sort_position_1.pushAtSortPosition(input.previousResults, doc, input.queryParams.sortComparator, true); }; -exports.removeExistingAndInsertAtSortPosition = function (input) { +exports.insertAtSortPosition = insertAtSortPosition; +var removeExistingAndInsertAtSortPosition = function (input) { exports.removeExisting(input); exports.insertAtSortPosition(input); }; -exports.runFullQueryAgain = function (_input) { +exports.removeExistingAndInsertAtSortPosition = removeExistingAndInsertAtSortPosition; +var runFullQueryAgain = function (_input) { throw new Error('Action runFullQueryAgain must be implemented by yourself'); }; -exports.unknownAction = function (_input) { +exports.runFullQueryAgain = runFullQueryAgain; +var unknownAction = function (_input) { throw new Error('Action unknownAction should never be called'); }; +exports.unknownAction = unknownAction; -},{"array-push-at-sort-position":73}],530:[function(require,module,exports){ +},{"array-push-at-sort-position":74}],532:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.actionFunctions = exports.orderedActionList = void 0; @@ -46422,7 +49138,7 @@ exports.actionFunctions = { unknownAction: action_functions_1.unknownAction }; -},{"./action-functions":529}],531:[function(require,module,exports){ +},{"./action-functions":531}],533:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveInput = exports.simpleBdd = exports.minimalBddString = void 0; @@ -46430,9 +49146,10 @@ var binary_decision_diagram_1 = require("binary-decision-diagram"); var states_1 = require("../states"); exports.minimalBddString = '11a+b0c/d3e.f2g*h-i)j(k4ljk3mkj3nbh,odh,peh,qkj5rkm5sdk5tjk5uok5vfi5wkp5xfk5yxk/zgk/{jt/|jk/}bd1~xy1gz1¡jq1¢bs1£no1¤j{1¥j|1¦jl1§kl1¨jr1©nu1ª|a7«|l7¬d}7­¤a7®~¡7¯h7°s¢7±kj7²o£7³¤§7´k¨7µ¥¦7¶u©7·vg6¸¬d6¹­j6º®¯6»°d6¼wj6½²k6¾³j6¿´µ6À¶k6Á¹ª*¾«*ÃjÁ-ÄjÂ-Å·º-Ƹ»-Çi±-ȼ¿-ɽÀ-ÊÃc2ËÄk2ÌÅÆ2ÍÈÉ2ÎÊË0ÏÌÍ0ÐÎÏ8ÑjÇ8ÐÑ.'; exports.simpleBdd = binary_decision_diagram_1.minimalStringToSimpleBdd(exports.minimalBddString); -exports.resolveInput = function (input) { return binary_decision_diagram_1.resolveWithSimpleBdd(exports.simpleBdd, states_1.stateResolveFunctionByIndex, input); }; +var resolveInput = function (input) { return binary_decision_diagram_1.resolveWithSimpleBdd(exports.simpleBdd, states_1.stateResolveFunctionByIndex, input); }; +exports.resolveInput = resolveInput; -},{"../states":533,"binary-decision-diagram":97}],532:[function(require,module,exports){ +},{"../states":535,"binary-decision-diagram":98}],534:[function(require,module,exports){ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -46449,7 +49166,6 @@ exports.runAction = exports.calculateActionFunction = exports.calculateActionNam var states_1 = require("./states"); var actions_1 = require("./actions"); var bdd_generated_1 = require("./bdd/bdd.generated"); -__exportStar(require("./types"), exports); __exportStar(require("./states"), exports); __exportStar(require("./util"), exports); function calculateActionFromMap(stateSetToActionMap, input) { @@ -46496,7 +49212,7 @@ function runAction(action, queryParams, changeEvent, previousResults, keyDocumen } exports.runAction = runAction; -},{"./actions":530,"./bdd/bdd.generated":531,"./states":533,"./types":536,"./util":538}],533:[function(require,module,exports){ +},{"./actions":532,"./bdd/bdd.generated":533,"./states":535,"./util":537}],535:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.logStateSet = exports.getStateSet = exports.resolveState = exports.stateResolveFunctionByIndex = exports.stateResolveFunctions = exports.orderedStateList = void 0; @@ -46589,7 +49305,7 @@ function logStateSet(stateSet) { } exports.logStateSet = logStateSet; -},{"./state-resolver":534}],534:[function(require,module,exports){ +},{"./state-resolver":536}],536:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; @@ -46598,13 +49314,15 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.wasResultsEmpty = exports.doesMatchNow = exports.wasMatching = exports.isSortedAfterLast = exports.isSortedBeforeFirst = exports.wasSortedAfterLast = exports.wasSortedBeforeFirst = exports.wasInResult = exports.sortParamsChanged = exports.wasLimitReached = exports.previousUnknown = exports.isUpdate = exports.isInsert = exports.isDelete = exports.hasSkip = exports.isFindOne = exports.hasLimit = void 0; var object_path_1 = __importDefault(require("object-path")); var util_1 = require("../util"); -exports.hasLimit = function (input) { +var hasLimit = function (input) { return !!input.queryParams.limit; }; -exports.isFindOne = function (input) { +exports.hasLimit = hasLimit; +var isFindOne = function (input) { return input.queryParams.limit === 1; }; -exports.hasSkip = function (input) { +exports.isFindOne = isFindOne; +var hasSkip = function (input) { if (input.queryParams.skip && input.queryParams.skip > 0) { return true; } @@ -46612,22 +49330,28 @@ exports.hasSkip = function (input) { return false; } }; -exports.isDelete = function (input) { +exports.hasSkip = hasSkip; +var isDelete = function (input) { return input.changeEvent.operation === 'DELETE'; }; -exports.isInsert = function (input) { +exports.isDelete = isDelete; +var isInsert = function (input) { return input.changeEvent.operation === 'INSERT'; }; -exports.isUpdate = function (input) { +exports.isInsert = isInsert; +var isUpdate = function (input) { return input.changeEvent.operation === 'UPDATE'; }; -exports.previousUnknown = function (input) { +exports.isUpdate = isUpdate; +var previousUnknown = function (input) { return input.changeEvent.previous === util_1.UNKNOWN_VALUE; }; -exports.wasLimitReached = function (input) { +exports.previousUnknown = previousUnknown; +var wasLimitReached = function (input) { return exports.hasLimit(input) && input.previousResults.length >= input.queryParams.limit; }; -exports.sortParamsChanged = function (input) { +exports.wasLimitReached = wasLimitReached; +var sortParamsChanged = function (input) { var sortFields = input.queryParams.sortFields; var prev = input.changeEvent.previous; var doc = input.changeEvent.doc; @@ -46647,7 +49371,8 @@ exports.sortParamsChanged = function (input) { } return false; }; -exports.wasInResult = function (input) { +exports.sortParamsChanged = sortParamsChanged; +var wasInResult = function (input) { var id = input.changeEvent.id; if (input.keyDocumentMap) { var has = input.keyDocumentMap.has(id); @@ -46665,7 +49390,8 @@ exports.wasInResult = function (input) { return false; } }; -exports.wasSortedBeforeFirst = function (input) { +exports.wasInResult = wasInResult; +var wasSortedBeforeFirst = function (input) { var prev = input.changeEvent.previous; if (!prev || prev === util_1.UNKNOWN_VALUE) { return false; @@ -46677,7 +49403,8 @@ exports.wasSortedBeforeFirst = function (input) { var comp = input.queryParams.sortComparator(prev, first); return comp < 0; }; -exports.wasSortedAfterLast = function (input) { +exports.wasSortedBeforeFirst = wasSortedBeforeFirst; +var wasSortedAfterLast = function (input) { var prev = input.changeEvent.previous; if (!prev || prev === util_1.UNKNOWN_VALUE) { return false; @@ -46689,7 +49416,8 @@ exports.wasSortedAfterLast = function (input) { var comp = input.queryParams.sortComparator(prev, last); return comp > 0; }; -exports.isSortedBeforeFirst = function (input) { +exports.wasSortedAfterLast = wasSortedAfterLast; +var isSortedBeforeFirst = function (input) { var doc = input.changeEvent.doc; if (!doc) { return false; @@ -46701,7 +49429,8 @@ exports.isSortedBeforeFirst = function (input) { var comp = input.queryParams.sortComparator(doc, first); return comp < 0; }; -exports.isSortedAfterLast = function (input) { +exports.isSortedBeforeFirst = isSortedBeforeFirst; +var isSortedAfterLast = function (input) { var doc = input.changeEvent.doc; if (!doc) { return false; @@ -46713,14 +49442,16 @@ exports.isSortedAfterLast = function (input) { var comp = input.queryParams.sortComparator(doc, last); return comp > 0; }; -exports.wasMatching = function (input) { +exports.isSortedAfterLast = isSortedAfterLast; +var wasMatching = function (input) { var prev = input.changeEvent.previous; if (!prev || prev === util_1.UNKNOWN_VALUE) { return false; } return input.queryParams.queryMatcher(prev); }; -exports.doesMatchNow = function (input) { +exports.wasMatching = wasMatching; +var doesMatchNow = function (input) { var doc = input.changeEvent.doc; if (!doc) { return false; @@ -46728,35 +49459,13 @@ exports.doesMatchNow = function (input) { var ret = input.queryParams.queryMatcher(doc); return ret; }; -exports.wasResultsEmpty = function (input) { +exports.doesMatchNow = doesMatchNow; +var wasResultsEmpty = function (input) { return input.previousResults.length === 0; }; +exports.wasResultsEmpty = wasResultsEmpty; -},{"../util":538,"object-path":630}],535:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); - -},{}],536:[function(require,module,exports){ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./change-event"), exports); -__exportStar(require("./mongo"), exports); - -},{"./change-event":535,"./mongo":537}],537:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); - -},{}],538:[function(require,module,exports){ +},{"../util":537,"object-path":629}],537:[function(require,module,exports){ "use strict"; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; @@ -46774,9 +49483,10 @@ var __read = (this && this.__read) || function (o, n) { } return ar; }; -var __spread = (this && this.__spread) || function () { - for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); - return ar; +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeSets = exports.cloneMap = exports.objectToMap = exports.mapToObject = exports.replaceCharAt = exports.getSortFieldsOfQuery = exports.normalizeSortField = exports.tryToFillPreviousDoc = exports.shuffleArray = exports.randomOfArray = exports.lastOfArray = exports.UNKNOWN_VALUE = void 0; @@ -46885,13 +49595,13 @@ exports.cloneMap = cloneMap; function mergeSets(sets) { var ret = new Set(); sets.forEach(function (set) { - ret = new Set(__spread(ret, set)); + ret = new Set(__spreadArray(__spreadArray([], __read(ret)), __read(set))); }); return ret; } exports.mergeSets = mergeSets; -},{}],539:[function(require,module,exports){ +},{}],538:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -47390,7 +50100,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) { } } -},{}],540:[function(require,module,exports){ +},{}],539:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var MD5 = require('md5.js') @@ -47437,7 +50147,7 @@ function EVP_BytesToKey (password, salt, keyBits, ivLen) { module.exports = EVP_BytesToKey -},{"md5.js":615,"safe-buffer":909}],541:[function(require,module,exports){ +},{"md5.js":614,"safe-buffer":909}],540:[function(require,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; @@ -47461,7 +50171,7 @@ module.exports = function forEach (obj, fn, ctx) { }; -},{}],542:[function(require,module,exports){ +},{}],541:[function(require,module,exports){ 'use strict'; /* eslint no-invalid-this: 1 */ @@ -47515,14 +50225,14 @@ module.exports = function bind(that) { return bound; }; -},{}],543:[function(require,module,exports){ +},{}],542:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); module.exports = Function.prototype.bind || implementation; -},{"./implementation":542}],544:[function(require,module,exports){ +},{"./implementation":541}],543:[function(require,module,exports){ var util = require('util') var isProperty = require('is-property') @@ -47705,7 +50415,7 @@ var genfun = function() { genfun.formats = formats module.exports = genfun -},{"is-property":599,"util":942}],545:[function(require,module,exports){ +},{"is-property":598,"util":942}],544:[function(require,module,exports){ var isProperty = require('is-property') var gen = function(obj, prop) { @@ -47719,7 +50429,7 @@ gen.property = function (prop) { module.exports = gen -},{"is-property":599}],546:[function(require,module,exports){ +},{"is-property":598}],545:[function(require,module,exports){ 'use strict'; var undefined; @@ -48051,7 +50761,7 @@ module.exports = function GetIntrinsic(name, allowMissing) { return value; }; -},{"function-bind":543,"has":549,"has-symbols":547}],547:[function(require,module,exports){ +},{"function-bind":542,"has":548,"has-symbols":546}],546:[function(require,module,exports){ 'use strict'; var origSymbol = typeof Symbol !== 'undefined' && Symbol; @@ -48066,7 +50776,7 @@ module.exports = function hasNativeSymbols() { return hasSymbolSham(); }; -},{"./shams":548}],548:[function(require,module,exports){ +},{"./shams":547}],547:[function(require,module,exports){ 'use strict'; /* eslint complexity: [2, 18], max-statements: [2, 33] */ @@ -48110,14 +50820,14 @@ module.exports = function hasSymbols() { return true; }; -},{}],549:[function(require,module,exports){ +},{}],548:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); -},{"function-bind":543}],550:[function(require,module,exports){ +},{"function-bind":542}],549:[function(require,module,exports){ 'use strict' var Buffer = require('safe-buffer').Buffer var Transform = require('readable-stream').Transform @@ -48214,39 +50924,39 @@ HashBase.prototype._digest = function () { module.exports = HashBase -},{"inherits":587,"readable-stream":565,"safe-buffer":566}],551:[function(require,module,exports){ -arguments[4][152][0].apply(exports,arguments) -},{"dup":152}],552:[function(require,module,exports){ +},{"inherits":586,"readable-stream":564,"safe-buffer":565}],550:[function(require,module,exports){ arguments[4][153][0].apply(exports,arguments) -},{"./_stream_readable":554,"./_stream_writable":556,"_process":667,"dup":153,"inherits":587}],553:[function(require,module,exports){ +},{"dup":153}],551:[function(require,module,exports){ arguments[4][154][0].apply(exports,arguments) -},{"./_stream_transform":555,"dup":154,"inherits":587}],554:[function(require,module,exports){ +},{"./_stream_readable":553,"./_stream_writable":555,"_process":667,"dup":154,"inherits":586}],552:[function(require,module,exports){ arguments[4][155][0].apply(exports,arguments) -},{"../errors":551,"./_stream_duplex":552,"./internal/streams/async_iterator":557,"./internal/streams/buffer_list":558,"./internal/streams/destroy":559,"./internal/streams/from":561,"./internal/streams/state":563,"./internal/streams/stream":564,"_process":667,"buffer":169,"dup":155,"events":539,"inherits":587,"string_decoder/":936,"util":124}],555:[function(require,module,exports){ +},{"./_stream_transform":554,"dup":155,"inherits":586}],553:[function(require,module,exports){ arguments[4][156][0].apply(exports,arguments) -},{"../errors":551,"./_stream_duplex":552,"dup":156,"inherits":587}],556:[function(require,module,exports){ +},{"../errors":550,"./_stream_duplex":551,"./internal/streams/async_iterator":556,"./internal/streams/buffer_list":557,"./internal/streams/destroy":558,"./internal/streams/from":560,"./internal/streams/state":562,"./internal/streams/stream":563,"_process":667,"buffer":170,"dup":156,"events":538,"inherits":586,"string_decoder/":936,"util":125}],554:[function(require,module,exports){ arguments[4][157][0].apply(exports,arguments) -},{"../errors":551,"./_stream_duplex":552,"./internal/streams/destroy":559,"./internal/streams/state":563,"./internal/streams/stream":564,"_process":667,"buffer":169,"dup":157,"inherits":587,"util-deprecate":939}],557:[function(require,module,exports){ +},{"../errors":550,"./_stream_duplex":551,"dup":157,"inherits":586}],555:[function(require,module,exports){ arguments[4][158][0].apply(exports,arguments) -},{"./end-of-stream":560,"_process":667,"dup":158}],558:[function(require,module,exports){ +},{"../errors":550,"./_stream_duplex":551,"./internal/streams/destroy":558,"./internal/streams/state":562,"./internal/streams/stream":563,"_process":667,"buffer":170,"dup":158,"inherits":586,"util-deprecate":939}],556:[function(require,module,exports){ arguments[4][159][0].apply(exports,arguments) -},{"buffer":169,"dup":159,"util":124}],559:[function(require,module,exports){ +},{"./end-of-stream":559,"_process":667,"dup":159}],557:[function(require,module,exports){ arguments[4][160][0].apply(exports,arguments) -},{"_process":667,"dup":160}],560:[function(require,module,exports){ +},{"buffer":170,"dup":160,"util":125}],558:[function(require,module,exports){ arguments[4][161][0].apply(exports,arguments) -},{"../../../errors":551,"dup":161}],561:[function(require,module,exports){ +},{"_process":667,"dup":161}],559:[function(require,module,exports){ arguments[4][162][0].apply(exports,arguments) -},{"dup":162}],562:[function(require,module,exports){ +},{"../../../errors":550,"dup":162}],560:[function(require,module,exports){ arguments[4][163][0].apply(exports,arguments) -},{"../../../errors":551,"./end-of-stream":560,"dup":163}],563:[function(require,module,exports){ +},{"dup":163}],561:[function(require,module,exports){ arguments[4][164][0].apply(exports,arguments) -},{"../../../errors":551,"dup":164}],564:[function(require,module,exports){ +},{"../../../errors":550,"./end-of-stream":559,"dup":164}],562:[function(require,module,exports){ arguments[4][165][0].apply(exports,arguments) -},{"dup":165,"events":539}],565:[function(require,module,exports){ +},{"../../../errors":550,"dup":165}],563:[function(require,module,exports){ arguments[4][166][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":552,"./lib/_stream_passthrough.js":553,"./lib/_stream_readable.js":554,"./lib/_stream_transform.js":555,"./lib/_stream_writable.js":556,"./lib/internal/streams/end-of-stream.js":560,"./lib/internal/streams/pipeline.js":562,"dup":166}],566:[function(require,module,exports){ +},{"dup":166,"events":538}],564:[function(require,module,exports){ arguments[4][167][0].apply(exports,arguments) -},{"buffer":169,"dup":167}],567:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":551,"./lib/_stream_passthrough.js":552,"./lib/_stream_readable.js":553,"./lib/_stream_transform.js":554,"./lib/_stream_writable.js":555,"./lib/internal/streams/end-of-stream.js":559,"./lib/internal/streams/pipeline.js":561,"dup":167}],565:[function(require,module,exports){ +arguments[4][168][0].apply(exports,arguments) +},{"buffer":170,"dup":168}],566:[function(require,module,exports){ var hash = exports; hash.utils = require('./hash/utils'); @@ -48263,7 +50973,7 @@ hash.sha384 = hash.sha.sha384; hash.sha512 = hash.sha.sha512; hash.ripemd160 = hash.ripemd.ripemd160; -},{"./hash/common":568,"./hash/hmac":569,"./hash/ripemd":570,"./hash/sha":571,"./hash/utils":578}],568:[function(require,module,exports){ +},{"./hash/common":567,"./hash/hmac":568,"./hash/ripemd":569,"./hash/sha":570,"./hash/utils":577}],567:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); @@ -48357,7 +51067,7 @@ BlockHash.prototype._pad = function pad() { return res; }; -},{"./utils":578,"minimalistic-assert":618}],569:[function(require,module,exports){ +},{"./utils":577,"minimalistic-assert":617}],568:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); @@ -48406,7 +51116,7 @@ Hmac.prototype.digest = function digest(enc) { return this.outer.digest(enc); }; -},{"./utils":578,"minimalistic-assert":618}],570:[function(require,module,exports){ +},{"./utils":577,"minimalistic-assert":617}],569:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); @@ -48554,7 +51264,7 @@ var sh = [ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; -},{"./common":568,"./utils":578}],571:[function(require,module,exports){ +},{"./common":567,"./utils":577}],570:[function(require,module,exports){ 'use strict'; exports.sha1 = require('./sha/1'); @@ -48563,7 +51273,7 @@ exports.sha256 = require('./sha/256'); exports.sha384 = require('./sha/384'); exports.sha512 = require('./sha/512'); -},{"./sha/1":572,"./sha/224":573,"./sha/256":574,"./sha/384":575,"./sha/512":576}],572:[function(require,module,exports){ +},{"./sha/1":571,"./sha/224":572,"./sha/256":573,"./sha/384":574,"./sha/512":575}],571:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -48639,7 +51349,7 @@ SHA1.prototype._digest = function digest(enc) { return utils.split32(this.h, 'big'); }; -},{"../common":568,"../utils":578,"./common":577}],573:[function(require,module,exports){ +},{"../common":567,"../utils":577,"./common":576}],572:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -48671,7 +51381,7 @@ SHA224.prototype._digest = function digest(enc) { }; -},{"../utils":578,"./256":574}],574:[function(require,module,exports){ +},{"../utils":577,"./256":573}],573:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -48778,7 +51488,7 @@ SHA256.prototype._digest = function digest(enc) { return utils.split32(this.h, 'big'); }; -},{"../common":568,"../utils":578,"./common":577,"minimalistic-assert":618}],575:[function(require,module,exports){ +},{"../common":567,"../utils":577,"./common":576,"minimalistic-assert":617}],574:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -48815,7 +51525,7 @@ SHA384.prototype._digest = function digest(enc) { return utils.split32(this.h.slice(0, 12), 'big'); }; -},{"../utils":578,"./512":576}],576:[function(require,module,exports){ +},{"../utils":577,"./512":575}],575:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -49147,7 +51857,7 @@ function g1_512_lo(xh, xl) { return r; } -},{"../common":568,"../utils":578,"minimalistic-assert":618}],577:[function(require,module,exports){ +},{"../common":567,"../utils":577,"minimalistic-assert":617}],576:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -49198,7 +51908,7 @@ function g1_256(x) { } exports.g1_256 = g1_256; -},{"../utils":578}],578:[function(require,module,exports){ +},{"../utils":577}],577:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -49478,7 +52188,7 @@ function shr64_lo(ah, al, num) { } exports.shr64_lo = shr64_lo; -},{"inherits":587,"minimalistic-assert":618}],579:[function(require,module,exports){ +},{"inherits":586,"minimalistic-assert":617}],578:[function(require,module,exports){ 'use strict'; var hash = require('hash.js'); @@ -49593,7 +52303,7 @@ HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { return utils.encode(res, enc); }; -},{"hash.js":567,"minimalistic-assert":618,"minimalistic-crypto-utils":619}],580:[function(require,module,exports){ +},{"hash.js":566,"minimalistic-assert":617,"minimalistic-crypto-utils":618}],579:[function(require,module,exports){ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m @@ -49680,7 +52390,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],581:[function(require,module,exports){ +},{}],580:[function(require,module,exports){ 'use strict'; var types = [ require('./nextTick'), @@ -49779,7 +52489,7 @@ function immediate(task) { } } -},{"./messageChannel":582,"./mutation.js":583,"./nextTick":124,"./queueMicrotask":584,"./stateChange":585,"./timeout":586}],582:[function(require,module,exports){ +},{"./messageChannel":581,"./mutation.js":582,"./nextTick":125,"./queueMicrotask":583,"./stateChange":584,"./timeout":585}],581:[function(require,module,exports){ (function (global){(function (){ 'use strict'; @@ -49800,7 +52510,7 @@ exports.install = function (func) { }; }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],583:[function(require,module,exports){ +},{}],582:[function(require,module,exports){ (function (global){(function (){ 'use strict'; //based off rsvp https://github.com/tildeio/rsvp.js @@ -49825,7 +52535,7 @@ exports.install = function (handle) { }; }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],584:[function(require,module,exports){ +},{}],583:[function(require,module,exports){ (function (global){(function (){ 'use strict'; exports.test = function () { @@ -49839,7 +52549,7 @@ exports.install = function (func) { }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],585:[function(require,module,exports){ +},{}],584:[function(require,module,exports){ (function (global){(function (){ 'use strict'; @@ -49866,7 +52576,7 @@ exports.install = function (handle) { }; }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],586:[function(require,module,exports){ +},{}],585:[function(require,module,exports){ 'use strict'; exports.test = function () { return true; @@ -49877,7 +52587,7 @@ exports.install = function (t) { setTimeout(t, 0); }; }; -},{}],587:[function(require,module,exports){ +},{}],586:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -49906,7 +52616,7 @@ if (typeof Object.create === 'function') { } } -},{}],588:[function(require,module,exports){ +},{}],587:[function(require,module,exports){ 'use strict'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; @@ -49941,7 +52651,7 @@ isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; -},{"call-bind/callBound":170}],589:[function(require,module,exports){ +},{"call-bind/callBound":171}],588:[function(require,module,exports){ 'use strict'; if (typeof BigInt === 'function') { @@ -49979,7 +52689,7 @@ if (typeof BigInt === 'function') { }; } -},{}],590:[function(require,module,exports){ +},{}],589:[function(require,module,exports){ 'use strict'; var callBound = require('call-bind/callBound'); @@ -50007,7 +52717,7 @@ module.exports = function isBoolean(value) { return hasToStringTag && Symbol.toStringTag in value ? tryBooleanObject(value) : $toString(value) === boolClass; }; -},{"call-bind/callBound":170}],591:[function(require,module,exports){ +},{"call-bind/callBound":171}],590:[function(require,module,exports){ 'use strict'; var getDay = Date.prototype.getDay; @@ -50031,7 +52741,7 @@ module.exports = function isDateObject(value) { return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; }; -},{}],592:[function(require,module,exports){ +},{}],591:[function(require,module,exports){ (function (process){(function (){ // https://github.com/electron/electron/issues/2288 function isElectron() { @@ -50056,7 +52766,7 @@ function isElectron() { module.exports = isElectron; }).call(this)}).call(this,require('_process')) -},{"_process":667}],593:[function(require,module,exports){ +},{"_process":667}],592:[function(require,module,exports){ 'use strict'; var toStr = Object.prototype.toString; @@ -50096,7 +52806,7 @@ module.exports = function isGeneratorFunction(fn) { return getProto(fn) === GeneratorFunction; }; -},{}],594:[function(require,module,exports){ +},{}],593:[function(require,module,exports){ 'use strict'; var $Map = typeof Map === 'function' && Map.prototype ? Map : null; @@ -50140,7 +52850,7 @@ module.exports = exported || function isMap(x) { return false; }; -},{}],595:[function(require,module,exports){ +},{}],594:[function(require,module,exports){ var reIpv4FirstPass = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ var reSubnetString = /\/\d{1,3}(?=%|$)/ @@ -50232,7 +52942,7 @@ module.exports['__all_regexes__'] = [ reBadAddress ] -},{}],596:[function(require,module,exports){ +},{}],595:[function(require,module,exports){ var createIpValidator = require('is-my-ip-valid') var reEmailWhitespace = /\s/ @@ -50274,7 +52984,7 @@ exports['phone'] = function (input) { } exports['utc-millisec'] = /^[0-9]{1,15}\.?[0-9]{0,15}$/ -},{"is-my-ip-valid":595}],597:[function(require,module,exports){ +},{"is-my-ip-valid":594}],596:[function(require,module,exports){ var genobj = require('generate-object-property') var genfun = require('generate-function') var jsonpointer = require('jsonpointer') @@ -50899,7 +53609,7 @@ module.exports.filter = function(schema, opts) { } } -},{"./formats":596,"generate-function":544,"generate-object-property":545,"jsonpointer":608,"xtend":957}],598:[function(require,module,exports){ +},{"./formats":595,"generate-function":543,"generate-object-property":544,"jsonpointer":607,"xtend":957}],597:[function(require,module,exports){ 'use strict'; var numToStr = Number.prototype.toString; @@ -50925,13 +53635,13 @@ module.exports = function isNumberObject(value) { return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass; }; -},{}],599:[function(require,module,exports){ +},{}],598:[function(require,module,exports){ "use strict" function isProperty(str) { return /^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(str) } module.exports = isProperty -},{}],600:[function(require,module,exports){ +},{}],599:[function(require,module,exports){ 'use strict'; var callBound = require('call-bind/callBound'); @@ -50992,7 +53702,7 @@ module.exports = hasToStringTag return $toString(value) === regexClass; }; -},{"call-bind/callBound":170,"has-symbols/shams":548}],601:[function(require,module,exports){ +},{"call-bind/callBound":171,"has-symbols/shams":547}],600:[function(require,module,exports){ 'use strict'; var $Map = typeof Map === 'function' && Map.prototype ? Map : null; @@ -51036,7 +53746,7 @@ module.exports = exported || function isSet(x) { return false; }; -},{}],602:[function(require,module,exports){ +},{}],601:[function(require,module,exports){ 'use strict'; var strValue = String.prototype.valueOf; @@ -51062,7 +53772,7 @@ module.exports = function isString(value) { return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass; }; -},{}],603:[function(require,module,exports){ +},{}],602:[function(require,module,exports){ 'use strict'; var toStr = Object.prototype.toString; @@ -51099,7 +53809,7 @@ if (hasSymbols) { }; } -},{"has-symbols":547}],604:[function(require,module,exports){ +},{"has-symbols":546}],603:[function(require,module,exports){ (function (global){(function (){ 'use strict'; @@ -51164,7 +53874,7 @@ module.exports = function isTypedArray(value) { }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":89,"call-bind/callBound":170,"es-abstract/helpers/getOwnPropertyDescriptor":527,"foreach":541,"has-symbols":547}],605:[function(require,module,exports){ +},{"available-typed-arrays":90,"call-bind/callBound":171,"es-abstract/helpers/getOwnPropertyDescriptor":529,"foreach":540,"has-symbols":546}],604:[function(require,module,exports){ 'use strict'; var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null; @@ -51208,7 +53918,7 @@ module.exports = exported || function isWeakMap(x) { return false; }; -},{}],606:[function(require,module,exports){ +},{}],605:[function(require,module,exports){ 'use strict'; var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null; @@ -51252,14 +53962,14 @@ module.exports = exported || function isWeakSet(x) { return false; }; -},{}],607:[function(require,module,exports){ +},{}],606:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],608:[function(require,module,exports){ +},{}],607:[function(require,module,exports){ var hasExcape = /~/ var escapeMatcher = /~[01]/g function escapeReplacer (m) { @@ -51357,7 +54067,7 @@ exports.get = get exports.set = set exports.compile = compile -},{}],609:[function(require,module,exports){ +},{}],608:[function(require,module,exports){ "use strict"; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; @@ -51523,8 +54233,82 @@ function compressQuerySelector(table, selector) { } exports.compressQuerySelector = compressQuerySelector; -},{}],610:[function(require,module,exports){ +},{}],609:[function(require,module,exports){ "use strict"; +var __read = (this && this.__read) || function (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; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createCompressedJsonSchema = void 0; +var util_1 = require("./util"); +var compress_1 = require("./compress"); +function createCompressedJsonSchema(compressionTable, schema) { + if (schema.type === 'array' && schema.items) { + var cloned = util_1.flatClone(schema); + if (Array.isArray(schema.items)) { + var newItems = schema.items.map(function (item) { return createCompressedJsonSchema(compressionTable, item); }); + cloned.items = newItems; + } + else { + var newItems = createCompressedJsonSchema(compressionTable, schema.items); + cloned.items = newItems; + } + return cloned; + } + else if (schema.type === 'object' && schema.properties) { + var cloned = util_1.flatClone(schema); + // compress all property names + var newProperties_1 = {}; + Object.entries(schema.properties).forEach(function (_a) { + var _b = __read(_a, 2), key = _b[0], property = _b[1]; + var compressedKey = compress_1.compressedPath(compressionTable, key); + newProperties_1[compressedKey] = createCompressedJsonSchema(compressionTable, property); + }); + cloned.properties = newProperties_1; + // also compress the required array + if (cloned.required) { + cloned.required = cloned.required.map(function (key) { return compress_1.compressedPath(compressionTable, key); }); + } + return cloned; + } + else { + // no deeper fields in the schema + return schema; + } +} +exports.createCompressedJsonSchema = createCompressedJsonSchema; + +},{"./compress":608,"./util":613}],610:[function(require,module,exports){ +"use strict"; +var __read = (this && this.__read) || function (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; +}; Object.defineProperty(exports, "__esModule", { value: true }); exports.uncompressedToCompressedTable = exports.compressedToUncompressedTable = exports.getPropertiesOfSchema = exports.createCompressionTable = exports.DEFAULT_COMPRESSION_FLAG = void 0; var util_1 = require("./util"); @@ -51547,6 +54331,10 @@ function createCompressionTable(schema, compressionFlag, ignoreProperties) { return compressionTable; } exports.createCompressionTable = createCompressionTable; +/** + * Returns a list of all property names that occur in the schema. + * @returns Set of strings to ensure uniqueness. + */ function getPropertiesOfSchema(schema) { var ret = new Set(); function addSchema(innerSchema) { @@ -51554,11 +54342,12 @@ function getPropertiesOfSchema(schema) { Array.from(keys).forEach(function (k) { return ret.add(k); }); } if (schema.properties) { - Object.keys(schema.properties).forEach(function (property) { + Object.entries(schema.properties).forEach(function (_a) { + var _b = __read(_a, 2), property = _b[0], deepSchema = _b[1]; ret.add(property); - if (!schema.properties) + if (!schema.properties) { return; - var deepSchema = schema.properties[property]; + } addSchema(deepSchema); }); } @@ -51602,7 +54391,7 @@ function uncompressedToCompressedTable(table, compressionFlag, ignoreProperties) } exports.uncompressedToCompressedTable = uncompressedToCompressedTable; -},{"./util":614}],611:[function(require,module,exports){ +},{"./util":613}],611:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decompressedKey = exports.decompressedPath = exports.decompressObject = void 0; @@ -51661,18 +54450,8 @@ exports.decompressedKey = decompressedKey; },{}],612:[function(require,module,exports){ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); -}; Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./types"), exports); +exports.createCompressedJsonSchema = exports.decompressedPath = exports.decompressObject = exports.compressQuery = exports.compressQuerySelector = exports.compressedPath = exports.compressObject = exports.DEFAULT_COMPRESSION_FLAG = exports.createCompressionTable = void 0; var create_compression_table_1 = require("./create-compression-table"); Object.defineProperty(exports, "createCompressionTable", { enumerable: true, get: function () { return create_compression_table_1.createCompressionTable; } }); Object.defineProperty(exports, "DEFAULT_COMPRESSION_FLAG", { enumerable: true, get: function () { return create_compression_table_1.DEFAULT_COMPRESSION_FLAG; } }); @@ -51684,15 +54463,13 @@ Object.defineProperty(exports, "compressQuery", { enumerable: true, get: functio var decompress_1 = require("./decompress"); Object.defineProperty(exports, "decompressObject", { enumerable: true, get: function () { return decompress_1.decompressObject; } }); Object.defineProperty(exports, "decompressedPath", { enumerable: true, get: function () { return decompress_1.decompressedPath; } }); +var create_compressed_json_schema_1 = require("./create-compressed-json-schema"); +Object.defineProperty(exports, "createCompressedJsonSchema", { enumerable: true, get: function () { return create_compressed_json_schema_1.createCompressedJsonSchema; } }); -},{"./compress":609,"./create-compression-table":610,"./decompress":611,"./types":613}],613:[function(require,module,exports){ +},{"./compress":608,"./create-compressed-json-schema":609,"./create-compression-table":610,"./decompress":611}],613:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - -},{}],614:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.alphabeticCompare = exports.numberToLetter = void 0; +exports.flatClone = exports.alphabeticCompare = exports.numberToLetter = void 0; /** * @link https://de.wikipedia.org/wiki/Base58 * this does not start with the numbers to generate valid variable-names @@ -51716,7 +54493,7 @@ function numberToLetter(nr) { .join(''); } exports.numberToLetter = numberToLetter; -exports.alphabeticCompare = function (a, b) { +var alphabeticCompare = function (a, b) { if (a < b) { return -1; } @@ -51725,8 +54502,18 @@ exports.alphabeticCompare = function (a, b) { } return 0; }; +exports.alphabeticCompare = alphabeticCompare; +/** + * does a flat copy on the objects, + * is about 3 times faster then using deepClone + * @link https://jsperf.com/object-rest-spread-vs-clone/2 + */ +function flatClone(obj) { + return Object.assign({}, obj); +} +exports.flatClone = flatClone; -},{}],615:[function(require,module,exports){ +},{}],614:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var HashBase = require('hash-base') @@ -51874,7 +54661,7 @@ function fnI (a, b, c, d, m, k, s) { module.exports = MD5 -},{"hash-base":550,"inherits":587,"safe-buffer":909}],616:[function(require,module,exports){ +},{"hash-base":549,"inherits":586,"safe-buffer":909}],615:[function(require,module,exports){ var bn = require('bn.js'); var brorand = require('brorand'); @@ -51991,9 +54778,9 @@ MillerRabin.prototype.getDivisor = function getDivisor(n, k) { return false; }; -},{"bn.js":617,"brorand":123}],617:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"buffer":124,"dup":88}],618:[function(require,module,exports){ +},{"bn.js":616,"brorand":124}],616:[function(require,module,exports){ +arguments[4][89][0].apply(exports,arguments) +},{"buffer":125,"dup":89}],617:[function(require,module,exports){ module.exports = assert; function assert(val, msg) { @@ -52006,7 +54793,7 @@ assert.equal = function assertEqual(l, r, msg) { throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; -},{}],619:[function(require,module,exports){ +},{}],618:[function(require,module,exports){ 'use strict'; var utils = exports; @@ -52066,7 +54853,7 @@ utils.encode = function encode(arr, enc) { return arr; }; -},{}],620:[function(require,module,exports){ +},{}],619:[function(require,module,exports){ 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } @@ -52622,7 +55409,7 @@ var MODIFIERS = { module.exports = modify; -},{"clone":173,"deep-equal":621}],621:[function(require,module,exports){ +},{"clone":174,"deep-equal":620}],620:[function(require,module,exports){ var objectKeys = require('object-keys'); var isArguments = require('is-arguments'); var is = require('object-is'); @@ -52736,7 +55523,7 @@ function objEquiv(a, b, opts) { module.exports = deepEqual; -},{"is-arguments":588,"is-date-object":591,"is-regex":600,"object-is":624,"object-keys":628,"regexp.prototype.flags":680}],622:[function(require,module,exports){ +},{"is-arguments":587,"is-date-object":590,"is-regex":599,"object-is":623,"object-keys":627,"regexp.prototype.flags":680}],621:[function(require,module,exports){ var hasMap = typeof Map === 'function' && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; @@ -53206,7 +55993,7 @@ function arrObjKeys(obj, inspect) { return xs; } -},{"./util.inspect":124}],623:[function(require,module,exports){ +},{"./util.inspect":125}],622:[function(require,module,exports){ 'use strict'; var numberIsNaN = function (value) { @@ -53227,7 +56014,7 @@ module.exports = function is(a, b) { }; -},{}],624:[function(require,module,exports){ +},{}],623:[function(require,module,exports){ 'use strict'; var define = require('define-properties'); @@ -53247,7 +56034,7 @@ define(polyfill, { module.exports = polyfill; -},{"./implementation":623,"./polyfill":625,"./shim":626,"call-bind":171,"define-properties":497}],625:[function(require,module,exports){ +},{"./implementation":622,"./polyfill":624,"./shim":625,"call-bind":172,"define-properties":499}],624:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); @@ -53256,7 +56043,7 @@ module.exports = function getPolyfill() { return typeof Object.is === 'function' ? Object.is : implementation; }; -},{"./implementation":623}],626:[function(require,module,exports){ +},{"./implementation":622}],625:[function(require,module,exports){ 'use strict'; var getPolyfill = require('./polyfill'); @@ -53272,7 +56059,7 @@ module.exports = function shimObjectIs() { return polyfill; }; -},{"./polyfill":625,"define-properties":497}],627:[function(require,module,exports){ +},{"./polyfill":624,"define-properties":499}],626:[function(require,module,exports){ 'use strict'; var keysShim; @@ -53396,7 +56183,7 @@ if (!Object.keys) { } module.exports = keysShim; -},{"./isArguments":629}],628:[function(require,module,exports){ +},{"./isArguments":628}],627:[function(require,module,exports){ 'use strict'; var slice = Array.prototype.slice; @@ -53430,7 +56217,7 @@ keysShim.shim = function shimObjectKeys() { module.exports = keysShim; -},{"./implementation":627,"./isArguments":629}],629:[function(require,module,exports){ +},{"./implementation":626,"./isArguments":628}],628:[function(require,module,exports){ 'use strict'; var toStr = Object.prototype.toString; @@ -53449,7 +56236,7 @@ module.exports = function isArguments(value) { return isArgs; }; -},{}],630:[function(require,module,exports){ +},{}],629:[function(require,module,exports){ (function (root, factory){ 'use strict'; @@ -53754,7 +56541,7 @@ module.exports = function isArguments(value) { return mod; }); -},{}],631:[function(require,module,exports){ +},{}],630:[function(require,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es6-shim @@ -53798,7 +56585,7 @@ module.exports = function assign(target, source1) { return objTarget; }; -},{"call-bind/callBound":170,"has-symbols/shams":548,"object-keys":628}],632:[function(require,module,exports){ +},{"call-bind/callBound":171,"has-symbols/shams":547,"object-keys":627}],631:[function(require,module,exports){ 'use strict'; var defineProperties = require('define-properties'); @@ -53822,7 +56609,7 @@ defineProperties(bound, { module.exports = bound; -},{"./implementation":631,"./polyfill":633,"./shim":634,"call-bind":171,"define-properties":497}],633:[function(require,module,exports){ +},{"./implementation":630,"./polyfill":632,"./shim":633,"call-bind":172,"define-properties":499}],632:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); @@ -53879,7 +56666,7 @@ module.exports = function getPolyfill() { return Object.assign; }; -},{"./implementation":631}],634:[function(require,module,exports){ +},{"./implementation":630}],633:[function(require,module,exports){ 'use strict'; var define = require('define-properties'); @@ -53895,7 +56682,79 @@ module.exports = function shimAssign() { return polyfill; }; -},{"./polyfill":633,"define-properties":497}],635:[function(require,module,exports){ +},{"./polyfill":632,"define-properties":499}],634:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.now = exports.removeTooOldValues = exports.ObliviousSet = void 0; +/** + * this is a set which automatically forgets + * a given entry when a new entry is set and the ttl + * of the old one is over + */ +var ObliviousSet = /** @class */ (function () { + function ObliviousSet(ttl) { + this.ttl = ttl; + this.set = new Set(); + this.timeMap = new Map(); + } + ObliviousSet.prototype.has = function (value) { + return this.set.has(value); + }; + ObliviousSet.prototype.add = function (value) { + var _this = this; + this.timeMap.set(value, now()); + this.set.add(value); + /** + * When a new value is added, + * start the cleanup at the next tick + * to not block the cpu for more important stuff + * that might happen. + */ + setTimeout(function () { + removeTooOldValues(_this); + }, 0); + }; + ObliviousSet.prototype.clear = function () { + this.set.clear(); + this.timeMap.clear(); + }; + return ObliviousSet; +}()); +exports.ObliviousSet = ObliviousSet; +/** + * Removes all entries from the set + * where the TTL has expired + */ +function removeTooOldValues(obliviousSet) { + var olderThen = now() - obliviousSet.ttl; + var iterator = obliviousSet.set[Symbol.iterator](); + /** + * Because we can assume the new values are added at the bottom, + * we start from the top and stop as soon as we reach a non-too-old value. + */ + while (true) { + var value = iterator.next().value; + if (!value) { + return; // no more elements + } + var time = obliviousSet.timeMap.get(value); + if (time < olderThen) { + obliviousSet.timeMap.delete(value); + obliviousSet.set.delete(value); + } + else { + // We reached a value that is not old enough + return; + } + } +} +exports.removeTooOldValues = removeTooOldValues; +function now() { + return new Date().getTime(); +} +exports.now = now; + +},{}],635:[function(require,module,exports){ module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.2": "aes-128-cbc", "2.16.840.1.101.3.4.1.3": "aes-128-ofb", @@ -54033,7 +56892,7 @@ exports.signature = asn1.define('signature', function () { ) }) -},{"./certificate":637,"asn1.js":74}],637:[function(require,module,exports){ +},{"./certificate":637,"asn1.js":75}],637:[function(require,module,exports){ // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js // thanks to @Rantanen @@ -54124,7 +56983,7 @@ var X509Certificate = asn.define('X509Certificate', function () { module.exports = X509Certificate -},{"asn1.js":74}],638:[function(require,module,exports){ +},{"asn1.js":75}],638:[function(require,module,exports){ // adapted from https://github.com/apatil/pemstrip var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m @@ -54157,7 +57016,7 @@ module.exports = function (okey, password) { } } -},{"browserify-aes":127,"evp_bytestokey":540,"safe-buffer":909}],639:[function(require,module,exports){ +},{"browserify-aes":128,"evp_bytestokey":539,"safe-buffer":909}],639:[function(require,module,exports){ var asn1 = require('./asn1') var aesid = require('./aesid.json') var fixProc = require('./fixProc') @@ -54266,7 +57125,7 @@ function decrypt (data, password) { return Buffer.concat(out) } -},{"./aesid.json":635,"./asn1":636,"./fixProc":638,"browserify-aes":127,"pbkdf2":640,"safe-buffer":909}],640:[function(require,module,exports){ +},{"./aesid.json":635,"./asn1":636,"./fixProc":638,"browserify-aes":128,"pbkdf2":640,"safe-buffer":909}],640:[function(require,module,exports){ exports.pbkdf2 = require('./lib/async') exports.pbkdf2Sync = require('./lib/sync') @@ -54536,7 +57395,7 @@ function pbkdf2 (password, salt, iterations, keylen, digest) { module.exports = pbkdf2 -},{"./default-encoding":642,"./precondition":643,"./to-buffer":645,"create-hash/md5":481,"ripemd160":683,"safe-buffer":909,"sha.js":912}],645:[function(require,module,exports){ +},{"./default-encoding":642,"./precondition":643,"./to-buffer":645,"create-hash/md5":482,"ripemd160":683,"safe-buffer":909,"sha.js":912}],645:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer module.exports = function (thing, encoding, name) { @@ -56747,7 +59606,7 @@ function index (PouchDB) { module.exports = index; }).call(this)}).call(this,require('_process')) -},{"_process":667,"argsarray":71,"pouchdb-binary-utils":650,"pouchdb-errors":656,"pouchdb-fetch":657,"pouchdb-utils":666}],648:[function(require,module,exports){ +},{"_process":667,"argsarray":73,"pouchdb-binary-utils":650,"pouchdb-errors":656,"pouchdb-fetch":657,"pouchdb-utils":666}],648:[function(require,module,exports){ 'use strict'; var pouchdbAdapterUtils = require('pouchdb-adapter-utils'); @@ -61691,7 +64550,7 @@ PouchDB.version = version; module.exports = PouchDB; -},{"argsarray":71,"events":539,"inherits":587,"pouchdb-changes-filter":651,"pouchdb-collections":654,"pouchdb-errors":656,"pouchdb-fetch":657,"pouchdb-merge":663,"pouchdb-utils":666}],656:[function(require,module,exports){ +},{"argsarray":73,"events":538,"inherits":586,"pouchdb-changes-filter":651,"pouchdb-collections":654,"pouchdb-errors":656,"pouchdb-fetch":657,"pouchdb-merge":663,"pouchdb-utils":666}],656:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); @@ -61819,7 +64678,7 @@ exports.INVALID_URL = INVALID_URL; exports.createError = createError; exports.generateErrorFromResponse = generateErrorFromResponse; -},{"inherits":587}],657:[function(require,module,exports){ +},{"inherits":586}],657:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); @@ -63506,7 +66365,7 @@ exports.QueryParseError = QueryParseError; exports.NotFoundError = NotFoundError; exports.BuiltInError = BuiltInError; -},{"argsarray":71,"inherits":587,"pouchdb-collections":654,"pouchdb-utils":666}],662:[function(require,module,exports){ +},{"argsarray":73,"inherits":586,"pouchdb-collections":654,"pouchdb-utils":666}],662:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); @@ -65092,7 +67951,7 @@ function replication(PouchDB) { module.exports = replication; -},{"events":539,"inherits":587,"pouchdb-checkpointer":652,"pouchdb-errors":656,"pouchdb-generate-replication-id":659,"pouchdb-utils":666}],665:[function(require,module,exports){ +},{"events":538,"inherits":586,"pouchdb-checkpointer":652,"pouchdb-errors":656,"pouchdb-generate-replication-id":659,"pouchdb-utils":666}],665:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); @@ -66509,7 +69368,7 @@ exports.toPromise = toPromise; exports.upsert = upsert; exports.uuid = uuid$1; -},{"argsarray":71,"events":539,"immediate":581,"inherits":587,"pouchdb-collections":654,"pouchdb-errors":656,"pouchdb-md5":662,"uuid":944}],667:[function(require,module,exports){ +},{"argsarray":73,"events":538,"immediate":580,"inherits":586,"pouchdb-collections":654,"pouchdb-errors":656,"pouchdb-md5":662,"uuid":944}],667:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -66728,9 +69587,9 @@ function i2ops (c) { return out } -},{"create-hash":480,"safe-buffer":909}],670:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"buffer":124,"dup":88}],671:[function(require,module,exports){ +},{"create-hash":481,"safe-buffer":909}],670:[function(require,module,exports){ +arguments[4][89][0].apply(exports,arguments) +},{"buffer":125,"dup":89}],671:[function(require,module,exports){ var parseKeys = require('parse-asn1') var mgf = require('./mgf') var xor = require('./xor') @@ -66837,7 +69696,7 @@ function compare (a, b) { return dif } -},{"./mgf":669,"./withPublic":673,"./xor":674,"bn.js":670,"browserify-rsa":145,"create-hash":480,"parse-asn1":639,"safe-buffer":909}],672:[function(require,module,exports){ +},{"./mgf":669,"./withPublic":673,"./xor":674,"bn.js":670,"browserify-rsa":146,"create-hash":481,"parse-asn1":639,"safe-buffer":909}],672:[function(require,module,exports){ var parseKeys = require('parse-asn1') var randomBytes = require('randombytes') var createHash = require('create-hash') @@ -66927,7 +69786,7 @@ function nonZero (len) { return out } -},{"./mgf":669,"./withPublic":673,"./xor":674,"bn.js":670,"browserify-rsa":145,"create-hash":480,"parse-asn1":639,"randombytes":676,"safe-buffer":909}],673:[function(require,module,exports){ +},{"./mgf":669,"./withPublic":673,"./xor":674,"bn.js":670,"browserify-rsa":146,"create-hash":481,"parse-asn1":639,"randombytes":676,"safe-buffer":909}],673:[function(require,module,exports){ var BN = require('bn.js') var Buffer = require('safe-buffer').Buffer @@ -67956,7 +70815,7 @@ define(flagsBound, { module.exports = flagsBound; -},{"./implementation":679,"./polyfill":681,"./shim":682,"call-bind":171,"define-properties":497}],681:[function(require,module,exports){ +},{"./implementation":679,"./polyfill":681,"./shim":682,"call-bind":172,"define-properties":499}],681:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); @@ -67978,7 +70837,7 @@ module.exports = function getPolyfill() { return implementation; }; -},{"./implementation":679,"define-properties":497}],682:[function(require,module,exports){ +},{"./implementation":679,"define-properties":499}],682:[function(require,module,exports){ 'use strict'; var supportsDescriptors = require('define-properties').supportsDescriptors; @@ -68006,7 +70865,7 @@ module.exports = function shimFlags() { return polyfill; }; -},{"./polyfill":681,"define-properties":497}],683:[function(require,module,exports){ +},{"./polyfill":681,"define-properties":499}],683:[function(require,module,exports){ 'use strict' var Buffer = require('buffer').Buffer var inherits = require('inherits') @@ -68171,7 +71030,7 @@ function fn5 (a, b, c, d, e, m, k, s) { module.exports = RIPEMD160 -},{"buffer":169,"hash-base":550,"inherits":587}],684:[function(require,module,exports){ +},{"buffer":170,"hash-base":549,"inherits":586}],684:[function(require,module,exports){ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -68852,6 +71711,14 @@ var Subject = (function (_super) { this.isStopped = this.closed = true; this.observers = null; }; + Object.defineProperty(Subject.prototype, "observed", { + get: function () { + var _a; + return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0; + }, + enumerable: false, + configurable: true + }); Subject.prototype._trySubscribe = function (subscriber) { this._throwIfClosed(); return _super.prototype._trySubscribe.call(this, subscriber); @@ -71739,11 +74606,19 @@ var __extends = (this && this.__extends) || (function () { Object.defineProperty(exports, "__esModule", { value: true }); exports.groupBy = void 0; var Observable_1 = require("../Observable"); +var from_1 = require("../observable/from"); var Subject_1 = require("../Subject"); var lift_1 = require("../util/lift"); var OperatorSubscriber_1 = require("./OperatorSubscriber"); -function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) { +function groupBy(keySelector, elementOrOptions, duration, connector) { return lift_1.operate(function (source, subscriber) { + var element; + if (!elementOrOptions || typeof elementOrOptions === 'function') { + element = elementOrOptions; + } + else { + (duration = elementOrOptions.duration, element = elementOrOptions.element, connector = elementOrOptions.connector); + } var groups = new Map(); var notify = function (cb) { groups.forEach(cb); @@ -71755,18 +74630,18 @@ function groupBy(keySelector, elementSelector, durationSelector, subjectSelector var key_1 = keySelector(value); var group_1 = groups.get(key_1); if (!group_1) { - groups.set(key_1, (group_1 = subjectSelector ? subjectSelector() : new Subject_1.Subject())); + groups.set(key_1, (group_1 = connector ? connector() : new Subject_1.Subject())); var grouped = createGroupedObservable(key_1, group_1); subscriber.next(grouped); - if (durationSelector) { + if (duration) { var durationSubscriber_1 = new OperatorSubscriber_1.OperatorSubscriber(group_1, function () { group_1.complete(); durationSubscriber_1 === null || durationSubscriber_1 === void 0 ? void 0 : durationSubscriber_1.unsubscribe(); }, undefined, undefined, function () { return groups.delete(key_1); }); - groupBySourceSubscriber.add(durationSelector(grouped).subscribe(durationSubscriber_1)); + groupBySourceSubscriber.add(from_1.innerFrom(duration(grouped)).subscribe(durationSubscriber_1)); } } - group_1.next(elementSelector ? elementSelector(value) : value); + group_1.next(element ? element(value) : value); } catch (err) { handleError(err); @@ -71805,7 +74680,7 @@ var GroupBySubscriber = (function (_super) { return GroupBySubscriber; }(OperatorSubscriber_1.OperatorSubscriber)); -},{"../Observable":689,"../Subject":692,"../util/lift":901,"./OperatorSubscriber":729}],772:[function(require,module,exports){ +},{"../Observable":689,"../Subject":692,"../observable/from":709,"../util/lift":901,"./OperatorSubscriber":729}],772:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ignoreElements = void 0; @@ -72313,7 +75188,7 @@ var Subject_1 = require("../Subject"); var multicast_1 = require("./multicast"); var connect_1 = require("./connect"); function publish(selector) { - return selector ? connect_1.connect(selector) : multicast_1.multicast(new Subject_1.Subject()); + return selector ? function (source) { return connect_1.connect(selector)(source); } : function (source) { return multicast_1.multicast(new Subject_1.Subject())(source); }; } exports.publish = publish; @@ -72324,8 +75199,10 @@ exports.publishBehavior = void 0; var BehaviorSubject_1 = require("../BehaviorSubject"); var ConnectableObservable_1 = require("../observable/ConnectableObservable"); function publishBehavior(initialValue) { - var subject = new BehaviorSubject_1.BehaviorSubject(initialValue); - return function (source) { return new ConnectableObservable_1.ConnectableObservable(source, function () { return subject; }); }; + return function (source) { + var subject = new BehaviorSubject_1.BehaviorSubject(initialValue); + return new ConnectableObservable_1.ConnectableObservable(source, function () { return subject; }); + }; } exports.publishBehavior = publishBehavior; @@ -72336,8 +75213,10 @@ exports.publishLast = void 0; var AsyncSubject_1 = require("../AsyncSubject"); var ConnectableObservable_1 = require("../observable/ConnectableObservable"); function publishLast() { - var subject = new AsyncSubject_1.AsyncSubject(); - return function (source) { return new ConnectableObservable_1.ConnectableObservable(source, function () { return subject; }); }; + return function (source) { + var subject = new AsyncSubject_1.AsyncSubject(); + return new ConnectableObservable_1.ConnectableObservable(source, function () { return subject; }); + }; } exports.publishLast = publishLast; @@ -72353,8 +75232,7 @@ function publishReplay(bufferSize, windowTime, selectorOrScheduler, timestampPro timestampProvider = selectorOrScheduler; } var selector = isFunction_1.isFunction(selectorOrScheduler) ? selectorOrScheduler : undefined; - var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, timestampProvider); - return function (source) { return multicast_1.multicast(subject, selector)(source); }; + return function (source) { return multicast_1.multicast(new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, timestampProvider), selector)(source); }; } exports.publishReplay = publishReplay; @@ -72787,63 +75665,110 @@ function createState() { },{"../util/lift":901,"./OperatorSubscriber":729}],811:[function(require,module,exports){ "use strict"; +var __read = (this && this.__read) || function (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; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; Object.defineProperty(exports, "__esModule", { value: true }); exports.share = void 0; +var from_1 = require("../observable/from"); +var take_1 = require("../operators/take"); var Subject_1 = require("../Subject"); var Subscriber_1 = require("../Subscriber"); -var from_1 = require("../observable/from"); var lift_1 = require("../util/lift"); function share(options) { - options = options || {}; - var _a = options.connector, connector = _a === void 0 ? function () { return new Subject_1.Subject(); } : _a, _b = options.resetOnComplete, resetOnComplete = _b === void 0 ? true : _b, _c = options.resetOnError, resetOnError = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d; - var connection = null; - var subject = null; - var refCount = 0; - var hasCompleted = false; - var hasErrored = false; - var reset = function () { - connection = subject = null; - hasCompleted = hasErrored = false; - }; - return lift_1.operate(function (source, subscriber) { - refCount++; - subject = subject !== null && subject !== void 0 ? subject : connector(); - subscriber.add(function () { - refCount--; - if (resetOnRefCountZero && !refCount && !hasErrored && !hasCompleted) { - var conn = connection; - reset(); - conn === null || conn === void 0 ? void 0 : conn.unsubscribe(); + if (options === void 0) { options = {}; } + var _a = options.connector, connector = _a === void 0 ? function () { return new Subject_1.Subject(); } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? true : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d; + return function (wrapperSource) { + var connection = null; + var resetConnection = null; + var subject = null; + var refCount = 0; + var hasCompleted = false; + var hasErrored = false; + var cancelReset = function () { + resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe(); + resetConnection = null; + }; + var reset = function () { + cancelReset(); + connection = subject = null; + hasCompleted = hasErrored = false; + }; + var resetAndUnsubscribe = function () { + var conn = connection; + reset(); + conn === null || conn === void 0 ? void 0 : conn.unsubscribe(); + }; + return lift_1.operate(function (source, subscriber) { + refCount++; + if (!hasErrored && !hasCompleted) { + cancelReset(); } - }); - subject.subscribe(subscriber); - if (!connection) { - connection = new Subscriber_1.SafeSubscriber({ - next: function (value) { return subject.next(value); }, - error: function (err) { - hasErrored = true; - var dest = subject; - if (resetOnError) { - reset(); - } - dest.error(err); - }, - complete: function () { - hasCompleted = true; - var dest = subject; - if (resetOnComplete) { - reset(); - } - dest.complete(); - }, + var dest = (subject = subject !== null && subject !== void 0 ? subject : connector()); + subscriber.add(function () { + refCount--; + if (refCount === 0 && !hasErrored && !hasCompleted) { + resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero); + } }); - from_1.from(source).subscribe(connection); - } - }); + dest.subscribe(subscriber); + if (!connection) { + connection = new Subscriber_1.SafeSubscriber({ + next: function (value) { return dest.next(value); }, + error: function (err) { + hasErrored = true; + cancelReset(); + resetConnection = handleReset(reset, resetOnError, err); + dest.error(err); + }, + complete: function () { + hasCompleted = true; + cancelReset(); + resetConnection = handleReset(reset, resetOnComplete); + dest.complete(); + }, + }); + from_1.from(source).subscribe(connection); + } + })(wrapperSource); + }; } exports.share = share; +function handleReset(reset, on) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (on === true) { + reset(); + return null; + } + if (on === false) { + return null; + } + return on.apply(void 0, __spreadArray([], __read(args))).pipe(take_1.take(1)) + .subscribe(function () { return reset(); }); +} -},{"../Subject":692,"../Subscriber":693,"../observable/from":709,"../util/lift":901}],812:[function(require,module,exports){ +},{"../Subject":692,"../Subscriber":693,"../observable/from":709,"../operators/take":824,"../util/lift":901}],812:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shareReplay = void 0; @@ -74970,8 +77895,10 @@ exports.observable = void 0; exports.observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })(); },{}],875:[function(require,module,exports){ -arguments[4][613][0].apply(exports,arguments) -},{"dup":613}],876:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); + +},{}],876:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ArgumentOutOfRangeError = void 0; @@ -75806,7 +78733,7 @@ SafeBuffer.allocUnsafeSlow = function (size) { return buffer.SlowBuffer(size) } -},{"buffer":169}],910:[function(require,module,exports){ +},{"buffer":170}],910:[function(require,module,exports){ (function (process){(function (){ /* eslint-disable node/no-deprecated-api */ @@ -75887,7 +78814,7 @@ if (!safer.constants) { module.exports = safer }).call(this)}).call(this,require('_process')) -},{"_process":667,"buffer":169}],911:[function(require,module,exports){ +},{"_process":667,"buffer":170}],911:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer // prototype class for hash functions @@ -76083,7 +79010,7 @@ Sha.prototype._hash = function () { module.exports = Sha -},{"./hash":911,"inherits":587,"safe-buffer":909}],914:[function(require,module,exports){ +},{"./hash":911,"inherits":586,"safe-buffer":909}],914:[function(require,module,exports){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 @@ -76184,7 +79111,7 @@ Sha1.prototype._hash = function () { module.exports = Sha1 -},{"./hash":911,"inherits":587,"safe-buffer":909}],915:[function(require,module,exports){ +},{"./hash":911,"inherits":586,"safe-buffer":909}],915:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 @@ -76239,7 +79166,7 @@ Sha224.prototype._hash = function () { module.exports = Sha224 -},{"./hash":911,"./sha256":916,"inherits":587,"safe-buffer":909}],916:[function(require,module,exports){ +},{"./hash":911,"./sha256":916,"inherits":586,"safe-buffer":909}],916:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 @@ -76376,7 +79303,7 @@ Sha256.prototype._hash = function () { module.exports = Sha256 -},{"./hash":911,"inherits":587,"safe-buffer":909}],917:[function(require,module,exports){ +},{"./hash":911,"inherits":586,"safe-buffer":909}],917:[function(require,module,exports){ var inherits = require('inherits') var SHA512 = require('./sha512') var Hash = require('./hash') @@ -76435,7 +79362,7 @@ Sha384.prototype._hash = function () { module.exports = Sha384 -},{"./hash":911,"./sha512":918,"inherits":587,"safe-buffer":909}],918:[function(require,module,exports){ +},{"./hash":911,"./sha512":918,"inherits":586,"safe-buffer":909}],918:[function(require,module,exports){ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer @@ -76697,7 +79624,7 @@ Sha512.prototype._hash = function () { module.exports = Sha512 -},{"./hash":911,"inherits":587,"safe-buffer":909}],919:[function(require,module,exports){ +},{"./hash":911,"inherits":586,"safe-buffer":909}],919:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('get-intrinsic'); @@ -76823,7 +79750,7 @@ module.exports = function getSideChannel() { return channel; }; -},{"call-bind/callBound":170,"get-intrinsic":546,"object-inspect":622}],920:[function(require,module,exports){ +},{"call-bind/callBound":171,"get-intrinsic":545,"object-inspect":621}],920:[function(require,module,exports){ (function (factory) { if (typeof exports === 'object') { // Node/CommonJS @@ -77707,35 +80634,35 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":539,"inherits":587,"readable-stream/lib/_stream_duplex.js":923,"readable-stream/lib/_stream_passthrough.js":924,"readable-stream/lib/_stream_readable.js":925,"readable-stream/lib/_stream_transform.js":926,"readable-stream/lib/_stream_writable.js":927,"readable-stream/lib/internal/streams/end-of-stream.js":931,"readable-stream/lib/internal/streams/pipeline.js":933}],922:[function(require,module,exports){ -arguments[4][152][0].apply(exports,arguments) -},{"dup":152}],923:[function(require,module,exports){ +},{"events":538,"inherits":586,"readable-stream/lib/_stream_duplex.js":923,"readable-stream/lib/_stream_passthrough.js":924,"readable-stream/lib/_stream_readable.js":925,"readable-stream/lib/_stream_transform.js":926,"readable-stream/lib/_stream_writable.js":927,"readable-stream/lib/internal/streams/end-of-stream.js":931,"readable-stream/lib/internal/streams/pipeline.js":933}],922:[function(require,module,exports){ arguments[4][153][0].apply(exports,arguments) -},{"./_stream_readable":925,"./_stream_writable":927,"_process":667,"dup":153,"inherits":587}],924:[function(require,module,exports){ +},{"dup":153}],923:[function(require,module,exports){ arguments[4][154][0].apply(exports,arguments) -},{"./_stream_transform":926,"dup":154,"inherits":587}],925:[function(require,module,exports){ +},{"./_stream_readable":925,"./_stream_writable":927,"_process":667,"dup":154,"inherits":586}],924:[function(require,module,exports){ arguments[4][155][0].apply(exports,arguments) -},{"../errors":922,"./_stream_duplex":923,"./internal/streams/async_iterator":928,"./internal/streams/buffer_list":929,"./internal/streams/destroy":930,"./internal/streams/from":932,"./internal/streams/state":934,"./internal/streams/stream":935,"_process":667,"buffer":169,"dup":155,"events":539,"inherits":587,"string_decoder/":936,"util":124}],926:[function(require,module,exports){ +},{"./_stream_transform":926,"dup":155,"inherits":586}],925:[function(require,module,exports){ arguments[4][156][0].apply(exports,arguments) -},{"../errors":922,"./_stream_duplex":923,"dup":156,"inherits":587}],927:[function(require,module,exports){ +},{"../errors":922,"./_stream_duplex":923,"./internal/streams/async_iterator":928,"./internal/streams/buffer_list":929,"./internal/streams/destroy":930,"./internal/streams/from":932,"./internal/streams/state":934,"./internal/streams/stream":935,"_process":667,"buffer":170,"dup":156,"events":538,"inherits":586,"string_decoder/":936,"util":125}],926:[function(require,module,exports){ arguments[4][157][0].apply(exports,arguments) -},{"../errors":922,"./_stream_duplex":923,"./internal/streams/destroy":930,"./internal/streams/state":934,"./internal/streams/stream":935,"_process":667,"buffer":169,"dup":157,"inherits":587,"util-deprecate":939}],928:[function(require,module,exports){ +},{"../errors":922,"./_stream_duplex":923,"dup":157,"inherits":586}],927:[function(require,module,exports){ arguments[4][158][0].apply(exports,arguments) -},{"./end-of-stream":931,"_process":667,"dup":158}],929:[function(require,module,exports){ +},{"../errors":922,"./_stream_duplex":923,"./internal/streams/destroy":930,"./internal/streams/state":934,"./internal/streams/stream":935,"_process":667,"buffer":170,"dup":158,"inherits":586,"util-deprecate":939}],928:[function(require,module,exports){ arguments[4][159][0].apply(exports,arguments) -},{"buffer":169,"dup":159,"util":124}],930:[function(require,module,exports){ +},{"./end-of-stream":931,"_process":667,"dup":159}],929:[function(require,module,exports){ arguments[4][160][0].apply(exports,arguments) -},{"_process":667,"dup":160}],931:[function(require,module,exports){ +},{"buffer":170,"dup":160,"util":125}],930:[function(require,module,exports){ arguments[4][161][0].apply(exports,arguments) -},{"../../../errors":922,"dup":161}],932:[function(require,module,exports){ +},{"_process":667,"dup":161}],931:[function(require,module,exports){ arguments[4][162][0].apply(exports,arguments) -},{"dup":162}],933:[function(require,module,exports){ +},{"../../../errors":922,"dup":162}],932:[function(require,module,exports){ arguments[4][163][0].apply(exports,arguments) -},{"../../../errors":922,"./end-of-stream":931,"dup":163}],934:[function(require,module,exports){ +},{"dup":163}],933:[function(require,module,exports){ arguments[4][164][0].apply(exports,arguments) -},{"../../../errors":922,"dup":164}],935:[function(require,module,exports){ +},{"../../../errors":922,"./end-of-stream":931,"dup":164}],934:[function(require,module,exports){ arguments[4][165][0].apply(exports,arguments) -},{"dup":165,"events":539}],936:[function(require,module,exports){ +},{"../../../errors":922,"dup":165}],935:[function(require,module,exports){ +arguments[4][166][0].apply(exports,arguments) +},{"dup":166,"events":538}],936:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -78146,7 +81073,7 @@ var _default = { getSize: getSize }; exports["default"] = _default; -},{"./browser.js":937,"./node.js":124,"@babel/runtime/helpers/interopRequireDefault":65,"detect-node":504}],939:[function(require,module,exports){ +},{"./browser.js":937,"./node.js":125,"@babel/runtime/helpers/interopRequireDefault":67,"detect-node":506}],939:[function(require,module,exports){ (function (global){(function (){ /** @@ -78462,21 +81389,23 @@ function isDataView(value) { } exports.isDataView = isDataView; +// Store a copy of SharedArrayBuffer in case it's deleted elsewhere +var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; function isSharedArrayBufferToString(value) { return ObjectToString(value) === '[object SharedArrayBuffer]'; } -isSharedArrayBufferToString.working = ( - typeof SharedArrayBuffer !== 'undefined' && - isSharedArrayBufferToString(new SharedArrayBuffer()) -); function isSharedArrayBuffer(value) { - if (typeof SharedArrayBuffer === 'undefined') { + if (typeof SharedArrayBufferCopy === 'undefined') { return false; } + if (typeof isSharedArrayBufferToString.working === 'undefined') { + isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); + } + return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBuffer; + : value instanceof SharedArrayBufferCopy; } exports.isSharedArrayBuffer = isSharedArrayBuffer; @@ -78558,7 +81487,7 @@ exports.isAnyArrayBuffer = isAnyArrayBuffer; }); }); -},{"is-arguments":588,"is-generator-function":593,"is-typed-array":604,"which-typed-array":956}],942:[function(require,module,exports){ +},{"is-arguments":587,"is-generator-function":592,"is-typed-array":603,"which-typed-array":956}],942:[function(require,module,exports){ (function (process){(function (){ // Copyright Joyent, Inc. and other Node contributors. // @@ -79277,7 +82206,7 @@ function callbackify(original) { exports.callbackify = callbackify; }).call(this)}).call(this,require('_process')) -},{"./support/isBuffer":940,"./support/types":941,"_process":667,"inherits":587}],943:[function(require,module,exports){ +},{"./support/isBuffer":940,"./support/types":941,"_process":667,"inherits":586}],943:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -80162,7 +83091,7 @@ module.exports = function whichBoxedPrimitive(value) { } }; -},{"is-bigint":589,"is-boolean-object":590,"is-number-object":598,"is-string":602,"is-symbol":603}],955:[function(require,module,exports){ +},{"is-bigint":588,"is-boolean-object":589,"is-number-object":597,"is-string":601,"is-symbol":602}],955:[function(require,module,exports){ 'use strict'; var isMap = require('is-map'); @@ -80188,7 +83117,7 @@ module.exports = function whichCollection(value) { return false; }; -},{"is-map":594,"is-set":601,"is-weakmap":605,"is-weakset":606}],956:[function(require,module,exports){ +},{"is-map":593,"is-set":600,"is-weakmap":604,"is-weakset":605}],956:[function(require,module,exports){ (function (global){(function (){ 'use strict'; @@ -80248,7 +83177,7 @@ module.exports = function whichTypedArray(value) { }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":89,"call-bind/callBound":170,"es-abstract/helpers/getOwnPropertyDescriptor":527,"foreach":541,"has-symbols":547,"is-typed-array":604}],957:[function(require,module,exports){ +},{"available-typed-arrays":90,"call-bind/callBound":171,"es-abstract/helpers/getOwnPropertyDescriptor":529,"foreach":540,"has-symbols":546,"is-typed-array":603}],957:[function(require,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; diff --git a/dist/rxdb.browserify.min.js b/dist/rxdb.browserify.min.js index 9a50b6a3af7..941703ca079 100644 --- a/dist/rxdb.browserify.min.js +++ b/dist/rxdb.browserify.min.js @@ -1,12 +1,12 @@ -!function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=r[a]={exports:{}};t[a][0].call(f.exports,(function(e){return i(t[a][1][e]||e)}),f,f.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;athis.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return e0;){t--;var r=this.buffer[t];if(r.documentData&&r.documentData._rev===e)return!0}return!1},t.destroy=function(){this.subs.forEach((function(e){return e.unsubscribe()}))},e}();r.ChangeEventBuffer=n},{}],3:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={addRxPlugin:!0,PouchDB:!0,validateCouchDBString:!0,getBatch:!0,countAllUndeleted:!0,getNewestSequence:!0,createRxDatabase:!0,removeRxDatabase:!0,checkAdapter:!0,isRxDatabase:!0,dbCount:!0,_collectionNamePrimary:!0,isRxCollection:!0,_createRxCollection:!0,isRxDocument:!0,getDocumentOrmPrototype:!0,getDocumentPrototype:!0,isRxQuery:!0,isRxSchema:!0,createRxSchema:!0,RxSchema:!0,getIndexes:!0,normalize:!0,getFinalFields:!0,getPreviousVersions:!0,RxChangeEvent:!0,getRxStoragePouchDb:!0,getPouchLocation:!0,_clearHook:!0,createCrypter:!0};Object.defineProperty(r,"addRxPlugin",{enumerable:!0,get:function(){return i.addRxPlugin}}),Object.defineProperty(r,"PouchDB",{enumerable:!0,get:function(){return o.PouchDB}}),Object.defineProperty(r,"validateCouchDBString",{enumerable:!0,get:function(){return o.validateCouchDBString}}),Object.defineProperty(r,"getBatch",{enumerable:!0,get:function(){return o.getBatch}}),Object.defineProperty(r,"countAllUndeleted",{enumerable:!0,get:function(){return o.countAllUndeleted}}),Object.defineProperty(r,"getNewestSequence",{enumerable:!0,get:function(){return o.getNewestSequence}}),Object.defineProperty(r,"createRxDatabase",{enumerable:!0,get:function(){return a.createRxDatabase}}),Object.defineProperty(r,"removeRxDatabase",{enumerable:!0,get:function(){return a.removeRxDatabase}}),Object.defineProperty(r,"checkAdapter",{enumerable:!0,get:function(){return a.checkAdapter}}),Object.defineProperty(r,"isRxDatabase",{enumerable:!0,get:function(){return a.isInstanceOf}}),Object.defineProperty(r,"dbCount",{enumerable:!0,get:function(){return a.dbCount}}),Object.defineProperty(r,"_collectionNamePrimary",{enumerable:!0,get:function(){return a._collectionNamePrimary}}),Object.defineProperty(r,"isRxCollection",{enumerable:!0,get:function(){return s.isInstanceOf}}),Object.defineProperty(r,"_createRxCollection",{enumerable:!0,get:function(){return s.create}}),Object.defineProperty(r,"isRxDocument",{enumerable:!0,get:function(){return u.isInstanceOf}}),Object.defineProperty(r,"getDocumentOrmPrototype",{enumerable:!0,get:function(){return c.getDocumentOrmPrototype}}),Object.defineProperty(r,"getDocumentPrototype",{enumerable:!0,get:function(){return c.getDocumentPrototype}}),Object.defineProperty(r,"isRxQuery",{enumerable:!0,get:function(){return f.isInstanceOf}}),Object.defineProperty(r,"isRxSchema",{enumerable:!0,get:function(){return l.isInstanceOf}}),Object.defineProperty(r,"createRxSchema",{enumerable:!0,get:function(){return l.createRxSchema}}),Object.defineProperty(r,"RxSchema",{enumerable:!0,get:function(){return l.RxSchema}}),Object.defineProperty(r,"getIndexes",{enumerable:!0,get:function(){return l.getIndexes}}),Object.defineProperty(r,"normalize",{enumerable:!0,get:function(){return l.normalize}}),Object.defineProperty(r,"getFinalFields",{enumerable:!0,get:function(){return l.getFinalFields}}),Object.defineProperty(r,"getPreviousVersions",{enumerable:!0,get:function(){return l.getPreviousVersions}}),Object.defineProperty(r,"RxChangeEvent",{enumerable:!0,get:function(){return d.RxChangeEvent}}),Object.defineProperty(r,"getRxStoragePouchDb",{enumerable:!0,get:function(){return h.getRxStoragePouchDb}}),Object.defineProperty(r,"getPouchLocation",{enumerable:!0,get:function(){return h.getPouchLocation}}),Object.defineProperty(r,"_clearHook",{enumerable:!0,get:function(){return p._clearHook}}),Object.defineProperty(r,"createCrypter",{enumerable:!0,get:function(){return b.createCrypter}}),e("./types/modules/crypto-js.d"),e("./types/modules/graphql-client.d"),e("./types/modules/mocha.parallel.d"),e("./types/modules/modifiyjs.d"),e("./types/modules/pouchdb-selector-core.d"),e("./types/modules/random-token.d");var i=e("./plugin"),o=e("./pouch-db"),a=e("./rx-database"),s=e("./rx-collection"),u=e("./rx-document"),c=e("./rx-document-prototype-merge"),f=e("./rx-query"),l=e("./rx-schema"),d=e("./rx-change-event"),h=e("./rx-storage-pouchdb"),p=e("./hooks"),b=e("./crypter"),v=e("./query-cache");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===v[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return v[e]}}))}));var y=e("./util");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===y[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return y[e]}}))}))},{"./crypter":4,"./hooks":7,"./plugin":10,"./pouch-db":37,"./query-cache":38,"./rx-change-event":39,"./rx-collection":41,"./rx-database":43,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-query":47,"./rx-schema":48,"./rx-storage-pouchdb":49,"./types/modules/crypto-js.d":50,"./types/modules/graphql-client.d":51,"./types/modules/mocha.parallel.d":52,"./types/modules/modifiyjs.d":53,"./types/modules/pouchdb-selector-core.d":54,"./types/modules/random-token.d":55,"./util":56}],4:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.createCrypter=function(e,t){return new a(e,t)},r.Crypter=void 0;var i=n(e("object-path")),o=e("./util"),a=function(){function e(e,t){this.password=e,this.schema=t}var t=e.prototype;return t._encryptValue=function(e){throw(0,o.pluginMissing)("encryption")},t._decryptValue=function(e){throw(0,o.pluginMissing)("encryption")},t.encrypt=function(e){var t=this;return this.password?(e=(0,o.clone)(e),this.schema.encryptedPaths.forEach((function(r){var n=i.default.get(e,r);if(void 0!==n){var o=t._encryptValue(n);i.default.set(e,r,o)}})),e):e},t.decrypt=function(e){var t=this;return this.password?(e=(0,o.clone)(e),this.schema.encryptedPaths.forEach((function(r){var n=i.default.get(e,r);if(void 0!==n){var o=t._decryptValue(n);i.default.set(e,r,o)}})),e):e},e}();r.Crypter=a},{"./util":56,"@babel/runtime/helpers/interopRequireDefault":65,"object-path":630}],5:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createDocCache=function(){return new n},r.DocCache=void 0;var n=function(){function e(){this._map=new Map,this._map=new Map}var t=e.prototype;return t.get=function(e){return this._map.get(e)},t.set=function(e,t){return this._map.set(e,t)},t.delete=function(e){return this._map.delete(e)},e}();r.DocCache=n},{}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getSortFieldsOfQuery=i,r.getQueryParams=a,r.calculateNewResults=function(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=a(e),i=e._resultsData.slice(),o=e._resultsDataMap,s=!1;return t.find((function(e){var t=e.toEventReduceChangeEvent(),a=(0,n.calculateActionName)({queryParams:r,changeEvent:t,previousResults:i,keyDocumentMap:o});return"runFullQueryAgain"===a||("doNothing"!==a?(s=!0,(0,n.runAction)(a,r,t,i,o),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:i}},r.RXQUERY_QUERY_PARAMS_CACHE=void 0;var n=e("event-reduce-js");function i(e,t){return t.sort&&0!==t.sort.length?t.sort.map((function(e){return Object.keys(e)[0]})):[e]}var o=new WeakMap;function a(e){if(o.has(e))return o.get(e);var t=e.collection.database.storage,r=e.toJSON(),n=e.collection.schema.primaryPath,a={primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:i(n,r),sortComparator:t.getSortComparator(n,r),queryMatcher:t.getQueryMatcher(n,r)};return o.set(e,a),a}r.RXQUERY_QUERY_PARAMS_CACHE=o},{"event-reduce-js":532}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.runPluginHooks=function(e,t){n[e].forEach((function(e){return e(t)}))},r.runAsyncPluginHooks=function(e,t){return Promise.all(n[e].map((function(e){return e(t)})))},r._clearHook=function(e,t){n[e]=n[e].filter((function(e){return e!==t}))},r.HOOKS=void 0;var n={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],createRxQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreatePouchDb:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[]};r.HOOKS=n},{}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./core");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===n[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return n[e]}}))}));var i=e("./plugins/dev-mode"),o=e("./plugins/validate"),a=e("./plugins/key-compression"),s=e("./plugins/migration"),u=e("./plugins/leader-election"),c=e("./plugins/encryption"),f=e("./plugins/update"),l=e("./plugins/watch-for-changes"),d=e("./plugins/replication"),h=e("./plugins/adapter-check"),p=e("./plugins/json-dump"),b=e("./plugins/in-memory"),v=e("./plugins/attachments"),y=e("./plugins/local-documents"),m=e("./plugins/query-builder");(0,n.addRxPlugin)(i.RxDBDevModePlugin),(0,n.addRxPlugin)(o.RxDBValidatePlugin),(0,n.addRxPlugin)(a.RxDBKeyCompressionPlugin),(0,n.addRxPlugin)(s.RxDBMigrationPlugin),(0,n.addRxPlugin)(u.RxDBLeaderElectionPlugin),(0,n.addRxPlugin)(c.RxDBEncryptionPlugin),(0,n.addRxPlugin)(f.RxDBUpdatePlugin),(0,n.addRxPlugin)(l.RxDBWatchForChangesPlugin),(0,n.addRxPlugin)(d.RxDBReplicationPlugin),(0,n.addRxPlugin)(h.RxDBAdapterCheckPlugin),(0,n.addRxPlugin)(p.RxDBJsonDumpPlugin),(0,n.addRxPlugin)(b.RxDBInMemoryPlugin),(0,n.addRxPlugin)(v.RxDBAttachmentsPlugin),(0,n.addRxPlugin)(y.RxDBLocalDocumentsPlugin),(0,n.addRxPlugin)(m.RxDBQueryBuilderPlugin)},{"./core":3,"./plugins/adapter-check":11,"./plugins/attachments":12,"./plugins/dev-mode":19,"./plugins/encryption":21,"./plugins/in-memory":22,"./plugins/json-dump":23,"./plugins/key-compression":24,"./plugins/leader-election":25,"./plugins/local-documents":26,"./plugins/migration":28,"./plugins/query-builder":30,"./plugins/replication":33,"./plugins/update":34,"./plugins/validate":35,"./plugins/watch-for-changes":36}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.overwritable=void 0;var n=e("./util"),i={isDevMode:function(){return!1},validatePassword:function(e){throw(0,n.pluginMissing)("encryption")},createKeyCompressor:function(e){throw(0,n.pluginMissing)("key-compression")},checkAdapter:function(e){throw(0,n.pluginMissing)("adapter-check")},tunnelErrorMessage:function(e){return"RxDB Error-Code "+e+".\n - To find out what this means, use the dev-mode-plugin https://pubkey.github.io/rxdb/custom-build.html#dev-mode\n - Or search for this code https://github.com/pubkey/rxdb/search?q="+e+"\n "}};r.overwritable=i},{"./util":56}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.addRxPlugin=function(e){if((0,l.runPluginHooks)("preAddRxPlugin",{plugin:e,plugins:h}),h.has(e))return;h.add(e);if(!e.rxdb)return"object"==typeof e&&e.default&&(e=e.default),void c.PouchDB.plugin(e);var t=e;t.prototypes&&Object.entries(e.prototypes).forEach((function(e){var t=e[0];return(0,e[1])(d[t])}));t.overwritable&&Object.assign(f.overwritable,e.overwritable);t.hooks&&Object.entries(e.hooks).forEach((function(e){var t=e[0],r=e[1];return l.HOOKS[t].push(r)}))};var n=e("./rx-schema"),i=e("./crypter"),o=e("./rx-document"),a=e("./rx-query"),s=e("./rx-collection"),u=e("./rx-database"),c=e("./pouch-db"),f=e("./overwritable"),l=e("./hooks"),d={RxSchema:n.RxSchema.prototype,Crypter:i.Crypter.prototype,RxDocument:o.basePrototype,RxQuery:a.RxQueryBase.prototype,RxCollection:s.RxCollectionBase.prototype,RxDatabase:u.RxDatabaseBase.prototype},h=new Set},{"./crypter":4,"./hooks":7,"./overwritable":9,"./pouch-db":37,"./rx-collection":41,"./rx-database":43,"./rx-document":45,"./rx-query":47,"./rx-schema":48}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkAdapter=a,r.RxDBAdapterCheckPlugin=r.overwritable=r.prototypes=r.rxdb=r.POUCHDB_LOCATION=void 0;var n=e("../pouch-db"),i=e("../util"),o="rxdb-adapter-check";function a(e){var t,r,a=o+"-"+(0,i.generateId)();try{t=new n.PouchDB(o,(0,i.adapterObject)(e),{auto_compaction:!0,revs_limit:1})}catch(e){return Promise.resolve(!1)}return t.info().then((function(){return t.put({_id:a,value:{ok:!0,time:(new Date).getTime()}})})).then((function(){return t.get(a)})).then((function(e){return r=e})).then((function(){return t.remove(r)})).then((function(){return!0})).then((function(){return!!(r&&r.value&&r.value.ok)})).catch((function(){return!1}))}r.POUCHDB_LOCATION=o;r.rxdb=true;var s={};r.prototypes=s;var u={checkAdapter:a};r.overwritable=u;var c={name:"adapter-check",rxdb:true,prototypes:s,overwritable:u};r.RxDBAdapterCheckPlugin=c},{"../pouch-db":37,"../util":56}],12:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.fromPouchDocument=p,r.putAttachment=v,r.getAttachment=m,r.allAttachments=g,r.preMigrateDocument=_,r.postMigrateDocument=S,r.RxDBAttachmentsPlugin=r.hooks=r.overwritable=r.prototypes=r.rxdb=r.RxAttachment=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=e("rxjs/operators"),s=e("./../rx-change-event"),u=e("./../util"),c=e("../rx-error"),f=e("../pouch-db");function l(e){if(!e.collection.schema.jsonSchema.attachments)throw(0,c.newRxError)("AT1",{link:"https://pubkey.github.io/rxdb/rx-attachment.html"})}function d(e){var t=(0,u.now)();return e.collection.pouch.get(e.primary).then((function(r){var n=e.collection._handleFromPouch(r),i=(0,u.now)(),o=(0,s.createUpdateEvent)(e.collection,n,null,t,i,e);e.$emit(o)}))}var h=function(){function e(e){var t,r=e.doc,n=e.id,i=e.type,o=e.length,a=e.digest,s=e.rev;this.doc=r,this.id=n,this.type=i,this.length=o,this.digest=a,this.rev=s,t=this,Object.entries(t.doc.collection.attachments).forEach((function(e){var r=e[0],n=e[1];Object.defineProperty(t,r,{get:function(){return n.bind(t)}})}))}var t=e.prototype;return t.remove=function(){var e=this;return this.doc.collection.pouch.removeAttachment(this.doc.primary,this.id,this.doc._data._rev).then((function(){return d(e.doc)}))},t.getData=function(){var e=this;return this.doc.collection.pouch.getAttachment(this.doc.primary,this.id).then((function(t){return b(e.doc.collection.schema)?u.blobBufferUtil.toString(t).then((function(t){return u.blobBufferUtil.createBlobBuffer(e.doc.collection._crypter._decryptValue(t),e.type)})):t}))},t.getStringData=function(){return this.getData().then((function(e){return u.blobBufferUtil.toString(e)}))},e}();function p(e,t,r){return new h({doc:r,id:e,type:t.content_type,length:t.length,digest:t.digest,rev:t.revpos})}function b(e){return!(!e.jsonSchema.attachments||!e.jsonSchema.attachments.encrypted)}function v(e){return y.apply(this,arguments)}function y(){return(y=(0,o.default)(i.default.mark((function e(t){var r,n,a,s,c,h,v=this,y=arguments;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.id,n=t.data,a=t.type,s=void 0===a?"text/plain":a,c=y.length>1&&void 0!==y[1]&&y[1],l(this),b(this.collection.schema)&&(n=this.collection._crypter._encryptValue(n)),h=u.blobBufferUtil.createBlobBuffer(n,s),this._atomicQueue=this._atomicQueue.then((0,o.default)(i.default.mark((function e(){var t,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(c&&v._data._attachments&&v._data._attachments[r])){e.next=7;break}return t=v._data._attachments[r],e.next=4,(0,f.pouchAttachmentBinaryHash)(n);case 4:if(o=e.sent,t.content_type!==s||t.digest!==o){e.next=7;break}return e.abrupt("return",v.getAttachment(r));case 7:return e.abrupt("return",v.collection.pouch.putAttachment(v.primary,r,v._data._rev,h,s).then((function(){return v.collection.pouch.get(v.primary)})).then((function(e){var t=e._attachments[r],n=p(r,t,v);return v._data._rev=e._rev,v._data._attachments=e._attachments,d(v).then((function(){return n}))})));case 8:case"end":return e.stop()}}),e)})))),e.abrupt("return",this._atomicQueue);case 7:case"end":return e.stop()}}),e,this)})))).apply(this,arguments)}function m(e){l(this);var t=this._dataSync$.getValue();return t._attachments&&t._attachments[e]?p(e,t._attachments[e],this):null}function g(){var e=this;l(this);var t=this._dataSync$.getValue();return t._attachments?Object.keys(t._attachments).map((function(r){return p(r,t._attachments[r],e)})):[]}function _(e){return w.apply(this,arguments)}function w(){return(w=(0,o.default)(i.default.mark((function e(t){var r,n,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(r=t.docData._attachments)){e.next=7;break}return n=!!b(t.oldCollection.schema),a={},e.next=6,Promise.all(Object.keys(r).map(function(){var e=(0,o.default)(i.default.mark((function e(o){var s,c,f;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return s=r[o],c=t.docData[t.oldCollection.schema.primaryPath],e.next=4,t.oldCollection.pouchdb.getAttachment(c,o);case 4:if(f=e.sent,!n){e.next=9;break}return e.next=8,u.blobBufferUtil.toString(f).then((function(e){return u.blobBufferUtil.createBlobBuffer(t.oldCollection._crypter._decryptValue(e),s.content_type)}));case 8:f=e.sent;case 9:a[o]={digest:s.digest,length:s.length,revpos:s.revpos,content_type:s.content_type,stub:!1,data:f};case 10:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 6:t.docData._attachments=a;case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function S(e){return x.apply(this,arguments)}function x(){return(x=(0,o.default)(i.default.mark((function e(t){return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return");case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}r.RxAttachment=h;r.rxdb=true;var O={RxDocument:function(e){e.putAttachment=v,e.getAttachment=m,e.allAttachments=g,Object.defineProperty(e,"allAttachments$",{get:function(){var e=this;return this._dataSync$.pipe((0,a.map)((function(e){return e._attachments?e._attachments:{}})),(0,a.map)((function(e){return Object.entries(e)})),(0,a.map)((function(t){return t.map((function(t){return p(t[0],t[1],e)}))})))}})}};r.prototypes=O;var j={};r.overwritable=j;var E={preMigrateDocument:_,postMigrateDocument:S};r.hooks=E;var M={name:"attachments",rxdb:true,prototypes:O,overwritable:j,hooks:E};r.RxDBAttachmentsPlugin=M},{"../pouch-db":37,"../rx-error":46,"./../rx-change-event":39,"./../util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"rxjs/operators":908}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkMigrationStrategies=function(e,t){if("object"!=typeof t||Array.isArray(t))throw(0,n.newRxTypeError)("COL11",{schema:e});var r=(0,i.getPreviousVersions)(e);if(r.length!==Object.keys(t).length)throw(0,n.newRxError)("COL12",{have:Object.keys(t),should:r});return r.map((function(e){return{v:e,s:t[e+1]}})).filter((function(e){return"function"!=typeof e.s})).forEach((function(t){throw(0,n.newRxTypeError)("COL13",{version:t.v,type:typeof t,schema:e})})),!0};var n=e("../../rx-error"),i=e("../../rx-schema")},{"../../rx-error":46,"../../rx-schema":48}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkOrmMethods=function(e){if(!e)return;Object.entries(e).forEach((function(e){var t=e[0],r=e[1];if("string"!=typeof t)throw(0,n.newRxTypeError)("COL14",{name:t});if(t.startsWith("_"))throw(0,n.newRxTypeError)("COL15",{name:t});if("function"!=typeof r)throw(0,n.newRxTypeError)("COL16",{name:t,type:typeof t});if((0,i.rxCollectionProperties)().includes(t)||(0,i.rxDocumentProperties)().includes(t))throw(0,n.newRxError)("COL17",{name:t})}))};var n=e("../../rx-error"),i=e("./entity-properties")},{"../../rx-error":46,"./entity-properties":17}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkQuery=function(e){if("[object Object]"!==Object.prototype.toString.call(e.queryObj))throw(0,n.newRxTypeError)("QU11",{op:e.op,collection:e.collection.name,queryObj:e.queryObj});var t=["selector","limit","skip","sort"];Object.keys(e.queryObj).forEach((function(r){if(!t.includes(r))throw(0,n.newRxTypeError)("QU11",{op:e.op,collection:e.collection.name,queryObj:e.queryObj,key:r})}))};var n=e("../../rx-error")},{"../../rx-error":46}],16:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.checkFieldNameRegex=u,r.validateFieldsDeep=c,r.checkSchema=function(e){if(!e.hasOwnProperty("properties"))throw(0,o.newRxError)("SC29",{schema:e});if(e.properties._rev)throw(0,o.newRxError)("SC10",{schema:e});if(!e.hasOwnProperty("version")||"number"!=typeof e.version||e.version<0)throw(0,o.newRxError)("SC11",{version:e.version});var t;if(c(e),Object.keys(e.properties).forEach((function(r){var n=e.properties[r];if(n.primary){if(t)throw(0,o.newRxError)("SC12",{value:n});if(t=r,n.index)throw(0,o.newRxError)("SC13",{value:n});if(n.unique)throw(0,o.newRxError)("SC14",{value:n});if(n.encrypted)throw(0,o.newRxError)("SC15",{value:n});if("string"!==n.type)throw(0,o.newRxError)("SC16",{value:n})}if((0,s.rxDocumentProperties)().includes(r))throw(0,o.newRxError)("SC17",{key:r})})),e.indexes){if(!Array.isArray(e.indexes))throw(0,o.newRxError)("SC18",{indexes:e.indexes});e.indexes.forEach((function(e){if("string"!=typeof e&&!Array.isArray(e))throw(0,o.newRxError)("SC19",{index:e});if(Array.isArray(e))for(var t=0;t2||!t.type.includes("string")||!t.type.includes("null"))throw(0,o.newRxError)("SC4",{fieldName:e})}else switch(t.type){case"string":break;case"array":if(!t.items||!t.items.type||"string"!==t.items.type)throw(0,o.newRxError)("SC3",{fieldName:e});break;default:throw(0,o.newRxError)("SC4",{fieldName:e})}var n=r.split(".").length>=2;if(n){if(t.primary)throw(0,o.newRxError)("SC6",{path:r,primary:t.primary});if(t.default)throw(0,o.newRxError)("SC7",{path:r})}if(!n&&"_"===e.charAt(0)){if("_id"===e&&t.primary)return;throw(0,o.newRxError)("SC8",{fieldName:e})}}(n,t[n],r);var i=r;"properties"!==n&&(i=i+"."+n),e(t[n],i)}))}(e,""),!0}function f(e){for(var t=e.split("."),r="",n=0;n 2",QU1:"RxQuery._execOverDatabase(): op not known",QU4:"RxQuery.regex(): You cannot use .regex() on the primary field",QU5:"RxQuery.sort(): does not work because key is not defined in the schema",QU6:"RxQuery.limit(): cannot be called on .findOne()",QU7:"query must be an object",QU8:"query cannot be an array",QU9:"throwIfMissing can only be used in findOne queries",QU10:"result empty and throwIfMissing: true",QU11:"RxQuery: no valid query params given",MQ1:"path must be a string or object",MQ2:"Invalid argument",MQ3:"Invalid sort() argument. Must be a string, object, or array",MQ4:"Invalid argument. Expected instanceof mquery or plain object",MQ5:"method must be used after where() when called with these arguments",MQ6:"Can't mix sort syntaxes. Use either array or object | .sort([['field', 1], ['test', -1]]) | .sort({ field: 1, test: -1 })",MQ7:"Invalid sort value",MQ8:"Can't mix sort syntaxes. Use either array or object",DB1:"RxDocument.prepare(): another instance on this adapter has a different password",DB2:"RxDatabase.collection(): collection-names cannot start with underscore _",DB3:"RxDatabase.collection(): collection already exists. use myDatabase.[collectionName] to get it",DB4:"RxDatabase.collection(): schema is missing",DB5:"RxDatabase.collection(): collection-name not allowed",DB6:"RxDatabase.collection(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema",DB7:"RxDatabase.collection(): schema encrypted but no password given",DB8:"RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\nMake sure to use this combination only once or set ignoreDuplicate to true if you do this intentional",DB9:"RxDatabase.create(): Adapter not added. Use RxDB.plugin(require('pouchdb-adapter-[adaptername]');",DB10:"RxDatabase.create(): To use leveldown-adapters, you have to add the leveldb-plugin. Use RxDB.plugin(require('pouchdb-adapter-leveldb'));",DB11:"RxDatabase.create(): Invalid db-name, folder-paths must not have an ending slash",COL1:"RxDocument.insert() You cannot insert an existing document",COL2:"RxCollection.insert() do not provide ._id when it is not the primary key",COL3:"RxCollection.upsert() does not work without primary",COL4:"RxCollection.atomicUpsert() does not work without primary",COL5:"RxCollection.find() if you want to search by _id, use .findOne(_id)",COL6:"RxCollection.findOne() needs a queryObject or string",COL7:"hook must be a function",COL8:"hooks-when not known",COL9:"RxCollection.addHook() hook-name not known",COL10:"RxCollection .postCreate-hooks cannot be async",COL11:"migrationStrategies must be an object",COL12:"A migrationStrategy is missing or too much",COL13:"migrationStrategy must be a function",COL14:"given static method-name is not a string",COL15:"static method-names cannot start with underscore _",COL16:"given static method is not a function",COL17:"RxCollection.ORM: statics-name not allowed",COL18:"collection-method not allowed because fieldname is in the schema",COL19:"Pouchdb document update conflict",DOC1:"RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed",DOC2:"cannot observe primary path",DOC3:"final fields cannot be observed",DOC4:"RxDocument.get$ cannot observe a non-existed field",DOC5:"RxDocument.populate() cannot populate a non-existed field",DOC6:"RxDocument.populate() cannot populate because path has no ref",DOC7:"RxDocument.populate() ref-collection not in database",DOC8:"RxDocument.set(): primary-key cannot be modified",DOC9:"final fields cannot be modified",DOC10:"RxDocument.set(): cannot set childpath when rootPath not selected",DOC11:"RxDocument.save(): cant save deleted document",DOC12:"RxDocument.save(): error",DOC13:"RxDocument.remove(): Document is already deleted",DOC14:"RxDocument.destroy() does not exist",DOC15:"query cannot be an array",DOC16:"Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments",DOC17:"Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents",DM1:"migrate() Migration has already run",DM2:"migration of document failed final document does not match final schema",DM3:"migration already running",AT1:"to use attachments, please define this in your schema",EN1:"password is no string",EN2:"validatePassword: min-length of password not complied",JD1:"You must create the collections before you can import their data",JD2:"RxCollection.importDump(): the imported json relies on a different schema",JD3:"RxCollection.importDump(): json.passwordHash does not match the own",LD1:"RxDocument.allAttachments$ cant use attachments on local documents",LD2:"RxDocument.get(): objPath must be a string",LD3:"RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed",LD4:"cannot observe primary path",LD5:"RxDocument.set() id cannot be modified",LD6:"LocalDocument: Function is not useable on local documents",LD7:"Local document already exists",RC1:"Replication: already added",RC2:"RxCollection.sync() query must be from the same RxCollection",RC3:"RxCollection.sync() Do not use a collection's pouchdb as remote, use the collection instead",RC4:"RxReplicationState.awaitInitialReplication() cannot await inital replication when live: true",RC5:"RxReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance",SC1:"fieldnames do not match the regex",SC2:"SchemaCheck: name 'item' reserved for array-fields",SC3:"SchemaCheck: fieldname has a ref-array but items-type is not string",SC4:"SchemaCheck: fieldname has a ref but is not type string, [string,null] or array",SC6:"SchemaCheck: primary can only be defined at top-level",SC7:"SchemaCheck: default-values can only be defined at top-level",SC8:"SchemaCheck: first level-fields cannot start with underscore _",SC10:"SchemaCheck: schema defines ._rev, this will be done automatically",SC11:"SchemaCheck: schema needs a number >=0 as version",SC12:"SchemaCheck: primary can only be defined once",SC13:"SchemaCheck: primary is always index, do not declare it as index",SC14:"SchemaCheck: primary is always unique, do not declare it as index",SC15:"SchemaCheck: primary cannot be encrypted",SC16:"SchemaCheck: primary must have type: string",SC17:"SchemaCheck: top-level fieldname is not allowed",SC18:"SchemaCheck: indexes must be an array",SC19:"SchemaCheck: indexes must contain strings or arrays of strings",SC20:"SchemaCheck: indexes.array must contain strings",SC21:"SchemaCheck: given index is not defined in schema",SC22:"SchemaCheck: given indexKey is not type:string",SC23:"SchemaCheck: fieldname is not allowed",SC24:"SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required",SC25:"SchemaCheck: compoundIndexes needs to be specified in the indexes field",SC26:"SchemaCheck: indexes needs to be specified at collection schema level",SC27:"SchemaCheck: encrypted fields need to be specified at collection schema level",SC28:"SchemaCheck: encrypted fields is not defined in the schema",SC29:"SchemaCheck: missing object key 'properties'",DEV1:"dev-mode added multiple times, this is likely because you have mixed up the import from the the plugins/core and the full RxDB",VD1:"Sub-schema not found, does the schemaPath exists in your schema?",VD2:"object does not match schema",IM1:"InMemory: Memory-Adapter must be added. Use RxDB.plugin(require('pouchdb-adapter-memory'));",IM2:"inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead",S1:"You cannot create collections after calling RxDatabase.server()"}},{}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={RxDBDevModePlugin:!0};r.RxDBDevModePlugin=void 0;var i=e("./error-messages"),o=e("./check-schema");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===o[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return o[e]}}))}));var a=e("./check-orm"),s=e("./check-migration-strategies"),u=e("./unallowed-properties"),c=e("./check-query"),f=e("../../rx-error"),l="dev-mode",d={name:l,rxdb:!0,overwritable:{isDevMode:function(){return!0},tunnelErrorMessage:function(e){if(!i.ERROR_MESSAGES[e])throw console.error("RxDB: Error-Code not known: "+e),new Error("Error-Code "+e+" not known, contact the maintainer");return i.ERROR_MESSAGES[e]}},hooks:{preAddRxPlugin:function(e){if(e.plugin.name===l)throw(0,f.newRxError)("DEV1",{plugins:e.plugins})},preCreateRxSchema:o.checkSchema,preCreateRxDatabase:function(e){(0,u.ensureDatabaseNameIsValid)(e)},preCreateRxCollection:function(e){if((0,u.ensureCollectionNameValid)(e),"_"===e.name.charAt(0))throw(0,f.newRxError)("DB2",{name:e.name});if(!e.schema)throw(0,f.newRxError)("DB4",{name:e.name,args:e})},preCreateRxQuery:function(e){(0,c.checkQuery)(e)},createRxCollection:function(e){(0,a.checkOrmMethods)(e.statics),(0,a.checkOrmMethods)(e.methods),(0,a.checkOrmMethods)(e.attachments),e.schema&&e.migrationStrategies&&(0,s.checkMigrationStrategies)(e.schema,e.migrationStrategies)}}};r.RxDBDevModePlugin=d},{"../../rx-error":46,"./check-migration-strategies":13,"./check-orm":14,"./check-query":15,"./check-schema":16,"./error-messages":18,"./unallowed-properties":20}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ensureCollectionNameValid=function(e){if((0,i.rxDatabaseProperties)().includes(e.name))throw(0,n.newRxError)("DB5",{name:e.name})},r.ensureDatabaseNameIsValid=function(e){if((0,o.validateCouchDBString)(e.name),(0,a.isFolderPath)(e.name)&&(e.name.endsWith("/")||e.name.endsWith("\\")))throw(0,n.newRxError)("DB11",{name:e.name})};var n=e("../../rx-error"),i=e("./entity-properties"),o=e("../../pouch-db"),a=e("../../util")},{"../../pouch-db":37,"../../rx-error":46,"../../util":56,"./entity-properties":17}],21:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.encrypt=c,r.decrypt=f,r.storePasswordHashIntoDatabase=h,r.RxDBEncryptionPlugin=r.overwritable=r.prototypes=r.rxdb=void 0;var i=n(e("crypto-js/aes")),o=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=u(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(n,o,a):n[o]=e[o]}n.default=e,r&&r.set(e,n);return n}(e("crypto-js/enc-utf8")),a=e("../rx-error"),s=e("../util");function u(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(u=function(e){return e?r:t})(e)}function c(e,t){return i.default.encrypt(e,t).toString()}function f(e,t){return i.default.decrypt(e,t).toString(o)}var l=function(e){return c(JSON.stringify(e),this.password)},d=function(e){var t=f(e,this.password);return JSON.parse(t)};function h(e){if(!e.password)return Promise.resolve(!1);var t=(0,s.hash)(e.password);return e.internalStore.get(s.LOCAL_PREFIX+"pwHash").catch((function(){return null})).then((function(r){return r?t===r.value||e.destroy().then((function(){throw(0,a.newRxError)("DB1",{passwordHash:(0,s.hash)(e.password),existingPasswordHash:r.value})})):e.internalStore.put({_id:s.LOCAL_PREFIX+"pwHash",value:t}).catch((function(){return null})).then((function(){return!0}))}))}r.rxdb=true;var p={Crypter:function(e){e._encryptValue=l,e._decryptValue=d}};r.prototypes=p;var b={validatePassword:function(e){if(e&&"string"!=typeof e)throw(0,a.newRxTypeError)("EN1",{password:e});if(e&&e.length<8)throw(0,a.newRxError)("EN2",{minPassLength:8,password:e})}};r.overwritable=b;var v={name:"encryption",rxdb:true,prototypes:p,overwritable:b,hooks:{createRxDatabase:function(e){return h(e)}}};r.RxDBEncryptionPlugin=v},{"../rx-error":46,"../util":56,"@babel/runtime/helpers/interopRequireDefault":65,"crypto-js/aes":485,"crypto-js/enc-utf8":489}],22:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.replicateExistingDocuments=O,r.setIndexes=j,r.streamChangedDocuments=E,r.applyChangedDocumentToPouch=M,r.spawnInMemory=A,r.RxDBInMemoryPlugin=r.prototypes=r.rxdb=r.InMemoryRxCollection=void 0;var i=n(e("@babel/runtime/helpers/assertThisInitialized")),o=n(e("@babel/runtime/helpers/inheritsLoose")),a=e("rxjs"),s=e("rxjs/operators"),u=e("../rx-collection"),c=e("../util"),f=e("../core"),l=e("../crypter"),d=e("../change-event-buffer"),h=e("../rx-schema"),p=e("../pouch-db"),b=e("../rx-error"),v=e("../rx-storage-pouchdb"),y=e("../plugins/watch-for-changes");(0,f.addRxPlugin)(y.RxDBWatchForChangesPlugin);var m=new WeakMap,g=new WeakMap,_={new_edits:!0},w={new_edits:!1},S=function(e){function t(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(r=e.call(this,t.database,t.name,x(t.schema),n,{},t._methods)||this)._eventCounter=0,r._isInMemory=!0,r._parentCollection=t,r._parentCollection.onDestroy.then((function(){return r.destroy()})),r._crypter=(0,l.createCrypter)(r.database.password,r.schema),r._changeStreams=[],r.onDestroy.then((function(){r._changeStreams.forEach((function(e){return e.cancel()})),r.pouch.destroy()})),r.options=t.options,Object.entries(t.statics).forEach((function(e){var t=e[0],n=e[1];Object.defineProperty((0,i.default)(r),t,{get:function(){return n.bind((0,i.default)(r))}})}));var o=(0,v.getRxStoragePouchDb)("memory");r.pouch=o.createStorageInstance("rxdb-in-memory",(0,c.randomCouchString)(10),0),r._observable$=new a.Subject,r._changeEventBuffer=(0,d.createChangeEventBuffer)((0,i.default)(r));var s=Object.getPrototypeOf(t);return r._oldPouchPut=s._pouchPut.bind((0,i.default)(r)),r._nonPersistentRevisions=new Set,r._nonPersistentRevisionsSubject=new a.Subject,r}(0,o.default)(t,e);var r=t.prototype;return r.prepareChild=function(){var e=this;return j(this.schema,this.pouch).then((function(){e._subs.push(e._observable$.subscribe((function(t){var r=e._docCache.get(t.documentId);r&&r._handleChangeEvent(t)})))})).then((function(){return O(e._parentCollection,e)})).then((function(){e._parentCollection.watchForChanges(),e.watchForChanges();var t=E(e).pipe((0,s.mergeMap)((function(t){return M(e._parentCollection,t).then((function(){return t._rev}))}))).subscribe((function(t){e._nonPersistentRevisions.delete(t),e._nonPersistentRevisionsSubject.next(e._nonPersistentRevisions.size)}));e._subs.push(t);var r=E(e._parentCollection).subscribe((function(t){return M(e,t)}));e._subs.push(r)}))},r.awaitPersistence=function(){var e=this;return 0===this._nonPersistentRevisions.size?Promise.resolve():(0,a.firstValueFrom)(this._nonPersistentRevisionsSubject.pipe((0,s.filter)((function(){return 0===e._nonPersistentRevisions.size}))))},r._pouchPut=function(e,t){var r=this;return this._oldPouchPut(e,t).then((function(e){return r._nonPersistentRevisions.add(e.rev),e}))},r.$emit=function(e){this._changeEventBuffer.hasChangeWithRevision(e.documentData&&e.documentData._rev)||(this._observable$.next(e),this._eventCounter++,10===this._eventCounter&&(this._eventCounter=0,this.pouch.compact()))},r.sync=function(){throw(0,b.newRxError)("IM2")},t}(u.RxCollectionBase);function x(e){var t=(0,c.clone)(e.jsonSchema);t.keyCompression=!1,delete t.properties._id,delete t.properties._rev,delete t.properties._attachments;return function e(t,r){delete t.encrypted,Object.values(t).filter((function(e){return"object"==typeof e})).forEach((function(t){return e(t,r)}))}(t,t),(0,h.createRxSchema)(t)}function O(e,t){return e.pouch.allDocs({attachments:!1,include_docs:!0}).then((function(r){var n=r.rows.map((function(e){return e.doc})).filter((function(e){return!e.language})).map((function(t){return e._handleFromPouch(t)})).map((function(t){return e.schema.swapPrimaryToId(t)}));return 0===n.length?Promise.resolve([]):t.pouch.bulkDocs({docs:n},w).then((function(){return n}))}))}function j(e,t){return Promise.all(e.indexes.map((function(e){var r="idx-rxdb-"+e.join(",");return t.createIndex({ddoc:r,name:r,index:{fields:e}})})))}function E(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return!0};e._doNotEmitSet||(e._doNotEmitSet=new Set);var r=(0,a.fromEvent)(e.pouch.changes({since:"now",live:!0,include_docs:!0}),"change").pipe((0,s.delay)(0),(0,s.map)((function(e){return e[0]})),(0,s.filter)((function(t){var r=t.id+":"+t.doc._rev;return!e._doNotEmitSet.has(r)})),(0,s.filter)((function(e){return t(e)})),(0,s.map)((function(t){return e._handleFromPouch(t.doc)})));return r}function M(e,t){e._doNotEmitSet||(e._doNotEmitSet=new Set);var r=e._handleToPouch(t);return e.pouch.get(r._id).then((function(e){return r._rev=e._rev})).catch((function(){delete r._rev})).then((function(){return e.pouch.bulkDocs({docs:[r]},_)})).then((function(t){if(t.length>0&&!t[0].ok)throw new Error(JSON.stringify(t[0]));var n=r._id+":"+t[0].rev;return e._doNotEmitSet.add(n),setTimeout((function(){return e._doNotEmitSet.delete(n)}),3e4),r}))}r.InMemoryRxCollection=S;var k=!1;function A(){var e=this;if(!k&&(k=!0,!p.PouchDB.adapters||!p.PouchDB.adapters.memory))throw(0,b.newRxError)("IM1");if(m.has(this))return g.get(this).then((function(){return m.get(e)}));var t=new S(this),r=t.prepareChild();return m.set(this,t),g.set(this,r),r.then((function(){return t}))}r.rxdb=true;var P={RxCollection:function(e){e.inMemory=A}};r.prototypes=P;var R={name:"in-memory",rxdb:true,prototypes:P};r.RxDBInMemoryPlugin=R},{"../change-event-buffer":2,"../core":3,"../crypter":4,"../plugins/watch-for-changes":36,"../pouch-db":37,"../rx-collection":41,"../rx-error":46,"../rx-schema":48,"../rx-storage-pouchdb":49,"../util":56,"@babel/runtime/helpers/assertThisInitialized":59,"@babel/runtime/helpers/inheritsLoose":64,"@babel/runtime/helpers/interopRequireDefault":65,rxjs:684,"rxjs/operators":908}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RxDBJsonDumpPlugin=r.overwritable=r.prototypes=r.rxdb=void 0;var n=e("../util"),i=e("../rx-query"),o=e("../rx-error"),a=e("../rx-change-event");function s(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=arguments.length>1?arguments[1]:void 0,i={name:this.name,instanceToken:this.token,encrypted:!1,passwordHash:null,collections:[]};this.password&&(i.passwordHash=(0,n.hash)(this.password),i.encrypted=!t);var o=Object.keys(this.collections).filter((function(e){return!r||r.includes(e)})).filter((function(e){return"_"!==e.charAt(0)})).map((function(t){return e.collections[t]}));return Promise.all(o.map((function(e){return e.dump(t)}))).then((function(e){return i.collections=e,i}))}var u=function(e){var t=this,r=e.collections.filter((function(e){return!t.collections[e.name]})).map((function(e){return e.name}));if(r.length>0)throw(0,o.newRxError)("JD1",{missingCollections:r});return Promise.all(e.collections.map((function(e){return t.collections[e.name].importDump(e)})))},c=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=!e,r={name:this.name,schemaHash:this.schema.hash,encrypted:!1,passwordHash:null,docs:[]};this.database.password&&t&&(r.passwordHash=(0,n.hash)(this.database.password),r.encrypted=!0);var o=(0,i.createRxQuery)("find",(0,i._getDefaultQuery)(this),this);return this._pouchFind(o,void 0,t).then((function(e){return r.docs=e.map((function(e){return delete e._rev,delete e._attachments,e})),r}))};function f(e){var t=this;if(e.schemaHash!==this.schema.hash)throw(0,o.newRxError)("JD2",{schemaHash:e.schemaHash,own:this.schema.hash});if(e.encrypted&&e.passwordHash!==(0,n.hash)(this.database.password))throw(0,o.newRxError)("JD3",{passwordHash:e.passwordHash,own:(0,n.hash)(this.database.password)});var r,i=e.docs.map((function(e){return t._crypter.decrypt(e)})).map((function(e){return t.schema.validate(e)})).map((function(e){return t._handleToPouch(e)}));return this.database.lockedRun((function(){return r=(0,n.now)(),t.pouch.bulkDocs(i)})).then((function(){var e=(0,n.now)();i.forEach((function(n){var i=(0,a.createInsertEvent)(t,n,r,e);t.$emit(i)}))}))}r.rxdb=true;var l={RxDatabase:function(e){e.dump=s,e.importDump=u},RxCollection:function(e){e.dump=c,e.importDump=f}};r.prototypes=l;var d={};r.overwritable=d;var h={name:"json-dump",rxdb:true,prototypes:l,overwritable:d};r.RxDBJsonDumpPlugin=h},{"../rx-change-event":39,"../rx-error":46,"../rx-query":47,"../util":56}],24:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.create=u,r.RxDBKeyCompressionPlugin=r.overwritable=r.prototypes=r.rxdb=r.KeyCompressor=void 0;var i=n(e("@babel/runtime/helpers/createClass")),o=e("jsonschema-key-compression"),a=e("../util"),s=function(){function e(e){this.schema=e}var t=e.prototype;return t.compress=function(e){return this.schema.doKeyCompression()?(0,o.compressObject)(this.table,e):e},t.decompress=function(e){return this.schema.doKeyCompression()?(0,o.decompressObject)(this.table,e):e},t.transformKey=function(e){return(0,o.compressedPath)(this.table,e)},t.compressQuery=function(e){return this.schema.doKeyCompression()?(0,o.compressQuery)(this.table,e):e},(0,i.default)(e,[{key:"table",get:function(){var e=this.schema.normalized,t=(0,o.createCompressionTable)(e,o.DEFAULT_COMPRESSION_FLAG,[this.schema.primaryPath,"_rev","_attachments"]);return(0,a.overwriteGetterForCaching)(this,"table",t)}}]),e}();function u(e){return new s(e)}r.KeyCompressor=s;r.rxdb=true;var c={};r.prototypes=c;var f={createKeyCompressor:u};r.overwritable=f;var l={name:"key-compression",rxdb:true,prototypes:c,overwritable:f};r.RxDBKeyCompressionPlugin=l},{"../util":56,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"jsonschema-key-compression":612}],25:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getForDatabase=a,r.isLeader=s,r.waitForLeadership=u,r.onDestroy=c,r.RxDBLeaderElectionPlugin=r.prototypes=r.rxdb=r.LeaderElector=void 0;var n=e("broadcast-channel"),i=new WeakMap,o=function(){function e(e){this.destroyed=!1,this.isLeader=!1,this.isDead=!1,this.database=e,this.elector=(0,n.createLeaderElection)(e.broadcastChannel)}var t=e.prototype;return t.die=function(){return this.elector.die()},t.waitForLeadership=function(){var e=this;return this.elector.awaitLeadership().then((function(){return e.isLeader=!0,!0}))},t.destroy=function(){if(!this.destroyed)return this.destroyed=!0,this.isDead=!0,this.die()},e}();function a(){return i.has(this)||i.set(this,new o(this)),i.get(this)}function s(){return!this.multiInstance||this.leaderElector().isLeader}function u(){return this.multiInstance?this.leaderElector().waitForLeadership():Promise.resolve(!0)}function c(e){var t=i.get(e);t&&t.destroy()}r.LeaderElector=o;r.rxdb=true;var f={RxDatabase:function(e){e.leaderElector=a,e.isLeader=s,e.waitForLeadership=u}};r.prototypes=f;var l={name:"leader-election",rxdb:true,prototypes:f,hooks:{preDestroyRxDatabase:c}};r.RxDBLeaderElectionPlugin=l},{"broadcast-channel":112}],26:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxDBLocalDocumentsPlugin=r.overwritable=r.prototypes=r.rxdb=r.RxLocalDocument=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("@babel/runtime/helpers/inheritsLoose")),s=n(e("object-path")),u=e("../rx-document"),c=e("../rx-change-event"),f=e("../doc-cache"),l=e("../rx-error"),d=e("../util"),h=e("../rx-database"),p=e("../rx-collection"),b=e("rxjs/operators"),v=new WeakMap,y=function(e){return v.has(e)||v.set(e,(0,f.createDocCache)()),v.get(e)},m=new WeakMap,g=function(e){function t(t,r,n){var i;return(i=e.call(this,null,r)||this).id=t,i.parent=n,i}return(0,a.default)(t,e),t}((0,u.createRxDocumentConstructor)());r.RxLocalDocument=g;var _=function(e){return(0,h.isInstanceOf)(e)?e.internalStore:e.pouch},w={toPouchJson:function(){(0,d.clone)(this._data)._id=d.LOCAL_PREFIX+this.id},get isLocal(){return!0},get parentPouch(){return _(this.parent)},_handleChangeEvent:function(e){if(e.documentId===this.primary)switch(e.operation){case"UPDATE":var t=(0,d.clone)(e.documentData);this._dataSync$.next((0,d.clone)(t));break;case"DELETE":y(this.parent).delete(this.primary),this._deleted$.next(!0)}},get allAttachments$(){throw(0,l.newRxError)("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){return this._dataSync$.asObservable()},$emit:function(e){return this.parent.$emit(e)},get:function(e){if(this._data){if("string"!=typeof e)throw(0,l.newRxTypeError)("LD2",{objPath:e});var t=s.default.get(this._data,e);return t=(0,d.clone)(t)}},get$:function(e){if(e.includes(".item."))throw(0,l.newRxError)("LD3",{path:e});if(e===this.primaryPath)throw(0,l.newRxError)("LD4");return this._dataSync$.pipe((0,b.map)((function(t){return s.default.get(t,e)})),(0,b.distinctUntilChanged)())},set:function(e,t){if(!t){var r=(0,d.clone)(e);return r._rev=this._data._rev,this._data=r,this}if("_id"===e)throw(0,l.newRxError)("LD5",{objPath:e,value:t});if(!Object.is(this.get(e),t))return s.default.set(this._data,e,t),this},_saveData:function(e){var t=this,r=this._dataSync$.getValue();(e=(0,d.clone)(e))._id=d.LOCAL_PREFIX+this.id;var n=(0,d.now)();return this.parentPouch.put(e).then((function(i){var o=(0,d.now)();e._rev=i.rev;var a=new c.RxChangeEvent("UPDATE",t.id,(0,d.clone)(e),(0,h.isInstanceOf)(t.parent)?t.parent.token:t.parent.database.token,(0,p.isInstanceOf)(t.parent)?t.parent.name:null,!0,n,o,r,t);t.$emit(a)}))},remove:function(){var e=this,t=d.LOCAL_PREFIX+this.id,r=(0,d.now)();return this.parentPouch.remove(t,this._data._rev).then((function(){y(e.parent).delete(e.id);var t=(0,d.now)(),n=new c.RxChangeEvent("DELETE",e.id,(0,d.clone)(e._data),(0,h.isInstanceOf)(e.parent)?e.parent.token:e.parent.database.token,(0,p.isInstanceOf)(e.parent)?e.parent.name:null,!0,r,t,null,e);e.$emit(n)}))}},S=!1,x=function(){if(!S){S=!0;var e=u.basePrototype;Object.getOwnPropertyNames(e).forEach((function(t){if(!Object.getOwnPropertyDescriptor(w,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(w,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((function(e){return w[e]=function(e){return function(){throw(0,l.newRxError)("LD6",{functionName:e})}}(e)}))}};function O(e,t){var r=this;return(0,p.isInstanceOf)(this)&&this._isInMemory?this._parentCollection.insertLocal(e,t):(t=(0,d.clone)(t),this.getLocal(e).then((function(n){if(n)throw(0,l.newRxError)("LD7",{id:e,data:t});var i=_(r),o=(0,d.clone)(t);o._id=d.LOCAL_PREFIX+e;var a=(0,d.now)();return i.put(o).then((function(n){t._rev=n.rev;var i=g.create(e,t,r),o=(0,d.now)(),s=new c.RxChangeEvent("INSERT",e,(0,d.clone)(t),(0,h.isInstanceOf)(r)?r.token:r.database.token,(0,p.isInstanceOf)(r)?r.name:"",!0,a,o,void 0,i);return r.$emit(s),i}))})))}function j(e,t){var r=this;return(0,p.isInstanceOf)(this)&&this._isInMemory?this._parentCollection.upsertLocal(e,t):this.getLocal(e).then((function(n){return n?(t._rev=n._data._rev,n.atomicUpdate((function(){return t})).then((function(){return n}))):r.insertLocal(e,t)}))}function E(e){var t=this;if((0,p.isInstanceOf)(this)&&this._isInMemory)return this._parentCollection.getLocal(e);var r=_(this),n=y(this).get(e);return n?Promise.resolve(n):r.get(d.LOCAL_PREFIX+e).then((function(r){return r?g.create(e,r,t):null})).catch((function(){return null}))}function M(e){var t=this;return this.$.pipe((0,b.startWith)(null),(0,b.mergeMap)(function(){var r=(0,o.default)(i.default.mark((function r(n){var o;return i.default.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!n){r.next=4;break}return r.abrupt("return",{changeEvent:n});case 4:return r.next=6,t.getLocal(e);case 6:return o=r.sent,r.abrupt("return",{doc:o});case 8:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}()),(0,b.mergeMap)(function(){var r=(0,o.default)(i.default.mark((function r(n){var o,a;return i.default.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!n.changeEvent){r.next=17;break}if((o=n.changeEvent).isLocal&&o.documentId===e){r.next=6;break}return r.abrupt("return",{use:!1});case 6:if(!o.rxDocument){r.next=10;break}r.t0=o.rxDocument,r.next=13;break;case 10:return r.next=12,t.getLocal(e);case 12:r.t0=r.sent;case 13:return a=r.t0,r.abrupt("return",{use:!0,doc:a});case 15:r.next=18;break;case 17:return r.abrupt("return",{use:!0,doc:n.doc});case 18:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}()),(0,b.filter)((function(e){return e.use})),(0,b.map)((function(e){return e.doc})))}g.create=function(e,t,r){x(),function(e){if(!m.has(e)){var t=e.$.pipe((0,b.filter)((function(e){return e.isLocal}))).subscribe((function(t){var r=y(e).get(t.documentId);r&&r._handleChangeEvent(t)}));e._subs.push(t),m.set(e,t)}m.get(e)}(r);var n=new g(e,t,r);return n.__proto__=w,y(r).set(e,n),n};r.rxdb=true;var k={RxCollection:function(e){e.insertLocal=O,e.upsertLocal=j,e.getLocal=E,e.getLocal$=M},RxDatabase:function(e){e.insertLocal=O,e.upsertLocal=j,e.getLocal=E,e.getLocal$=M}};r.prototypes=k;var A={};r.overwritable=A;var P={name:"local-documents",rxdb:true,prototypes:k,overwritable:A};r.RxDBLocalDocumentsPlugin=P},{"../doc-cache":5,"../rx-change-event":39,"../rx-collection":41,"../rx-database":43,"../rx-document":45,"../rx-error":46,"../util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/inheritsLoose":64,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"object-path":630,"rxjs/operators":908}],27:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.createOldCollection=y,r._getOldCollections=m,r.mustMigrate=g,r.createDataMigrator=function(e,t){return new v(e,t)},r.runStrategyIfNotNull=_,r.getBatchOfOldCollection=w,r.migrateDocumentData=S,r.isDocumentDataWithoutRevisionEqual=x,r._migrateDocument=O,r.deleteOldCollection=j,r.migrateOldCollection=E,r.migratePromise=function(e,t){e._migratePromise||(e._migratePromise=new Promise((function(r,n){E(e,t).subscribe(null,n,r)})));return e._migratePromise},r.DataMigrator=void 0;var i=e("rxjs"),o=n(e("deep-equal")),a=e("../../pouch-db"),s=e("../../util"),u=e("../../rx-schema"),c=e("../../rx-error"),f=e("../../overwritable"),l=e("../../hooks"),d=e("../../crypter"),h=e("../../rx-collection-helper"),p=e("./migration-state"),b=e("rxjs/operators"),v=function(){function e(e,t){this._migrated=!1,this.newestCollection=e,this.migrationStrategies=t,this.currentSchema=e.schema,this.database=e.database,this.name=e.name}var t=e.prototype;return t.migrate=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;if(this._migrated)throw(0,c.newRxError)("DM1");this._migrated=!0;var r,n={done:!1,total:0,handled:0,success:0,deleted:0,percent:0},o=new i.Subject,u=(0,p.getMigrationStateByDatabase)(this.newestCollection.database),f=u.getValue().slice(0);return f.push(o.asObservable()),u.next(f),m(e).then((function(e){return r=e,Promise.all(r.map((function(e){return(0,a.countAllUndeleted)(e.pouchdb)})))})).then((function(i){var a=i.reduce((function(e,t){return e+t}),0);n.total=a,o.next({collection:e.newestCollection,state:(0,s.flatClone)(n)});for(var u=r.shift(),c=Promise.resolve(),f=function(){var i=E(u,t);c=c.then((function(){return new Promise((function(t){var r=i.subscribe((function(t){n.handled++,n[t.type]=n[t.type]+1,n.percent=Math.round(n.handled/n.total*100),o.next({collection:e.newestCollection,state:(0,s.flatClone)(n)})}),(function(e){r.unsubscribe(),o.error(e)}),(function(){r.unsubscribe(),t()}))}))})),u=r.shift()};u;)f();return c})).then((function(){n.done=!0,n.percent=100,o.next({collection:e.newestCollection,state:(0,s.flatClone)(n)}),o.complete()})),o.pipe((0,b.map)((function(e){return e.state})))},t.migratePromise=function(e){var t=this;return this._migratePromise||(this._migratePromise=g(this).then((function(r){return r?new Promise((function(r,n){t.migrate(e).subscribe(null,n,r)})):Promise.resolve(!1)}))),this._migratePromise},e}();function y(e,t,r){var n=r.newestCollection.database,i=(0,u.createRxSchema)(t,!1),o={version:e,dataMigrator:r,newestCollection:r.newestCollection,database:n,schema:(0,u.createRxSchema)(t,!1),pouchdb:n._spawnPouchDB(r.newestCollection.name,e,r.newestCollection.pouchSettings),_crypter:(0,d.createCrypter)(n.password,i)};return i.doKeyCompression()&&(o._keyCompressor=f.overwritable.createKeyCompressor(i)),o}function m(e){return Promise.all((0,u.getPreviousVersions)(e.currentSchema.jsonSchema).map((function(t){return e.database.internalStore.get(e.name+"-"+t)})).map((function(e){return e.catch((function(){return null}))}))).then((function(t){return t.filter((function(e){return null!==e})).map((function(t){return y(t.schema.version,t.schema,e)}))}))}function g(e){return 0===e.currentSchema.version?Promise.resolve(!1):m(e).then((function(e){return 0!==e.length}))}function _(e,t,r){if(null===r)return Promise.resolve(null);var n=e.dataMigrator.migrationStrategies[t](r,e);return(0,s.toPromise)(n)}function w(e,t){return(0,a.getBatch)(e.pouchdb,t).then((function(t){return t.map((function(t){return(0,h._handleFromPouch)(e,t)}))}))}function S(e,t){var r=(0,s.flatClone)(t._attachments),n=(0,s.clone)(t);n._attachments=r;for(var i=e.version+1,o=Promise.resolve(n),a=function(){var t=i;o=o.then((function(r){return _(e,t,r)})),i++};i<=e.newestCollection.schema.version;)a();return o.then((function(r){if(null===r)return Promise.resolve(null);try{e.newestCollection.schema.validate(r)}catch(i){var n=i;throw(0,c.newRxError)("DM2",{fromVersion:e.version,toVersion:e.newestCollection.schema.version,originalDoc:t,finalDoc:r,errors:n.parameters.errors,schema:n.parameters.schema})}return r}))}function x(e,t){var r=Object.assign({},e,{_attachments:void 0,_rev:void 0}),n=Object.assign({},t,{_attachments:void 0,_rev:void 0});return(0,o.default)(r,n)}function O(e,t){var r={res:null,type:"",migrated:null,doc:t,oldCollection:e,newestCollection:e.newestCollection};return(0,l.runAsyncPluginHooks)("preMigrateDocument",{docData:t,oldCollection:e}).then((function(){return S(e,t)})).then((function(n){if(x(t,n))n._rev=t._rev;else if(null!==n){var i=(0,s.getHeightOfRevision)(t._rev)+1+"-"+(0,s.createRevision)(n,!0);n._rev=i}if(r.migrated=n,n){var o=n._attachments,a=e.newestCollection._handleToPouch(n);return a._attachments=o,e.newestCollection.pouch.bulkDocs([a],{new_edits:!1}).then((function(){return r.res=a,r.type="success",(0,l.runAsyncPluginHooks)("postMigrateDocument",r)}))}r.type="deleted"})).then((function(){return e.pouchdb.remove((0,h._handleToPouch)(e,t)).catch((function(){}))})).then((function(){return r}))}function j(e){return e.pouchdb.destroy().then((function(){return e.database.removeCollectionDoc(e.dataMigrator.name,e.schema)}))}function E(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;if(e._migrate)throw(0,c.newRxError)("DM3");e._migrate=!0;var r,n=new i.Subject;return function i(){return w(e,t).then((function(t){return 0===t.length?(j(e).then((function(){return n.complete()})),!1):Promise.all(t.map((function(t){return O(e,t).then((function(e){return n.next(e)}))}))).catch((function(e){return r=e})).then((function(){return!0}))})).then((function(e){e&&(r?n.error(r):i())}))}(),n.asObservable()}r.DataMigrator=v},{"../../crypter":4,"../../hooks":7,"../../overwritable":9,"../../pouch-db":37,"../../rx-collection-helper":40,"../../rx-error":46,"../../rx-schema":48,"../../util":56,"./migration-state":29,"@babel/runtime/helpers/interopRequireDefault":65,"deep-equal":496,rxjs:684,"rxjs/operators":908}],28:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"_getOldCollections",{enumerable:!0,get:function(){return o._getOldCollections}}),Object.defineProperty(r,"getBatchOfOldCollection",{enumerable:!0,get:function(){return o.getBatchOfOldCollection}}),Object.defineProperty(r,"migrateDocumentData",{enumerable:!0,get:function(){return o.migrateDocumentData}}),Object.defineProperty(r,"_migrateDocument",{enumerable:!0,get:function(){return o._migrateDocument}}),Object.defineProperty(r,"deleteOldCollection",{enumerable:!0,get:function(){return o.deleteOldCollection}}),Object.defineProperty(r,"migrateOldCollection",{enumerable:!0,get:function(){return o.migrateOldCollection}}),Object.defineProperty(r,"migratePromise",{enumerable:!0,get:function(){return o.migratePromise}}),Object.defineProperty(r,"DataMigrator",{enumerable:!0,get:function(){return o.DataMigrator}}),r.RxDBMigrationPlugin=r.DATA_MIGRATOR_BY_COLLECTION=void 0;var n=e("rxjs"),i=e("rxjs/operators"),o=e("./data-migrator"),a=e("./migration-state"),s=new WeakMap;r.DATA_MIGRATOR_BY_COLLECTION=s;var u={name:"migration",rxdb:!0,hooks:{preDestroyRxDatabase:a.onDatabaseDestroy},prototypes:{RxDatabase:function(e){e.migrationStates=function(){return(0,a.getMigrationStateByDatabase)(this).pipe((0,i.switchMap)((function(e){return(0,n.combineLatest)(e)})),(0,i.shareReplay)({bufferSize:1,refCount:!0}))}},RxCollection:function(e){e.getDataMigrator=function(){return s.has(this)||s.set(this,(0,o.createDataMigrator)(this.asRxCollection,this.migrationStrategies)),s.get(this)},e.migrationNeeded=function(){return(0,o.mustMigrate)(this.getDataMigrator())}}}};r.RxDBMigrationPlugin=u},{"./data-migrator":27,"./migration-state":29,rxjs:684,"rxjs/operators":908}],29:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getMigrationStateByDatabase=function(e){o.has(e)||o.set(e,new n.BehaviorSubject([]));var t=o.get(e);return(0,i.ensureNotFalsy)(t)},r.onDatabaseDestroy=function(e){var t=o.get(e);t&&t.complete()},r.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE=void 0;var n=e("rxjs"),i=e("../../util"),o=new WeakMap;r.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE=o},{"../../util":56,rxjs:684}],30:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={runBuildingStep:!0,applyBuildingStep:!0,RxDBQueryBuilderPlugin:!0};r.runBuildingStep=s,r.applyBuildingStep=u,r.RxDBQueryBuilderPlugin=void 0;var i=e("./mquery/nosql-query-builder");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===i[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return i[e]}}))}));var o=e("../../rx-query"),a=e("../../util");function s(e,t,r){var n=(0,i.createQueryBuilder)((0,a.clone)(e.mangoQuery));e.other.queryBuilderPath&&(n._path=e.other.queryBuilderPath),n[t](r);var s=n.toJSON(),u=new o.RxQueryBase(e.op,s.query,e.collection);return s.path&&(u.other.queryBuilderPath=s.path),(0,o.tunnelQueryCache)(u)}function u(e,t){e[t]=function(e){return s(this,t,e)}}var c={name:"query-builder",rxdb:!0,prototypes:{RxQuery:function(e){["where","equals","eq","or","nor","and","mod","exists","elemMatch","sort"].forEach((function(t){u(e,t)})),i.OTHER_MANGO_ATTRIBUTES.forEach((function(t){u(e,t)})),i.OTHER_MANGO_OPERATORS.forEach((function(t){u(e,t)}))}}};r.RxDBQueryBuilderPlugin=c},{"../../rx-query":47,"../../util":56,"./mquery/nosql-query-builder":32}],31:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.merge=function e(t,r){Object.keys(r).forEach((function(o){n.includes(o)||(void 0===t[o]?t[o]=r[o]:i(r[o])?e(t[o],r[o]):t[o]=r[o])}))},r.isObject=i;var n=["__proto__","constructor","prototype"];function i(e){return"[object Object]"===e.toString()}},{}],32:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.mQuerySortToRxDBSort=a,r.canMerge=l,r.createQueryBuilder=function(e){return new o(e)},r.OTHER_MANGO_OPERATORS=r.OTHER_MANGO_ATTRIBUTES=r.NoSqlQueryBuilderClass=void 0;var n=e("./mquery-utils"),i=e("../../../rx-error"),o=function(){function e(e){if(this.options={},this._conditions={},this._fields={},e){var t=this;e.selector&&t.find(e.selector),e.limit&&t.limit(e.limit),e.skip&&t.skip(e.skip),e.sort&&e.sort.forEach((function(e){return t.sort(e)}))}}var t=e.prototype;return t.where=function(e,t){if(!arguments.length)return this;var r=typeof arguments[0];if("string"===r)return this._path=arguments[0],2===arguments.length&&(this._conditions[this._path]=arguments[1]),this;if("object"===r&&!Array.isArray(arguments[0]))return this.merge(arguments[0]);throw(0,i.newRxTypeError)("MQ1",{path:arguments[0]})},t.equals=function(e){this._ensurePath("equals");var t=this._path;return this._conditions[t]=e,this},t.eq=function(e){this._ensurePath("eq");var t=this._path;return this._conditions[t]=e,this},t.or=function(e){var t=this._conditions.$or||(this._conditions.$or=[]);return Array.isArray(e)||(e=[e]),t.push.apply(t,e),this},t.nor=function(e){var t=this._conditions.$nor||(this._conditions.$nor=[]);return Array.isArray(e)||(e=[e]),t.push.apply(t,e),this},t.and=function(e){var t=this._conditions.$and||(this._conditions.$and=[]);return Array.isArray(e)||(e=[e]),t.push.apply(t,e),this},t.mod=function(e,t){var r,n;1===arguments.length?(this._ensurePath("mod"),r=arguments[0],n=this._path):2!==arguments.length||Array.isArray(arguments[1])?3===arguments.length?(r=arguments.slice(1),n=arguments[0]):(r=arguments[1],n=arguments[0]):(this._ensurePath("mod"),r=arguments.slice(),n=this._path);var i=this._conditions[n]||(this._conditions[n]={});return i.$mod=r,this},t.exists=function(e,t){var r,n;0===arguments.length?(this._ensurePath("exists"),r=this._path,n=!0):1===arguments.length?"boolean"==typeof arguments[0]?(this._ensurePath("exists"),r=this._path,n=arguments[0]):(r=arguments[0],n=!0):2===arguments.length&&(r=arguments[0],n=arguments[1]);var i=this._conditions[r]||(this._conditions[r]={});return i.$exists=n,this},t.elemMatch=function(t,r){if(null===arguments[0])throw(0,i.newRxTypeError)("MQ2");var o,a,s;if("function"==typeof arguments[0])this._ensurePath("elemMatch"),a=this._path,o=arguments[0];else if((0,n.isObject)(arguments[0]))this._ensurePath("elemMatch"),a=this._path,s=arguments[0];else if("function"==typeof arguments[1])a=arguments[0],o=arguments[1];else{if(!arguments[1]||!(0,n.isObject)(arguments[1]))throw(0,i.newRxTypeError)("MQ2");a=arguments[0],s=arguments[1]}o&&(o(s=new e),s=s._conditions);var u=this._conditions[a]||(this._conditions[a]={});return u.$elemMatch=s,this},t.sort=function(e){var t,r=this;if(!e)return this;var o=typeof e;if(Array.isArray(e)){t=e.length;for(var a=0;a0||(0===l._lastEnsureEqual&&l._creationTime2&&void 0!==arguments[2]&&arguments[2];t=e.schema.swapIdToPrimary(t),e.schema.doKeyCompression()&&(t=e._keyCompressor.decompress(t));if(r)return t;return t=e._crypter.decrypt(t)},r.fillObjectDataBeforeInsert=function(e,t){var r=e.schema.fillObjectWithDefaults(t);if(r._id&&"_id"!==e.schema.primaryPath)throw(0,i.newRxError)("COL2",{data:t});"_id"!==e.schema.primaryPath||r._id||(r._id=(0,n.generateId)());return r};var n=e("./util"),i=e("./rx-error")},{"./rx-error":46,"./util":56}],41:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.create=k,r.isInstanceOf=A,r.default=r.RxCollectionBase=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("@babel/runtime/helpers/createClass")),s=e("rxjs/operators"),u=e("./util"),c=e("./pouch-db"),f=e("./rx-collection-helper"),l=e("./rx-query"),d=e("./rx-schema"),h=e("./rx-change-event"),p=e("./rx-error"),b=e("./crypter"),v=e("./doc-cache"),y=e("./query-cache"),m=e("./change-event-buffer"),g=e("./overwritable"),_=e("./hooks"),w=e("./rx-document"),S=e("./rx-document-prototype-merge"),x=["pre","post"],O=["insert","save","remove","create"],j=!1,E=function(){function e(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:{},s=arguments.length>7&&void 0!==arguments[7]?arguments[7]:{},u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:y.defaultCacheReplacementPolicy,c=arguments.length>9&&void 0!==arguments[9]?arguments[9]:{};this._isInMemory=!1,this.destroyed=!1,this._atomicUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._repStates=new Set,this.pouch={},this._docCache=(0,v.createDocCache)(),this._queryCache=(0,y.createQueryCache)(),this._crypter={},this._changeEventBuffer={},this.database=e,this.name=t,this.schema=r,this.pouchSettings=n,this.migrationStrategies=i,this.methods=o,this.attachments=a,this.options=s,this.cacheReplacementPolicy=u,this.statics=c,M(this.asRxCollection)}var t=e.prototype;return t.prepare=function(e){var t=this;this.pouch=this.database._spawnPouchDB(this.name,this.schema.version,this.pouchSettings),this.schema.doKeyCompression()&&(this._keyCompressor=g.overwritable.createKeyCompressor(this.schema));var r=e?Promise.resolve():this.pouch.info(),n=e?Promise.resolve():function(e,t){return t.then((function(){return e.pouch.getIndexes()})).then((function(e){var t=new Set;return e.indexes.forEach((function(e){return t.add(e.name)})),t})).then((function(r){return Promise.all(e.schema.indexes.map((function(n){var i=n.map((function(t){var r=t===e.schema.primaryPath?"_id":t;return e.schema.doKeyCompression()?e._keyCompressor.transformKey(r):r})),o="idx-rxdb-index-"+i.join(",");if(!r.has(o))return t.then((function(){return e.pouch.createIndex({name:o,ddoc:o,index:{fields:i}})}))})))}))}(this.asRxCollection,r);return this._crypter=(0,b.createCrypter)(this.database.password,this.schema),this._observable$=this.database.$.pipe((0,s.filter)((function(e){return e.collectionName===t.name}))),this._changeEventBuffer=(0,m.createChangeEventBuffer)(this.asRxCollection),this._subs.push(this._observable$.pipe((0,s.filter)((function(e){return!e.isLocal}))).subscribe((function(e){var r=t._docCache.get(e.documentId);r&&r._handleChangeEvent(e)}))),Promise.all([r,n])},t.migrationNeeded=function(){if(0===this.schema.version)return Promise.resolve(!1);throw(0,u.pluginMissing)("migration")},t.getDataMigrator=function(){throw(0,u.pluginMissing)("migration")},t.migrate=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this.getDataMigrator().migrate(e)},t.migratePromise=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this.getDataMigrator().migratePromise(e)},t._handleToPouch=function(e){return(0,f._handleToPouch)(this,e)},t._handleFromPouch=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return(0,f._handleFromPouch)(this,e,t)},t._pouchPut=function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e=this._handleToPouch(e),this.database.lockedRun((function(){return t.pouch.put(e)})).catch((function(n){if(r&&409===n.status)return t.database.lockedRun((function(){return t.pouch.get(e._id)})).then((function(r){return e._rev=r._rev,t.database.lockedRun((function(){return t.pouch.put(e)}))}));throw 409===n.status?(0,p.newRxError)("COL19",{id:e._id,pouchDbError:n,data:e}):n}))},t._pouchGet=function(e){var t=this;return this.pouch.get(e).then((function(e){return t._handleFromPouch(e)}))},t._pouchFind=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=e.keyCompress();return t&&(i.limit=t),this.database.lockedRun((function(){return r.pouch.find(i)})).then((function(e){return e.docs.map((function(e){return r._handleFromPouch(e,n)}))}))},t.$emit=function(e){return this.database.$emit(e)},t.insert=function(e){var t=this,r=null;if((0,w.isInstanceOf)(e)){if(!(r=e)._isTemporary)throw(0,p.newRxError)("COL1",{data:e});e=r.toJSON()}var n,i,o=(0,f.fillObjectDataBeforeInsert)(this,e),a=r;return this._runHooks("pre","insert",o).then((function(){return t.schema.validate(o),n=(0,u.now)(),t._pouchPut(o)})).then((function(e){return i=(0,u.now)(),o[t.schema.primaryPath]=e.id,o._rev=e.rev,r?r._dataSync$.next(o):a=(0,S.createRxDocument)(t,o),t._runHooks("post","insert",o,a)})).then((function(){var e=(0,h.createInsertEvent)(t,o,n,i,a);return t.$emit(e),a}))},t.bulkInsert=function(e){var t=this,r=e.map((function(e){return(0,f.fillObjectDataBeforeInsert)(t,e)}));return Promise.all(r.map((function(e){return t._runHooks("pre","insert",e).then((function(){return t.schema.validate(e),e}))}))).then((function(e){var r=e.map((function(e){return t._handleToPouch(e)})),n=new Map;return e.forEach((function(e){n.set(e[t.schema.primaryPath],e)})),t.database.lockedRun((function(){var e=(0,u.now)();return t.pouch.bulkDocs(r).then((function(e){var r=e.filter((function(e){return e.ok})).map((function(e){var r=n.get(e.id);return r._rev=e.rev,(0,S.createRxDocument)(t,r)}));return Promise.all(r.map((function(e){return t._runHooks("post","insert",n.get(e.primary),e)}))).then((function(){var t=e.filter((function(e){return!e.ok}));return{rxDocuments:r,errorResults:t}}))})).then((function(r){var n=r.rxDocuments,i=r.errorResults,o=(0,u.now)();return n.forEach((function(r){var n=(0,h.createInsertEvent)(t,r.toJSON(!0),e,o,r);t.$emit(n)})),{success:n,error:i}}))}))}))},t.bulkRemove=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,a,s,c,f,l,d,p,b=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.findByIds(t);case 2:return r=e.sent,n=[],a=new Map,Array.from(r.values()).forEach((function(e){var t=e.toJSON(!0);n.push(t),a.set(e.primary,t)})),e.next=8,Promise.all(n.map((function(e){var t=e[b.schema.primaryPath];return b._runHooks("pre","remove",e,r.get(t))})));case 8:return n.forEach((function(e){return e._deleted=!0})),s=n.map((function(e){return b._handleToPouch(e)})),e.next=12,this.database.lockedRun((0,o.default)(i.default.mark((function e(){var t;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return c=(0,u.now)(),e.next=3,b.pouch.bulkDocs(s);case 3:return t=e.sent,e.abrupt("return",t);case 5:case"end":return e.stop()}}),e)}))));case 12:return f=e.sent,l=(0,u.now)(),d=f.filter((function(e){return e.ok})),e.next=17,Promise.all(d.map((function(e){return b._runHooks("post","remove",a.get(e.id),r.get(e.id))})));case 17:return d.forEach((function(e){var t=r.get(e.id),n=(0,h.createDeleteEvent)(b,a.get(e.id),t._data,c,l,t);b.$emit(n)})),p=d.map((function(e){return r.get(e.id)})),e.abrupt("return",{success:p,error:d.filter((function(e){return!e.ok}))});case 20:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.upsert=function(e){var t=this,r=(0,u.flatClone)(e),n=r[this.schema.primaryPath];if(!n)throw(0,p.newRxError)("COL3",{primaryPath:this.schema.primaryPath,data:r});return this.findOne(n).exec().then((function(n){return n?(r._rev=n._rev,n.atomicUpdate((function(){return r})).then((function(){return n}))):t.insert(e)}))},t.atomicUpsert=function(e){var t,r=this,n=e[this.schema.primaryPath];if(!n)throw(0,p.newRxError)("COL4",{data:e});return t=(t=this._atomicUpsertQueues.has(n)?this._atomicUpsertQueues.get(n):Promise.resolve()).then((function(){return function(e,t,r){return e.findOne(t).exec().then((function(t){return t?{doc:t,inserted:!1}:e.insert(r).then((function(e){return{doc:e,inserted:!0}}))}))}(r,n,e)})).then((function(t){return t.inserted?t.doc:function(e,t){return e.atomicUpdate((function(e){return t._rev=e._rev,e._data=t,e._data})).then((function(){return e}))}(t.doc,e).then((function(){return(0,u.nextTick)()})).then((function(){return t.doc}))})),this._atomicUpsertQueues.set(n,t),t},t.find=function(e){if("string"==typeof e)throw(0,p.newRxError)("COL5",{queryObj:e});return e||(e=(0,l._getDefaultQuery)(this)),(0,l.createRxQuery)("find",e,this)},t.findOne=function(e){var t;if("string"==typeof e)t=(0,l.createRxQuery)("findOne",{selector:{_id:e}},this);else{if(e||(e=(0,l._getDefaultQuery)(this)),e.limit)throw(0,p.newRxError)("QU6");t=(0,l.createRxQuery)("findOne",e,this)}if("number"==typeof e||Array.isArray(e))throw(0,p.newRxTypeError)("COL6",{queryObj:e});return t},t.findByIds=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=new Map,n=[],t.forEach((function(e){var t=o._docCache.get(e);t?r.set(e,t):n.push(e)})),!(n.length>0)){e.next=8;break}return e.next=6,this.pouch.allDocs({include_docs:!0,keys:n});case 6:e.sent.rows.forEach((function(e){if(e.doc){var t=o._handleFromPouch(e.doc),n=(0,S.createRxDocument)(o,t);r.set(n.primary,n)}}));case 8:return e.abrupt("return",r);case 9:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.findByIds$=function(e){var t=this,r=null,n=-1,a=this.findByIds(e).then((function(e){n=t._changeEventBuffer.counter,r=e}));return this.$.pipe((0,s.startWith)(null),(0,s.mergeMap)((function(e){return a.then((function(){return e}))})),(0,s.mergeMap)(function(){var a=(0,o.default)(i.default.mark((function o(a){var s,c,f;return i.default.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:if(s=(0,u.ensureNotFalsy)(r),null!==(c=t._changeEventBuffer.getFrom(n+1))){i.next=10;break}return i.next=5,t.findByIds(e);case 5:f=i.sent,n=t._changeEventBuffer.counter,Array.from(f.entries()).forEach((function(e){var t=e[0],r=e[1];return s.set(t,r)})),i.next=11;break;case 10:c.filter((function(t){return e.includes(t.documentId)})).forEach((function(e){var r=e.operation;"INSERT"===r||"UPDATE"===r?s.set(e.documentId,t._docCache.get(e.documentId)):s.delete(e.documentId)}));case 11:return i.abrupt("return",s);case 12:case"end":return i.stop()}}),o)})));return function(e){return a.apply(this,arguments)}}()),(0,s.filter)((function(e){return!!e})),(0,s.shareReplay)({bufferSize:1,refCount:!0}))},t.dump=function(){throw(0,u.pluginMissing)("json-dump")},t.importDump=function(e){throw(0,u.pluginMissing)("json-dump")},t.watchForChanges=function(){throw(0,u.pluginMissing)("watch-for-changes")},t.sync=function(e){throw(0,u.pluginMissing)("replication")},t.syncGraphQL=function(e){throw(0,u.pluginMissing)("replication-graphql")},t.inMemory=function(){throw(0,u.pluginMissing)("in-memory")},t.addHook=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if("function"!=typeof r)throw(0,p.newRxTypeError)("COL7",{key:t,when:e});if(!x.includes(e))throw(0,p.newRxTypeError)("COL8",{key:t,when:e});if(!O.includes(t))throw(0,p.newRxError)("COL9",{key:t});if("post"===e&&"create"===t&&!0===n)throw(0,p.newRxError)("COL10",{when:e,key:t,parallel:n});var i=r.bind(this),o=n?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][o].push(i)},t.getHooks=function(e,t){try{return this.hooks[t][e]}catch(e){return{series:[],parallel:[]}}},t._runHooks=function(e,t,r,n){var i=this.getHooks(e,t);if(!i)return Promise.resolve();var o=i.series.map((function(e){return function(){return e(r,n)}}));return(0,u.promiseSeries)(o).then((function(){return Promise.all(i.parallel.map((function(e){return e(r,n)})))}))},t._runHooksSync=function(e,t,r,n){var i=this.getHooks(e,t);i&&i.series.forEach((function(e){return e(r,n)}))},t.newDocument=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e=this.schema.fillObjectWithDefaults(e);var t=(0,w.createWithConstructor)((0,S.getRxDocumentConstructor)(this),this,e);return t._isTemporary=!0,this._runHooksSync("post","create",e,t),t},t.destroy=function(){return this.destroyed?Promise.resolve(!1):(this._onDestroyCall&&this._onDestroyCall(),this._subs.forEach((function(e){return e.unsubscribe()})),this._changeEventBuffer&&this._changeEventBuffer.destroy(),Array.from(this._repStates).forEach((function(e){return e.cancel()})),delete this.database.collections[this.name],this.destroyed=!0,(0,_.runAsyncPluginHooks)("postDestroyRxCollection",this).then((function(){return!0})))},t.remove=function(){return this.database.removeCollection(this.name)},(0,a.default)(e,[{key:"$",get:function(){return this._observable$}},{key:"insert$",get:function(){return this.$.pipe((0,s.filter)((function(e){return"INSERT"===e.operation})))}},{key:"update$",get:function(){return this.$.pipe((0,s.filter)((function(e){return"UPDATE"===e.operation})))}},{key:"remove$",get:function(){return this.$.pipe((0,s.filter)((function(e){return"DELETE"===e.operation})))}},{key:"onDestroy",get:function(){var e=this;return this._onDestroy||(this._onDestroy=new Promise((function(t){return e._onDestroyCall=t}))),this._onDestroy}},{key:"asRxCollection",get:function(){return this}}]),e}();function M(e){if(!j){j=!0;var t=Object.getPrototypeOf(e);O.forEach((function(e){x.map((function(r){var n=r+(0,u.ucfirst)(e);t[n]=function(t,n){return this.addHook(r,e,t,n)}}))}))}}function k(e,t){var r=e.database,n=e.name,i=e.schema,o=e.pouchSettings,a=void 0===o?{}:o,s=e.migrationStrategies,u=void 0===s?{}:s,f=e.autoMigrate,l=void 0===f||f,h=e.statics,b=void 0===h?{}:h,v=e.methods,m=void 0===v?{}:v,g=e.attachments,w=void 0===g?{}:g,S=e.options,x=void 0===S?{}:S,O=e.cacheReplacementPolicy,j=void 0===O?y.defaultCacheReplacementPolicy:O;(0,c.validateCouchDBString)(n),(0,d.isInstanceOf)(i)||(i=(0,d.createRxSchema)(i)),Object.keys(m).filter((function(e){return i.topLevelFields.includes(e)})).forEach((function(e){throw(0,p.newRxError)("COL18",{funName:e})}));var M=new E(r,n,i,a,u,m,w,x,j,b);return M.prepare(t).then((function(){Object.entries(b).forEach((function(e){var t=e[0],r=e[1];Object.defineProperty(M,t,{get:function(){return r.bind(M)}})}));var e=Promise.resolve();return l&&0!==M.schema.version&&(e=M.migratePromise()),e})).then((function(){return(0,_.runPluginHooks)("createRxCollection",M),M}))}function A(e){return e instanceof E}r.RxCollectionBase=E;var P={create:k,isInstanceOf:A,RxCollectionBase:E};r.default=P},{"./change-event-buffer":2,"./crypter":4,"./doc-cache":5,"./hooks":7,"./overwritable":9,"./pouch-db":37,"./query-cache":38,"./rx-change-event":39,"./rx-collection-helper":40,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-error":46,"./rx-query":47,"./rx-schema":48,"./util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"rxjs/operators":908}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getLocalDocument=function(e,t){return e.get(n.LOCAL_PREFIX+t).catch((function(){return null}))},r.setLocalDocument=function(e,t,r){return e.put({_id:t,value:r}).then((function(){}))},r.putDocument=function(e,t){return e.put(t).then((function(e){return Object.assign({_id:e.id,_rev:e.rev},t)}))},r.getAllDocuments=function(e){return e.allDocs({include_docs:!0}).then((function(e){return e.rows}))},r.deleteStorageInstance=function(e){return e.destroy()},r.INTERNAL_STORAGE_NAME=void 0;var n=e("./util");r.INTERNAL_STORAGE_NAME="_rxdb_internal"},{"./util":56}],43:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r._ensureStorageTokenExists=j,r.writeToSocket=E,r._collectionNamePrimary=M,r._removeAllOfCollection=k,r.createRxDatabase=P,r.removeRxDatabase=R,r.checkAdapter=C,r.isInstanceOf=I,r.dbCount=D,r.default=r.RxDatabaseBase=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("@babel/runtime/helpers/createClass")),s=n(e("random-token")),u=e("custom-idle-queue"),c=e("broadcast-channel"),f=e("./util"),l=e("./rx-error"),d=e("./rx-schema"),h=e("./rx-change-event"),p=e("./overwritable"),b=e("./hooks"),v=e("rxjs"),y=e("rxjs/operators"),m=e("./pouch-db"),g=e("./rx-collection"),_=e("./rx-storage-pouchdb"),w=e("./rx-database-internal-store"),S={},x=0,O=function(){function e(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=arguments.length>6?arguments[6]:void 0;this.internalStore={},this.idleQueue=new u.IdleQueue,this.token=(0,s.default)(10),this._subs=[],this.destroyed=!1,this.subject=new v.Subject,this.observable$=this.subject.asObservable().pipe((0,y.filter)((function(e){return(0,h.isInstanceOf)(e)}))),this.name=e,this.adapter=t,this.password=r,this.multiInstance=n,this.eventReduce=i,this.options=o,this.pouchSettings=a,this.storage=(0,_.getRxStoragePouchDb)(t,a),this.collections={},x++}var t=e.prototype;return t.dangerousRemoveCollectionInfo=function(){var e=this;return(0,w.getAllDocuments)(this.internalStore).then((function(t){return Promise.all(t.map((function(e){return{_id:e.key,_rev:e.value.rev}})).map((function(t){return e.internalStore.remove(t._id,t._rev)})))}))},t._spawnPouchDB=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.storage.createStorageInstance(this.name,e,t,{pouchSettings:r})},t.$emit=function(e){e&&(this.subject.next(e),e.databaseToken===this.token&&E(this,e))},t.removeCollectionDoc=function(e,t){var r=this,n=M(e,t);return this.internalStore.get(n).then((function(e){return r.lockedRun((function(){return r.internalStore.remove(e)}))}))},t.addCollections=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a,s,u,c,h=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.internalStore,e.next=3,r.allDocs({include_docs:!0,keys:Object.keys(t).map((function(e){return M(e,t[e].schema)}))});case 3:return n=e.sent,o={},n.rows.forEach((function(e){e.error||(o[e.key]=e.doc)})),a={},e.next=9,Promise.all(Object.entries(t).map((function(e){var r=e[0],n=e[1],i=o[M(r,t[r].schema)],s=(0,f.flatClone)(n);s.name=r;var u=(0,d.createRxSchema)(n.schema);if(a[r]=u.hash,s.schema=u,s.database=h,h.collections[r])throw(0,l.newRxError)("DB3",{name:r});if(i&&i.schemaHash!==a[r])throw(0,l.newRxError)("DB6",{name:r,previousSchemaHash:i.schemaHash,schemaHash:a[r]});var c=(0,f.flatClone)(n);return c.database=h,c.name=r,(0,b.runPluginHooks)("preCreateRxCollection",c),(0,g.create)(s,!!i)})));case 9:if(s=e.sent,u=[],c={},s.forEach((function(e){var r=e.name;if(c[r]=e,e.schema.crypt&&!h.password)throw(0,l.newRxError)("DB7",{name:r});o[r]||u.push({_id:M(r,t[r].schema),schemaHash:a[r],schema:e.schema.normalized,version:e.schema.version}),h.collections[r]=e,h[r]||Object.defineProperty(h,r,{get:function(){return h.collections[r]}})})),!(u.length>0)){e.next=16;break}return e.next=16,r.bulkDocs({docs:u});case 16:return e.abrupt("return",c);case 17:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.collection=function(e){var t;return"string"==typeof e?Promise.resolve(this.collections[e]):this.addCollections((t={},t[e.name]=e,t)).then((function(t){return t[e.name]}))},t.removeCollection=function(e){var t=this;return this.collections[e]&&this.collections[e].destroy(),k(this,e).then((function(r){return r.map((function(r){return t._spawnPouchDB(e,r)}))})).then((function(e){return Promise.all(e.map((function(e){return t.lockedRun((function(){return e.destroy()}))})))})).then((function(){}))},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.dump=function(){throw(0,f.pluginMissing)("json-dump")},t.importDump=function(e){throw(0,f.pluginMissing)("json-dump")},t.server=function(e){throw(0,f.pluginMissing)("server")},t.backup=function(e){throw(0,f.pluginMissing)("backup")},t.leaderElector=function(){throw(0,f.pluginMissing)("leader-election")},t.isLeader=function(){throw(0,f.pluginMissing)("leader-election")},t.waitForLeadership=function(){throw(0,f.pluginMissing)("leader-election")},t.migrationStates=function(){throw(0,f.pluginMissing)("migration")},t.destroy=function(){var e=this;return this.destroyed?Promise.resolve(!1):((0,b.runPluginHooks)("preDestroyRxDatabase",this),x--,this.destroyed=!0,this._subs.map((function(e){return e.unsubscribe()})),this.requestIdlePromise().then((function(){return Promise.all(Object.keys(e.collections).map((function(t){return e.collections[t]})).map((function(e){return e.destroy()})))})).then((function(){return e.broadcastChannel?e.broadcastChannel.close():Promise.resolve()})).then((function(){return function(e,t){if(!S[e])return;var r=S[e].indexOf(t);S[e].splice(r,1)}(e.name,e.adapter)})).then((function(){return!0})))},t.remove=function(){var e=this;return this.destroy().then((function(){return R(e.name,e.adapter)}))},(0,a.default)(e,[{key:"$",get:function(){return this.observable$}}]),e}();function j(e){return e.internalStore.get(f.LOCAL_PREFIX+"storageToken").catch((function(){return e.internalStore.put({_id:f.LOCAL_PREFIX+"storageToken",value:(0,s.default)(10)}).catch((function(){})).then((function(){return(0,f.promiseWait)(0)}))})).then((function(){return e.internalStore.get(f.LOCAL_PREFIX+"storageToken")})).then((function(e){return e.value}))}function E(e,t){if(e.multiInstance&&!t.isIntern()&&e.broadcastChannel){var r={cE:t.toJSON(),storageToken:e.storageToken};return e.broadcastChannel.postMessage(r).then((function(){return!0}))}return Promise.resolve(!1)}function M(e,t){return e+"-"+t.version}function k(e,t){return e.lockedRun((function(){return(0,w.getAllDocuments)(e.internalStore)})).then((function(r){var n=r.map((function(e){return e.doc})).filter((function(e){return e._id.split("-")[0]===t}));return Promise.all(n.map((function(t){return e.lockedRun((function(){return e.internalStore.remove(t)}))}))).then((function(){return n.map((function(e){return e.version}))}))}))}function A(e){return e.storage.createInternalStorageInstance(e.name).then((function(t){return e.internalStore=t,j(e)})).then((function(t){e.storageToken=t,e.multiInstance&&function(e){e.broadcastChannel=new c.BroadcastChannel("RxDB:"+e.name+":socket"),e.broadcastChannel$=new v.Subject,e.broadcastChannel.onmessage=function(t){if(t.storageToken===e.storageToken&&t.cE.databaseToken!==e.token){var r=new h.RxChangeEvent(t.cE.operation,t.cE.documentId,t.cE.documentData,t.cE.databaseToken,t.cE.collectionName,t.cE.isLocal,t.cE.startTime,t.cE.endTime,t.cE.previousData);e.broadcastChannel$.next(r)}},e._subs.push(e.broadcastChannel$.subscribe((function(t){e.$emit(t)})))}(e)}))}function P(e){var t=e.name,r=e.adapter,n=e.password,i=e.multiInstance,o=void 0===i||i,a=e.eventReduce,s=void 0!==a&&a,u=e.ignoreDuplicate,c=void 0!==u&&u,f=e.options,d=void 0===f?{}:f,h=e.pouchSettings,v=void 0===h?{}:h;if((0,b.runPluginHooks)("preCreateRxDatabase",{name:t,adapter:r,password:n,multiInstance:o,eventReduce:s,ignoreDuplicate:c,options:d,pouchSettings:v}),"string"==typeof r){if(!m.PouchDB.adapters||!m.PouchDB.adapters[r])throw(0,l.newRxError)("DB9",{adapter:r})}else if((0,m.isLevelDown)(r),!m.PouchDB.adapters||!m.PouchDB.adapters.leveldb)throw(0,l.newRxError)("DB10",{adapter:r});n&&p.overwritable.validatePassword(n),c||function(e,t){if(!S[e])return!1;var r=!1;if(S[e].forEach((function(e){e===t&&(r=!0)})),r)throw(0,l.newRxError)("DB8",{name:e,adapter:t,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(t,r),S[t]||(S[t]=[]),S[t].push(r);var y=new O(t,r,n,o,s,d,v);return A(y).then((function(){return(0,b.runAsyncPluginHooks)("createRxDatabase",y)})).then((function(){return y}))}function R(e,t){var r=(0,_.getRxStoragePouchDb)(t);return r.createInternalStorageInstance(e).then((function(t){return(0,w.getAllDocuments)(t).then((function(t){return Promise.all(t.map((function(e){return e.id})).map((function(t){var n=t.split("-"),i=n[0],o=parseInt(n[1],10);return r.createStorageInstance(e,i,o).destroy()})))})).then((function(){return(0,w.deleteStorageInstance)(t)}))}))}function C(e){return p.overwritable.checkAdapter(e)}function I(e){return e instanceof O}function D(){return x}r.RxDatabaseBase=O;var B={createRxDatabase:P,removeRxDatabase:R,checkAdapter:C,isInstanceOf:I,RxDatabaseBase:O,dbCount:D};r.default=B},{"./hooks":7,"./overwritable":9,"./pouch-db":37,"./rx-change-event":39,"./rx-collection":41,"./rx-database-internal-store":42,"./rx-error":46,"./rx-schema":48,"./rx-storage-pouchdb":49,"./util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"broadcast-channel":112,"custom-idle-queue":494,"random-token":675,rxjs:684,"rxjs/operators":908}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getDocumentPrototype=s,r.getRxDocumentConstructor=u,r.createRxDocument=c,r.createRxDocuments=function(e,t){return t.map((function(t){return c(e,t)}))},r.getDocumentOrmPrototype=f;var n=e("./rx-document"),i=e("./hooks"),o=new WeakMap,a=new WeakMap;function s(e){if(!o.has(e)){var t=e.schema.getDocumentPrototype(),r=f(e),i=n.basePrototype,a={};[t,r,i].forEach((function(e){Object.getOwnPropertyNames(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t),n=!0;(t.startsWith("_")||t.endsWith("_")||t.startsWith("$")||t.endsWith("$"))&&(n=!1),"function"==typeof r.value?Object.defineProperty(a,t,{get:function(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(a,t,r))}))})),o.set(e,a)}return o.get(e)}function u(e){if(!a.has(e)){var t=(0,n.createRxDocumentConstructor)(s(e));a.set(e,t)}return a.get(e)}function c(e,t){var r=t[e.schema.primaryPath],o=e._docCache.get(r);if(o)return o;var a=(0,n.createWithConstructor)(u(e),e,t);return e._docCache.set(r,a),e._runHooksSync("post","create",t,a),(0,i.runPluginHooks)("postCreateRxDocument",a),a}function f(e){var t={};return Object.entries(e.methods).forEach((function(e){var r=e[0],n=e[1];t[r]=n})),t}},{"./hooks":7,"./rx-document":45}],45:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.createRxDocumentConstructor=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:h,t=function(e,t){this.collection=e,this._isTemporary=!1,this._dataSync$=new s.BehaviorSubject(t),this._deleted$=new s.BehaviorSubject(!1),this._atomicQueue=Promise.resolve(),this.isInstanceOfRxDocument=!0};return t.prototype=e,t},r.defineGetterSetter=p,r.createWithConstructor=function(e,t,r){if(r[t.schema.primaryPath]&&r[t.schema.primaryPath].startsWith("_design"))return null;var n=new e(t,r);return(0,d.runPluginHooks)("createRxDocument",n),n},r.isInstanceOf=function(e){return void 0!==e&&!!e.isInstanceOfRxDocument},r.basePrototype=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("object-path")),s=e("rxjs"),u=e("rxjs/operators"),c=e("./util"),f=e("./rx-change-event"),l=e("./rx-error"),d=e("./hooks"),h={get _data(){if(this.isInstanceOfRxDocument)return this._dataSync$.getValue()},get primaryPath(){if(this.isInstanceOfRxDocument)return this.collection.schema.primaryPath},get primary(){var e=this;if(e.isInstanceOfRxDocument)return e._data[e.primaryPath]},get revision(){if(this.isInstanceOfRxDocument)return this._data._rev},get deleted$(){if(this.isInstanceOfRxDocument)return this._deleted$.asObservable()},get deleted(){if(this.isInstanceOfRxDocument)return this._deleted$.getValue()},get $(){return this._dataSync$.asObservable()},_handleChangeEvent:function(e){if(e.documentId===this.primary){var t=(0,c.getHeightOfRevision)(e.documentData._rev);if(!((0,c.getHeightOfRevision)(this._data._rev)>t))switch(e.operation){case"INSERT":break;case"UPDATE":var r=e.documentData;this._dataSync$.next(r);break;case"DELETE":this.collection._docCache.delete(this.primary),this._deleted$.next(!0)}}},$emit:function(e){return this.collection.$emit(e)},get$:function(e){if(e.includes(".item."))throw(0,l.newRxError)("DOC1",{path:e});if(e===this.primaryPath)throw(0,l.newRxError)("DOC2");if(this.collection.schema.finalFields.includes(e))throw(0,l.newRxError)("DOC3",{path:e});if(!this.collection.schema.getSchemaByObjectPath(e))throw(0,l.newRxError)("DOC4",{path:e});return this._dataSync$.pipe((0,u.map)((function(t){return a.default.get(t,e)})),(0,u.distinctUntilChanged)())},populate:function(e){var t=this.collection.schema.getSchemaByObjectPath(e),r=this.get(e);if(!r)return Promise.resolve(null);if(!t)throw(0,l.newRxError)("DOC5",{path:e});if(!t.ref)throw(0,l.newRxError)("DOC6",{path:e,schemaObj:t});var n=this.collection.database.collections[t.ref];if(!n)throw(0,l.newRxError)("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?n.findByIds(r).then((function(e){var t=e.values();return Array.from(t)})):n.findOne(r).exec()},get:function(e){if(this._data){var t=a.default.get(this._data,e);return"object"!=typeof(t=(0,c.clone)(t))||Array.isArray(t)||p(this.collection.schema,t,e,this),t}},toJSON:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=(0,c.clone)(this._data);return e||(delete t._rev,delete t._attachments),t},set:function(e,t){if(!this._isTemporary)throw(0,l.newRxTypeError)("DOC16",{objPath:e,value:t});if("string"!=typeof e)throw(0,l.newRxTypeError)("DOC15",{objPath:e,value:t});if(!Object.is(this.get(e),t)){var r=e.split(".");r.pop();var n=r.join(".");if(void 0===a.default.get(this._data,n))throw(0,l.newRxError)("DOC10",{childpath:e,rootPath:n});return a.default.set(this._data,e,t),this}},update:function(e){throw(0,c.pluginMissing)("update")},putAttachment:function(){throw(0,c.pluginMissing)("attachments")},getAttachment:function(){throw(0,c.pluginMissing)("attachments")},allAttachments:function(){throw(0,c.pluginMissing)("attachments")},get allAttachments$(){throw(0,c.pluginMissing)("attachments")},atomicUpdate:function(e){var t=this;return new Promise((function(r,n){t._atomicQueue=t._atomicQueue.then((0,o.default)(i.default.mark((function o(){var a,s,u;return i.default.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:a=!1;case 1:if(a){i.next=24;break}return s=t._dataSync$.getValue(),i.prev=3,i.next=6,e((0,c.clone)(t._dataSync$.getValue()),t);case 6:return u=i.sent,t.collection&&(u=t.collection.schema.fillObjectWithDefaults(u)),i.next=10,t._saveData(u,s);case 10:a=!0,i.next=22;break;case 13:if(i.prev=13,i.t0=i.catch(3),!(0,l.isPouchdbConflictError)(i.t0)){i.next=20;break}return i.next=18,(0,c.nextTick)();case 18:i.next=22;break;case 20:return n(i.t0),i.abrupt("return");case 22:i.next=1;break;case 24:r(t);case 25:case"end":return i.stop()}}),o,null,[[3,13]])}))))}))},atomicPatch:function(e){return this.atomicUpdate((function(t){return Object.entries(e).forEach((function(e){var r=e[0],n=e[1];t[r]=n})),t}))},atomicSet:function(e,t){return this.atomicUpdate((function(r){return a.default.set(r,e,t),r}))},_saveData:function(e,t){var r,n=this;if(e=e,this._deleted$.getValue())throw(0,l.newRxError)("DOC11",{id:this.primary,document:this});return this.collection.schema.validateChange(t,e),this.collection._runHooks("pre","save",e,this).then((function(){return n.collection.schema.validate(e),r=(0,c.now)(),n.collection._pouchPut(e)})).then((function(i){var o=(0,c.now)();if(!i.ok)throw(0,l.newRxError)("DOC12",{data:i});e._rev=i.rev;var a=(0,f.createUpdateEvent)(n.collection,e,t,r,o,n);return n.$emit(a),n.collection._runHooks("post","save",e,n)}))},save:function(){var e=this;if(!this._isTemporary)throw(0,l.newRxError)("DOC17",{id:this.primary,document:this});return this.collection.insert(this).then((function(){return e._isTemporary=!1,e.collection._docCache.set(e.primary,e),e._dataSync$.next(e._data),!0}))},remove:function(){var e=this;if(this.deleted)return Promise.reject((0,l.newRxError)("DOC13",{document:this,id:this.primary}));var t,r=(0,c.clone)(this._data);return this.collection._runHooks("pre","remove",r,this).then((function(){return r._deleted=!0,t=(0,c.now)(),e.collection._pouchPut(r)})).then((function(){var n=(0,c.now)();return e.$emit((0,f.createDeleteEvent)(e.collection,r,e._data,t,n,e)),e.collection._runHooks("post","remove",r,e)})).then((function(){return e}))},destroy:function(){throw(0,l.newRxError)("DOC14")}};function p(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(null!==t){var i=e.getSchemaByObjectPath(r);void 0!==i&&(i.properties&&(i=i.properties),Object.keys(i).forEach((function(e){var i=(0,c.trimDots)(r+"."+e);t.__defineGetter__(e,(function(){var e=n||this;if(e.get&&"function"==typeof e.get)return e.get(i)})),Object.defineProperty(t,e+"$",{get:function(){return(n||this).get$(i)},enumerable:!1,configurable:!1}),Object.defineProperty(t,e+"_",{get:function(){return(n||this).populate(i)},enumerable:!1,configurable:!1}),t.__defineSetter__(e,(function(e){return(n||this).set(i,e)}))})))}}r.basePrototype=h},{"./hooks":7,"./rx-change-event":39,"./rx-error":46,"./util":56,"@babel/runtime/helpers/asyncToGenerator":60,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/regenerator":70,"object-path":630,rxjs:684,"rxjs/operators":908}],46:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.newRxError=function(e,t){return new c(e,s.overwritable.tunnelErrorMessage(e),t)},r.newRxTypeError=function(e,t){return new f(e,s.overwritable.tunnelErrorMessage(e),t)},r.isPouchdbConflictError=function(e){return!(!e.parameters||!e.parameters.pouchDbError||409!==e.parameters.pouchDbError.status)},r.RxTypeError=r.RxError=void 0;var i=n(e("@babel/runtime/helpers/createClass")),o=n(e("@babel/runtime/helpers/inheritsLoose")),a=n(e("@babel/runtime/helpers/wrapNativeSuper")),s=e("./overwritable");function u(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((function(t){var r="[object Object]";try{r=JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(e){}return t+":"+r})).join("\n"),t+="}")}(r)}var c=function(e){function t(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=u(r,t,i);return(n=e.call(this,o)||this).code=t,n.message=o,n.parameters=i,n.rxdb=!0,n}return(0,o.default)(t,e),t.prototype.toString=function(){return this.message},(0,i.default)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,a.default)(Error));r.RxError=c;var f=function(e){function t(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=u(r,t,i);return(n=e.call(this,o)||this).code=t,n.message=o,n.parameters=i,n.rxdb=!0,n}return(0,o.default)(t,e),t.prototype.toString=function(){return this.message},(0,i.default)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,a.default)(TypeError));r.RxTypeError=f},{"./overwritable":9,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/inheritsLoose":64,"@babel/runtime/helpers/interopRequireDefault":65,"@babel/runtime/helpers/wrapNativeSuper":69}],47:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r._getDefaultQuery=y,r.tunnelQueryCache=m,r.createRxQuery=function(e,t,r){if(t&&"object"!=typeof t)throw(0,f.newRxTypeError)("QU7",{queryObj:t});if(Array.isArray(t))throw(0,f.newRxTypeError)("QU8",{queryObj:t});(0,l.runPluginHooks)("preCreateRxQuery",{op:e,queryObj:t,collection:r});var n=new v(e,t,r);return n=m(n),(0,l.runPluginHooks)("createRxQuery",n),(0,p.triggerCacheReplacement)(r),n},r.isInstanceOf=function(e){return e instanceof v},r.RxQueryBase=void 0;var i=n(e("@babel/runtime/helpers/createClass")),o=n(e("deep-equal")),a=e("rxjs"),s=e("rxjs/operators"),u=e("pouchdb-selector-core"),c=e("./util"),f=e("./rx-error"),l=e("./hooks"),d=e("./rx-document-prototype-merge"),h=e("./event-reduce"),p=e("./query-cache"),b=0,v=function(){function e(e,t,r){this.id=++b,this._execOverDatabaseCount=0,this._creationTime=(0,c.now)(),this._lastEnsureEqual=0,this.other={},this.uncached=!1,this.refCount$=new a.BehaviorSubject(null),this._latestChangeEvent=-1,this._resultsData=null,this._resultsDataMap=new Map,this._lastExecStart=0,this._lastExecEnd=0,this._resultsDocs$=new a.BehaviorSubject(null),this._ensureEqualQueue=Promise.resolve(!1),this.op=e,this.mangoQuery=t,this.collection=r,t||(t=y(this.collection))}var t=e.prototype;return t._setResultData=function(e){this._resultsData=e;var t=(0,d.createRxDocuments)(this.collection,this._resultsData);return this._resultsDocs$.next(t),t},t._execOverDatabase=function(){var e,t=this;switch(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,c.now)(),this.op){case"find":e=this.collection._pouchFind(this);break;case"findOne":e=this.collection._pouchFind(this,1);break;default:throw(0,f.newRxError)("QU1",{collection:this.collection.name,op:this.op})}return e.then((function(e){t._lastExecEnd=(0,c.now)(),t._resultsDataMap=new Map;var r=t.collection.schema.primaryPath;return e.forEach((function(e){var n=e[r];t._resultsDataMap.set(n,e)})),e}))},t.exec=function(e){var t=this;if(e&&"findOne"!==this.op)throw(0,f.newRxError)("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return g(this).then((function(){return(0,a.firstValueFrom)(t.$)})).then((function(r){if(!r&&e)throw(0,f.newRxError)("QU10",{collection:t.collection.name,query:t.mangoQuery,op:t.op});return r}))},t.toString=function(){var e=(0,c.sortObject)({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e,c.stringifyFilter);return this.toString=function(){return t},t},t.toJSON=function(){var e=this.collection.database.storage.prepareQuery(this.asRxQuery,(0,c.clone)(this.mangoQuery));return this.toJSON=function(){return e},e},t.keyCompress=function(){var e;return e=this.collection.schema.doKeyCompression()?this.collection._keyCompressor.compressQuery(this.toJSON()):this.toJSON(),this.keyCompress=function(){return e},e},t.doesDocumentDataMatch=function(e){if(e._deleted)return!1;e=this.collection.schema.swapPrimaryToId(e);var t=this.massageSelector,r={doc:e},n=(0,u.filterInMemoryFields)([r],{selector:t},Object.keys(t));return n&&1===n.length},t.remove=function(){var e;return this.exec().then((function(t){return e=t,Array.isArray(t)?Promise.all(t.map((function(e){return e.remove()}))):t.remove()})).then((function(){return e}))},t.update=function(e){throw(0,c.pluginMissing)("update")},t.where=function(e){throw(0,c.pluginMissing)("query-builder")},t.sort=function(e){throw(0,c.pluginMissing)("query-builder")},t.skip=function(e){throw(0,c.pluginMissing)("query-builder")},t.limit=function(e){throw(0,c.pluginMissing)("query-builder")},(0,i.default)(e,[{key:"$",get:function(){var e=this;if(!this._$){var t=this._resultsDocs$.pipe((0,s.mergeMap)((function(t){return g(e).then((function(e){return!e&&t}))})),(0,s.filter)((function(e){return!!e})),(0,s.map)((function(t){return"findOne"===e.op?0===t.length?null:t[0]:t})),(0,s.map)((function(e){return Array.isArray(e)?e.slice():e}))).asObservable(),r=this.collection.$.pipe((0,s.tap)((function(){return g(e)})),(0,s.filter)((function(){return!1})));this._$=(0,a.merge)(t,r,this.refCount$.pipe((0,s.filter)((function(){return!1}))))}return this._$}},{key:"massageSelector",get:function(){return(0,c.overwriteGetterForCaching)(this,"massageSelector",(0,u.massageSelector)(this.mangoQuery.selector))}},{key:"asRxQuery",get:function(){return this}}]),e}();function y(e){var t;return{selector:(t={},t[e.schema.primaryPath]={},t)}}function m(e){return e.collection._queryCache.getByQuery(e)}function g(e){return e._ensureEqualQueue=e._ensureEqualQueue.then((function(){return new Promise((function(e){return setTimeout(e,0)}))})).then((function(){return function(e){if(e._lastEnsureEqual=(0,c.now)(),e.collection.database.destroyed)return!1;if(function(e){return e._latestChangeEvent>=e.collection._changeEventBuffer.counter}(e))return!1;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var n=e.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===n)r=!0;else{e._latestChangeEvent=e.collection._changeEventBuffer.counter,n=n.filter((function(t){return!t.startTime||t.startTime>e._lastExecStart}));var i=e.collection._changeEventBuffer.reduceByLastOfDoc(n),a=(0,h.calculateNewResults)(e,i);a.runFullQueryAgain?r=!0:a.changed&&(t=!0,e._setResultData(a.newResults))}}if(r){var s=e.collection._changeEventBuffer.counter;return e._execOverDatabase().then((function(r){return e._latestChangeEvent=s,(0,o.default)(r,e._resultsData)||(t=!0,e._setResultData(r)),t}))}return t}(e)})).then((function(e){return new Promise((function(e){return setTimeout(e,0)})).then((function(){return e}))})),e._ensureEqualQueue}r.RxQueryBase=v},{"./event-reduce":6,"./hooks":7,"./query-cache":38,"./rx-document-prototype-merge":44,"./rx-error":46,"./util":56,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"deep-equal":496,"pouchdb-selector-core":665,rxjs:684,"rxjs/operators":908}],48:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.getIndexes=d,r.getPrimary=h,r.getPreviousVersions=function(e){var t=e.version?e.version:0,r=0;return new Array(t).fill(0).map((function(){return r++}))},r.getFinalFields=p,r.normalize=b,r.createRxSchema=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];t&&(0,c.runPluginHooks)("preCreateRxSchema",e);var r=new l(v(e));return(0,c.runPluginHooks)("createRxSchema",r),r},r.isInstanceOf=function(e){return e instanceof l},r.fillWithDefaultSettings=r.RxSchema=void 0;var i=n(e("@babel/runtime/helpers/createClass")),o=n(e("object-path")),a=n(e("deep-equal")),s=e("./util"),u=e("./rx-error"),c=e("./hooks"),f=e("./rx-document"),l=function(){function e(e){this.jsonSchema=e,this.indexes=d(this.jsonSchema),this.primaryPath=h(this.jsonSchema),this.primaryPath&&this.jsonSchema.required.push(this.primaryPath),this.finalFields=p(this.jsonSchema),this.jsonSchema.required=this.jsonSchema.required.concat(this.finalFields).filter((function(e,t,r){return r.indexOf(e)===t})),this.jsonSchema.properties[this.primaryPath]||(this.jsonSchema.properties[this.primaryPath]={type:"string",minLength:1})}var t=e.prototype;return t.getSchemaByObjectPath=function(e){var t=e;return t="properties."+(t=t.replace(/\./g,".properties.")),t=(0,s.trimDots)(t),o.default.get(this.jsonSchema,t)},t.validateChange=function(e,t){this.finalFields.forEach((function(r){if(!(0,a.default)(e[r],t[r]))throw(0,u.newRxError)("DOC9",{dataBefore:e,dataAfter:t,fieldName:r})}))},t.validate=function(e,t){throw(0,s.pluginMissing)("validate")},t.fillObjectWithDefaults=function(e){return e=(0,s.clone)(e),Object.entries(this.defaultValues).filter((function(t){var r=t[0];return!e.hasOwnProperty(r)||void 0===e[r]})).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.swapIdToPrimary=function(e){return"_id"===this.primaryPath||e[this.primaryPath]||(e[this.primaryPath]=e._id,delete e._id),e},t.swapPrimaryToId=function(e){var t=this;if("_id"===this.primaryPath)return e;var r={};return Object.entries(e).forEach((function(e){var n=e[0]===t.primaryPath?"_id":e[0];r[n]=e[1]})),r},t.doKeyCompression=function(){return this.jsonSchema.keyCompression},t.getDocumentPrototype=function(){var e={};return(0,f.defineGetterSetter)(this,e,""),(0,s.overwriteGetterForCaching)(this,"getDocumentPrototype",(function(){return e})),e},(0,i.default)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"normalized",get:function(){return(0,s.overwriteGetterForCaching)(this,"normalized",b(this.jsonSchema))}},{key:"topLevelFields",get:function(){return Object.keys(this.normalized.properties)}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.normalized.properties).filter((function(e){return e[1].hasOwnProperty("default")})).forEach((function(t){var r=t[0],n=t[1];return e[r]=n.default})),(0,s.overwriteGetterForCaching)(this,"defaultValues",e)}},{key:"crypt",get:function(){return!!(this.jsonSchema.encrypted&&this.jsonSchema.encrypted.length>0||this.jsonSchema.attachments&&this.jsonSchema.attachments.encrypted)}},{key:"encryptedPaths",get:function(){return this.jsonSchema.encrypted||[]}},{key:"hash",get:function(){return(0,s.overwriteGetterForCaching)(this,"hash",(0,s.hash)(this.normalized))}}]),e}();function d(e){return(e.indexes||[]).map((function(e){return Array.isArray(e)?e:[e]}))}function h(e){var t=Object.keys(e.properties).filter((function(t){return e.properties[t].primary})).shift();return t||"_id"}function p(e){var t=Object.keys(e.properties).filter((function(t){return e.properties[t].final}));return t.push(h(e)),t}function b(e){var t=(0,s.sortObject)((0,s.clone)(e));return e.indexes&&(t.indexes=Array.from(e.indexes)),t}r.RxSchema=l;var v=function(e){return(e=(0,s.clone)(e)).additionalProperties=!1,e.hasOwnProperty("keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes||[],e.required=e.required||[],e.encrypted=e.encrypted||[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.version=e.version||0,e};r.fillWithDefaultSettings=v},{"./hooks":7,"./rx-document":45,"./rx-error":46,"./util":56,"@babel/runtime/helpers/createClass":62,"@babel/runtime/helpers/interopRequireDefault":65,"deep-equal":496,"object-path":630}],49:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.primarySwapPouchDbQuerySelector=c,r.getPouchLocation=f,r.getRxStoragePouchDb=function(e,t){if(!e)throw new Error("adapter missing");return new u(e,t)},r.RxStoragePouchDbClass=void 0;var n=e("pouchdb-selector-core"),i=e("./util"),o=e("./hooks"),a=e("./pouch-db"),s=e("./rx-error"),u=function(){function e(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.name="pouchdb",this.adapter=e,this.pouchSettings=t}var t=e.prototype;return t.getSortComparator=function(e,t){var r,o=t.sort?t.sort:[(r={},r[e]="asc",r)],a=(0,n.massageSelector)(t.selector),s=Object.keys(t.selector);return function(t,r){var u=[t,r].map((function(t){var r=(0,i.flatClone)(t),n=r[e];return delete r[e],r._id=n,{doc:r}}));return(0,n.filterInMemoryFields)(u,{selector:a,sort:o},s)[0].doc._id===u[0].doc._id?-1:1}},t.getQueryMatcher=function(e,t){var r=(0,n.massageSelector)(t.selector);return function(o){var a=(0,i.flatClone)(o),s=a[e];delete a[e],a._id=s;var u={doc:a},c=(0,n.filterInMemoryFields)([u],{selector:r},Object.keys(t.selector));return c&&1===c.length}},t.createStorageInstance=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};n.pouchSettings||(n.pouchSettings={});var s=f(e,t,r),u={location:s,adapter:(0,i.adapterObject)(this.adapter),settings:n.pouchSettings},c=Object.assign({},u.adapter,this.pouchSettings,u.settings);return(0,o.runPluginHooks)("preCreatePouchDb",u),new a.PouchDB(u.location,c)},t.createInternalStorageInstance=function(e,t){var r=this.createStorageInstance(e,"_rxdb_internal",0,{pouchSettings:{auto_compaction:!1,revs_limit:1}});return Promise.resolve(r)},t.prepareQuery=function(e,t){var r=e.collection.schema.primaryPath,n=t;if(n.sort&&n.sort.forEach((function(t){var r=Object.keys(t)[0],i=["$gt","$gte","$lt","$lte"];if(!(n.selector[r]&&Object.keys(n.selector[r]).some((function(e){return i.includes(e)}))||!1)){var o=e.collection.schema.getSchemaByObjectPath(r);if(!o)throw(0,s.newRxError)("QU5",{key:r});switch(n.selector[r]||(n.selector[r]={}),o.type){case"number":case"integer":n.selector[r].$gt=-1e28;break;case"string":"string"!=typeof n.selector[r]&&(n.selector[r].$gt="");break;default:n.selector[r].$gt=null}}})),n.selector[r]&&n.selector[r].$regex)throw(0,s.newRxError)("QU4",{path:r,query:e.mangoQuery});if(n.sort){var i=n.sort.map((function(e){var t,n=Object.keys(e)[0],i=Object.values(e)[0];return(t={})[n===r?"_id":n]=i,t}));n.sort=i}return Object.entries(n.selector).forEach((function(e){var t=e[0],r=e[1];"object"!=typeof r||null===r||Array.isArray(r)||0!==Object.keys(r).length||delete n.selector[t]})),"_id"!==r&&(n.selector=c(n.selector,r)),n},e}();function c(e,t){if(Array.isArray(e))return e.map((function(e){return c(e,t)}));if("object"==typeof e){var r={};return Object.entries(e).forEach((function(e){var n=e[0],i=e[1];n===t?r._id=i:n.startsWith("$")?r[n]=c(i,t):r[n]=i})),r}return e}function f(e,t,r){var n=e+"-rxdb-"+r+"-";if(t.includes("/")){var i=t.split("/"),o=i.pop(),a=i.join("/");return a+="/"+n+o}return n+t}r.RxStoragePouchDbClass=u},{"./hooks":7,"./pouch-db":37,"./rx-error":46,"./util":56,"pouchdb-selector-core":665}],50:[function(e,t,r){},{}],51:[function(e,t,r){},{}],52:[function(e,t,r){},{}],53:[function(e,t,r){},{}],54:[function(e,t,r){},{}],55:[function(e,t,r){},{}],56:[function(e,t,r){(function(t){(function(){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.pluginMissing=function(e){var t=e.split("-"),r="RxDB";return t.forEach((function(e){r+=p(e)})),r+="Plugin",new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { "+r+" } from 'rxdb/plugins/"+e+"';\n addRxPlugin("+r+");\n ")},r.fastUnsecureHash=function(e){"string"!=typeof e&&(e=JSON.stringify(e));var t,r,n,i=0;if(0===e.length)return i;for(t=0,n=e.length;t0&&void 0!==arguments[0]?arguments[0]:0;return new Promise((function(t){return setTimeout(t,e)}))},r.toPromise=function(e){return e&&"function"==typeof e.then?e:Promise.resolve(e)},r.requestIdlePromise=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return"object"==typeof window&&window.requestIdleCallback?new Promise((function(t){return window.requestIdleCallback(t,{timeout:e})})):Promise.resolve()},r.promiseSeries=function(e,t){return e.reduce((function(e,t){return e.then(t)}),Promise.resolve(t))},r.requestIdleCallbackIfAvailable=function(e){"object"==typeof window&&window.requestIdleCallback&&window.requestIdleCallback(e)},r.ucfirst=p,r.trimDots=function(e){for(;"."===e.charAt(0);)e=e.substr(1);for(;"."===e.slice(-1);)e=e.slice(0,-1);return e},r.ensureNotFalsy=function(e){if(!e)throw new Error("ensureNotFalsy() is falsy");return e},r.sortObject=function e(t){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!t)return t;if(!r&&Array.isArray(t))return t.sort((function(e,t){return"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1})).map((function(t){return e(t,r)}));if("object"==typeof t&&!Array.isArray(t)){if(t instanceof RegExp)return t;var n={};return Object.keys(t).sort((function(e,t){return e.localeCompare(t)})).forEach((function(i){n[i]=e(t[i],r)})),n}return t},r.stringifyFilter=function(e,t){return t instanceof RegExp?t.toString():t},r.randomCouchString=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10,t="",r="abcdefghijklmnopqrstuvwxyz",n=0;n>1)],t)<=0?a=s+1:o=s-1}r(i[s],t)<=0&&s++;return i.splice(s,0,t),i}},{}],74:[function(e,t,r){"use strict";const n=r;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":75,"./asn1/base":77,"./asn1/constants":81,"./asn1/decoders":83,"./asn1/encoders":86,"bn.js":88}],75:[function(e,t,r){"use strict";const n=e("./encoders"),i=e("./decoders"),o=e("inherits");function a(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new a(e,t)},a.prototype._createNamed=function(e){const t=this.name;function r(e){this._initNamed(e,t)}return o(r,e),r.prototype._initNamed=function(t,r){e.call(this,t,r)},new r(this)},a.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(i[e])),this.decoders[e]},a.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},a.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n[e])),this.encoders[e]},a.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},{"./decoders":83,"./encoders":86,inherits:587}],76:[function(e,t,r){"use strict";const n=e("inherits"),i=e("../base/reporter").Reporter,o=e("safer-buffer").Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map((function(e){return s.isEncoderBuffer(e)||(e=new s(e,t)),this.length+=e.length,e}),this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),r.DecoderBuffer=a,a.isDecoderBuffer=function(e){if(e instanceof a)return!0;return"object"==typeof e&&o.isBuffer(e.base)&&"DecoderBuffer"===e.constructor.name&&"number"==typeof e.offset&&"number"==typeof e.length&&"function"==typeof e.save&&"function"==typeof e.restore&&"function"==typeof e.isEmpty&&"function"==typeof e.readUInt8&&"function"==typeof e.skip&&"function"==typeof e.raw},a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){const t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");const r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=s,s.isEncoderBuffer=function(e){if(e instanceof s)return!0;return"object"==typeof e&&"EncoderBuffer"===e.constructor.name&&"number"==typeof e.length&&"function"==typeof e.join},s.prototype.join=function(e,t){return e||(e=o.alloc(this.length)),t||(t=0),0===this.length||(Array.isArray(this.value)?this.value.forEach((function(r){r.join(e,t),t+=r.length})):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}},{"../base/reporter":79,inherits:587,"safer-buffer":910}],77:[function(e,t,r){"use strict";const n=r;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":76,"./node":78,"./reporter":79}],78:[function(e,t,r){"use strict";const n=e("../base/reporter").Reporter,i=e("../base/buffer").EncoderBuffer,o=e("../base/buffer").DecoderBuffer,a=e("minimalistic-assert"),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function c(e,t,r){const n={};this._baseState=n,n.name=r,n.enc=e,n.parent=t||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}t.exports=c;const f=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){const e=this._baseState,t={};f.forEach((function(r){t[r]=e[r]}));const r=new this.constructor(t.parent);return r._baseState=t,r},c.prototype._wrap=function(){const e=this._baseState;u.forEach((function(t){this[t]=function(){const r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}}),this)},c.prototype._init=function(e){const t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter((function(e){return e._baseState.parent===this}),this),a.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){const t=this._baseState,r=e.filter((function(e){return e instanceof this.constructor}),this);e=e.filter((function(e){return!(e instanceof this.constructor)}),this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach((function(e){e._baseState.parent=this}),this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map((function(e){if("object"!=typeof e||e.constructor!==Object)return e;const t={};return Object.keys(e).forEach((function(r){r==(0|r)&&(r|=0);const n=e[r];t[n]=r})),t})))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach((function(e){c.prototype[e]=function(){const t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}})),s.forEach((function(e){c.prototype[e]=function(){const t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}})),c.prototype.use=function(e){a(e);const t=this._baseState;return a(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){const t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){const t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){const t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){const e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){const t=this._baseState;return a(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){const t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map((function(t){return e[t]}))),this},c.prototype.contains=function(e){const t=this._baseState;return a(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){const r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));let n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){let n=null;if(null!==r.explicit?n=r.explicit:null!==r.implicit?n=r.implicit:null!==r.tag&&(n=r.tag),null!==n||r.any){if(a=this._peekTag(e,n,r.any),e.isError(a))return a}else{const n=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(n)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){const t=this._decodeTag(e,r.explicit);if(e.isError(t))return t;e=t}const n=e.offset;if(null===r.use&&null===r.choice){let t;r.any&&(t=e.save());const n=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(n))return n;r.any?i=e.raw(t):e=n}if(t&&t.track&&null!==r.tag&&t.track(e.path(),n,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),r.any||(i=null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t)),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach((function(r){r._decode(e,t)})),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){const n=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(n,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},c.prototype._decodeGeneric=function(e,t,r){const n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){const r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},c.prototype._decodeChoice=function(e,t){const r=this._baseState;let n=null,i=!1;return Object.keys(r.choice).some((function(o){const a=e.save(),s=r.choice[o];try{const r=s._decode(e,t);if(e.isError(r))return!1;n={type:o,value:r},i=!0}catch(t){return e.restore(a),!1}return!0}),this),i?n:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,r){const n=this._baseState;if(null!==n.default&&n.default===e)return;const i=this._encodeValue(e,t,r);return void 0===i||this._skipDefault(i,t,r)?void 0:i},c.prototype._encodeValue=function(e,t,r){const i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);let o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}let a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map((function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");const n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");const i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i}),this).filter((function(e){return e})),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");const r=this.clone();r._baseState.implicit=null,a=this._createEncoderBuffer(e.map((function(r){const n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)}),r))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){const e=null!==i.implicit?i.implicit:i.tag,r=null===i.implicit?"universal":"context";null===e?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(e,s,r,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){const r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){const r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},{"../base/buffer":76,"../base/reporter":79,"minimalistic-assert":618}],79:[function(e,t,r){"use strict";const n=e("inherits");function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}r.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){const e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){const t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){const t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){const n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){const e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){const t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){let t;const r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map((function(e){return"["+JSON.stringify(e)+"]"})).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){const t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:587}],80:[function(e,t,r){"use strict";function n(e){const t={};return Object.keys(e).forEach((function(r){(0|r)==r&&(r|=0);const n=e[r];t[n]=r})),t}r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=n(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=n(r.tag)},{}],81:[function(e,t,r){"use strict";const n=r;n._reverse=function(e){const t={};return Object.keys(e).forEach((function(r){(0|r)==r&&(r|=0);const n=e[r];t[n]=r})),t},n.der=e("./der")},{"./der":80}],82:[function(e,t,r){"use strict";const n=e("inherits"),i=e("bn.js"),o=e("../base/buffer").DecoderBuffer,a=e("../base/node"),s=e("../constants/der");function u(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){a.call(this,"der",e)}function f(e,t){let r=e.readUInt8(t);if(e.isError(r))return r;const n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){let n=r;for(r=0;128==(128&n);){if(n=e.readUInt8(t),e.isError(n))return n;r<<=7,r|=127&n}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function l(e,t,r){let n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;const i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(let t=0;t=31)return n.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=a.tagClassByName[r||"universal"]<<6,i}(e,t,r,this.reporter);if(n.length<128){const e=i.alloc(2);return e[0]=o,e[1]=n.length,this._createEncoderBuffer([e,n])}let s=1;for(let e=n.length;e>=256;e>>=8)s++;const u=i.alloc(2+s);u[0]=o,u[1]=128|s;for(let e=1+s,t=n.length;t>0;e--,t>>=8)u[e]=255&t;return this._createEncoderBuffer([u,n])},u.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){const t=i.alloc(2*e.length);for(let r=0;r=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let n=0;for(let t=0;t=128;r>>=7)n++}const o=i.alloc(n);let a=o.length-1;for(let t=e.length-1;t>=0;t--){let r=e[t];for(o[a--]=127&r;(r>>=7)>0;)o[a--]=128|127&r}return this._createEncoderBuffer(o)},u.prototype._encodeTime=function(e,t){let r;const n=new Date(e);return"gentime"===t?r=[c(n.getUTCFullYear()),c(n.getUTCMonth()+1),c(n.getUTCDate()),c(n.getUTCHours()),c(n.getUTCMinutes()),c(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[c(n.getUTCFullYear()%100),c(n.getUTCMonth()+1),c(n.getUTCDate()),c(n.getUTCHours()),c(n.getUTCMinutes()),c(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},u.prototype._encodeNull=function(){return this._createEncoderBuffer("")},u.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){const t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=i.from(t)}if(i.isBuffer(e)){let t=e.length;0===e.length&&t++;const r=i.alloc(t);return e.copy(r),0===e.length&&(r[0]=0),this._createEncoderBuffer(r)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let r=1;for(let t=e;t>=256;t>>=8)r++;const n=new Array(r);for(let t=n.length-1;t>=0;t--)n[t]=255&e,e>>=8;return 128&n[0]&&n.unshift(0),this._createEncoderBuffer(i.from(n))},u.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},u.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},u.prototype._skipDefault=function(e,t,r){const n=this._baseState;let i;if(null===n.default)return!1;const o=e.join();if(void 0===n.defaultBuffer&&(n.defaultBuffer=this._encodeValue(n.default,t,r).join()),o.length!==n.defaultBuffer.length)return!1;for(i=0;i=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(e,t,r){var n=s(e,r);return r-1>=t&&(n|=s(e,r-1)<<4),n}function c(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)i=u(e,t,n)<=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,u=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var f=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],l=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],d=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,l=67108863&u,d=Math.min(c,t.length-1),h=Math.max(0,c-e.length+1);h<=d;h++){var p=c-h|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[h])+l)/67108864|0,l=67108863&a}r.words[c]=0|l,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?f[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var c=l[e],h=d[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(h).toString(e);r=(p=p.idivn(h)).isZero()?b+r:f[c-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,h=0|a[1],p=8191&h,b=h>>>13,v=0|a[2],y=8191&v,m=v>>>13,g=0|a[3],_=8191&g,w=g>>>13,S=0|a[4],x=8191&S,O=S>>>13,j=0|a[5],E=8191&j,M=j>>>13,k=0|a[6],A=8191&k,P=k>>>13,R=0|a[7],C=8191&R,I=R>>>13,D=0|a[8],B=8191&D,T=D>>>13,L=0|a[9],N=8191&L,F=L>>>13,q=0|s[0],U=8191&q,z=q>>>13,$=0|s[1],W=8191&$,H=$>>>13,V=0|s[2],K=8191&V,G=V>>>13,Q=0|s[3],J=8191&Q,Y=Q>>>13,X=0|s[4],Z=8191&X,ee=X>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],le=8191&fe,de=fe>>>13,he=0|s[9],pe=8191&he,be=he>>>13;r.negative=e.negative^t.negative,r.length=19;var ve=(c+(n=Math.imul(l,U))|0)+((8191&(i=(i=Math.imul(l,z))+Math.imul(d,U)|0))<<13)|0;c=((o=Math.imul(d,z))+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,U),i=(i=Math.imul(p,z))+Math.imul(b,U)|0,o=Math.imul(b,z);var ye=(c+(n=n+Math.imul(l,W)|0)|0)+((8191&(i=(i=i+Math.imul(l,H)|0)+Math.imul(d,W)|0))<<13)|0;c=((o=o+Math.imul(d,H)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(y,U),i=(i=Math.imul(y,z))+Math.imul(m,U)|0,o=Math.imul(m,z),n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,H)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,H)|0;var me=(c+(n=n+Math.imul(l,K)|0)|0)+((8191&(i=(i=i+Math.imul(l,G)|0)+Math.imul(d,K)|0))<<13)|0;c=((o=o+Math.imul(d,G)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(_,U),i=(i=Math.imul(_,z))+Math.imul(w,U)|0,o=Math.imul(w,z),n=n+Math.imul(y,W)|0,i=(i=i+Math.imul(y,H)|0)+Math.imul(m,W)|0,o=o+Math.imul(m,H)|0,n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,G)|0;var ge=(c+(n=n+Math.imul(l,J)|0)|0)+((8191&(i=(i=i+Math.imul(l,Y)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,Y)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(x,U),i=(i=Math.imul(x,z))+Math.imul(O,U)|0,o=Math.imul(O,z),n=n+Math.imul(_,W)|0,i=(i=i+Math.imul(_,H)|0)+Math.imul(w,W)|0,o=o+Math.imul(w,H)|0,n=n+Math.imul(y,K)|0,i=(i=i+Math.imul(y,G)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,G)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,Y)|0;var _e=(c+(n=n+Math.imul(l,Z)|0)|0)+((8191&(i=(i=i+Math.imul(l,ee)|0)+Math.imul(d,Z)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(E,U),i=(i=Math.imul(E,z))+Math.imul(M,U)|0,o=Math.imul(M,z),n=n+Math.imul(x,W)|0,i=(i=i+Math.imul(x,H)|0)+Math.imul(O,W)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(_,K)|0,i=(i=i+Math.imul(_,G)|0)+Math.imul(w,K)|0,o=o+Math.imul(w,G)|0,n=n+Math.imul(y,J)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(m,J)|0,o=o+Math.imul(m,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,ee)|0;var we=(c+(n=n+Math.imul(l,re)|0)|0)+((8191&(i=(i=i+Math.imul(l,ne)|0)+Math.imul(d,re)|0))<<13)|0;c=((o=o+Math.imul(d,ne)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(A,U),i=(i=Math.imul(A,z))+Math.imul(P,U)|0,o=Math.imul(P,z),n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,H)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(x,K)|0,i=(i=i+Math.imul(x,G)|0)+Math.imul(O,K)|0,o=o+Math.imul(O,G)|0,n=n+Math.imul(_,J)|0,i=(i=i+Math.imul(_,Y)|0)+Math.imul(w,J)|0,o=o+Math.imul(w,Y)|0,n=n+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(m,Z)|0,o=o+Math.imul(m,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Se=(c+(n=n+Math.imul(l,oe)|0)|0)+((8191&(i=(i=i+Math.imul(l,ae)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,ae)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(C,U),i=(i=Math.imul(C,z))+Math.imul(I,U)|0,o=Math.imul(I,z),n=n+Math.imul(A,W)|0,i=(i=i+Math.imul(A,H)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,H)|0,n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,G)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,G)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,Y)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Y)|0,n=n+Math.imul(_,Z)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,n=n+Math.imul(y,re)|0,i=(i=i+Math.imul(y,ne)|0)+Math.imul(m,re)|0,o=o+Math.imul(m,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var xe=(c+(n=n+Math.imul(l,ue)|0)|0)+((8191&(i=(i=i+Math.imul(l,ce)|0)+Math.imul(d,ue)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(B,U),i=(i=Math.imul(B,z))+Math.imul(T,U)|0,o=Math.imul(T,z),n=n+Math.imul(C,W)|0,i=(i=i+Math.imul(C,H)|0)+Math.imul(I,W)|0,o=o+Math.imul(I,H)|0,n=n+Math.imul(A,K)|0,i=(i=i+Math.imul(A,G)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,G)|0,n=n+Math.imul(E,J)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(x,Z)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(_,re)|0,i=(i=i+Math.imul(_,ne)|0)+Math.imul(w,re)|0,o=o+Math.imul(w,ne)|0,n=n+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,ae)|0)+Math.imul(m,oe)|0,o=o+Math.imul(m,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var Oe=(c+(n=n+Math.imul(l,le)|0)|0)+((8191&(i=(i=i+Math.imul(l,de)|0)+Math.imul(d,le)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(N,U),i=(i=Math.imul(N,z))+Math.imul(F,U)|0,o=Math.imul(F,z),n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,H)|0)+Math.imul(T,W)|0,o=o+Math.imul(T,H)|0,n=n+Math.imul(C,K)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,G)|0,n=n+Math.imul(A,J)|0,i=(i=i+Math.imul(A,Y)|0)+Math.imul(P,J)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(x,re)|0,i=(i=i+Math.imul(x,ne)|0)+Math.imul(O,re)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(_,oe)|0,i=(i=i+Math.imul(_,ae)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,ae)|0,n=n+Math.imul(y,ue)|0,i=(i=i+Math.imul(y,ce)|0)+Math.imul(m,ue)|0,o=o+Math.imul(m,ce)|0,n=n+Math.imul(p,le)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(b,le)|0,o=o+Math.imul(b,de)|0;var je=(c+(n=n+Math.imul(l,pe)|0)|0)+((8191&(i=(i=i+Math.imul(l,be)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(N,W),i=(i=Math.imul(N,H))+Math.imul(F,W)|0,o=Math.imul(F,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,G)|0)+Math.imul(T,K)|0,o=o+Math.imul(T,G)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,Y)|0)+Math.imul(I,J)|0,o=o+Math.imul(I,Y)|0,n=n+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,ee)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,ae)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,ae)|0,n=n+Math.imul(_,ue)|0,i=(i=i+Math.imul(_,ce)|0)+Math.imul(w,ue)|0,o=o+Math.imul(w,ce)|0,n=n+Math.imul(y,le)|0,i=(i=i+Math.imul(y,de)|0)+Math.imul(m,le)|0,o=o+Math.imul(m,de)|0;var Ee=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,K),i=(i=Math.imul(N,G))+Math.imul(F,K)|0,o=Math.imul(F,G),n=n+Math.imul(B,J)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(T,J)|0,o=o+Math.imul(T,Y)|0,n=n+Math.imul(C,Z)|0,i=(i=i+Math.imul(C,ee)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,ee)|0,n=n+Math.imul(A,re)|0,i=(i=i+Math.imul(A,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,ce)|0,n=n+Math.imul(_,le)|0,i=(i=i+Math.imul(_,de)|0)+Math.imul(w,le)|0,o=o+Math.imul(w,de)|0;var Me=(c+(n=n+Math.imul(y,pe)|0)|0)+((8191&(i=(i=i+Math.imul(y,be)|0)+Math.imul(m,pe)|0))<<13)|0;c=((o=o+Math.imul(m,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(N,J),i=(i=Math.imul(N,Y))+Math.imul(F,J)|0,o=Math.imul(F,Y),n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(C,re)|0,i=(i=i+Math.imul(C,ne)|0)+Math.imul(I,re)|0,o=o+Math.imul(I,ne)|0,n=n+Math.imul(A,oe)|0,i=(i=i+Math.imul(A,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(x,le)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(O,le)|0,o=o+Math.imul(O,de)|0;var ke=(c+(n=n+Math.imul(_,pe)|0)|0)+((8191&(i=(i=i+Math.imul(_,be)|0)+Math.imul(w,pe)|0))<<13)|0;c=((o=o+Math.imul(w,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(N,Z),i=(i=Math.imul(N,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(T,re)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(C,oe)|0,i=(i=i+Math.imul(C,ae)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,ae)|0,n=n+Math.imul(A,ue)|0,i=(i=i+Math.imul(A,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(E,le)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,le)|0,o=o+Math.imul(M,de)|0;var Ae=(c+(n=n+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,be)|0)+Math.imul(O,pe)|0))<<13)|0;c=((o=o+Math.imul(O,be)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(N,re),i=(i=Math.imul(N,ne))+Math.imul(F,re)|0,o=Math.imul(F,ne),n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,ae)|0,n=n+Math.imul(C,ue)|0,i=(i=i+Math.imul(C,ce)|0)+Math.imul(I,ue)|0,o=o+Math.imul(I,ce)|0,n=n+Math.imul(A,le)|0,i=(i=i+Math.imul(A,de)|0)+Math.imul(P,le)|0,o=o+Math.imul(P,de)|0;var Pe=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(N,oe),i=(i=Math.imul(N,ae))+Math.imul(F,oe)|0,o=Math.imul(F,ae),n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(T,ue)|0,o=o+Math.imul(T,ce)|0,n=n+Math.imul(C,le)|0,i=(i=i+Math.imul(C,de)|0)+Math.imul(I,le)|0,o=o+Math.imul(I,de)|0;var Re=(c+(n=n+Math.imul(A,pe)|0)|0)+((8191&(i=(i=i+Math.imul(A,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(N,ue),i=(i=Math.imul(N,ce))+Math.imul(F,ue)|0,o=Math.imul(F,ce),n=n+Math.imul(B,le)|0,i=(i=i+Math.imul(B,de)|0)+Math.imul(T,le)|0,o=o+Math.imul(T,de)|0;var Ce=(c+(n=n+Math.imul(C,pe)|0)|0)+((8191&(i=(i=i+Math.imul(C,be)|0)+Math.imul(I,pe)|0))<<13)|0;c=((o=o+Math.imul(I,be)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(N,le),i=(i=Math.imul(N,de))+Math.imul(F,le)|0,o=Math.imul(F,de);var Ie=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(T,pe)|0))<<13)|0;c=((o=o+Math.imul(T,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863;var De=(c+(n=Math.imul(N,pe))|0)+((8191&(i=(i=Math.imul(N,be))+Math.imul(F,pe)|0))<<13)|0;return c=((o=Math.imul(F,be))+(i>>>13)|0)+(De>>>26)|0,De&=67108863,u[0]=ve,u[1]=ye,u[2]=me,u[3]=ge,u[4]=_e,u[5]=we,u[6]=Se,u[7]=xe,u[8]=Oe,u[9]=je,u[10]=Ee,u[11]=Me,u[12]=ke,u[13]=Ae,u[14]=Pe,u[15]=Re,u[16]=Ce,u[17]=Ie,u[18]=De,0!==c&&(u[19]=c,r.length++),r};function b(e,t,r){return(new v).mulp(e,t,r)}function v(e,t){this.x=e,this.y=t}Math.imul||(p=h),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?p(this,e,t):r<63?h(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):b(this,e,t)},v.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},v.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var l=0|this.words[c];this.words[c]=f<<26-o|l>>>o,f=l&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;l--){var d=67108864*(0|n.words[i.length+l])+(0|n.words[i.length+l-1]);for(d=Math.min(d/a|0,67108863),n._ishlnsubmul(i,d,l);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(i,1,l),n.isZero()||(n.negative^=1);s&&(s.words[l]=d)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),l=t.clone();!t.isZero();){for(var d=0,h=1;0==(t.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(l)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(l)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var l=0,d=1;0==(r.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(r.iushrn(l);l-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new x(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function g(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function _(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function x(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function O(e){x.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(g,m),g.prototype.split=function(e,t){for(var r=4194303,n=Math.min(e.length,9),i=0;i>>22,o=a}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},g.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new g;else if("p224"===e)t=new _;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return y[e]=t,t},x.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},x.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},x.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},x.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},x.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},x.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},x.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},x.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},x.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},x.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},x.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},x.prototype.isqr=function(e){return this.imul(e,e.clone())},x.prototype.sqr=function(e){return this.mul(e,e)},x.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var l=this.pow(f,i),d=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=a;0!==h.cmp(s);){for(var b=h,v=0;0!==b.cmp(s);v++)b=b.redSqr();n(v=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var l=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==l||0!==a?(a<<=1,a|=l,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},x.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},x.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new O(e)},i(O,x),O.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},O.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},O.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},O.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},O.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:124}],89:[function(e,t,r){(function(r){(function(){"use strict";var n=e("array-filter");t.exports=function(){return n(["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],(function(e){return"function"==typeof r[e]}))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"array-filter":72}],90:[function(e,t,r){"use strict";r.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},r.toByteArray=function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),f=0,l=s>0?a-4:a;for(r=0;r>16&255,u[f++]=t>>8&255,u[f++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[f++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[f++]=t>>8&255,u[f++]=255&t);return u},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],a=16383,s=0,u=r-i;su?u:s+a));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function f(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],91:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./util"),i=e("./find-similar-node"),o=function(){function e(e,t,r){this.level=e,this.id=n.nextNodeId(),this.deleted=!1,this.type=r,this.rootNode=t,t&&this.rootNode.addNode(this)}return e.prototype.isEqualToOtherNode=function(e,t){return void 0===t&&(t=this.toString()),t===e.toString()},e.prototype.remove=function(){var e;if((this.ensureNotDeleted("remove"),this.isInternalNode())&&(e=this).parents.size>0)throw new Error("cannot remove node with parents "+this.id);this.branches&&((e=this).branches.areBranchesStrictEqual()?e.branches.getBranch("0").parents.remove(e):(e.branches.getBranch("0").parents.remove(e),e.branches.getBranch("1").parents.remove(e)));this.deleted=!0,this.rootNode.removeNode(this)},e.prototype.toJSON=function(e){void 0===e&&(e=!1);var t={id:e?this.id:void 0,deleted:e?this.deleted:void 0,type:this.type,level:this.level};if(e&&this.parents&&(t.parents=this.parents.toString()),this.isLeafNode()&&(t.value=this.asLeafNode().value),this.branches&&!this.branches.deleted){var r=this.branches;t.branches={0:r.getBranch("0").toJSON(e),1:r.getBranch("1").toJSON(e)}}return t},e.prototype.toString=function(){var e="<"+this.type+":"+this.level;if(this.branches){var t=this.branches;e+="|0:"+t.getBranch("0"),e+="|1:"+t.getBranch("1")}return this.isLeafNode()&&(e+="|v:"+this.asLeafNode().value),e+=">"},e.prototype.isRootNode=function(){return"RootNode"===this.type},e.prototype.isInternalNode=function(){return"InternalNode"===this.type},e.prototype.isLeafNode=function(){return"LeafNode"===this.type},e.prototype.asRootNode=function(){if(!this.isRootNode())throw new Error("ouch");return this},e.prototype.asInternalNode=function(){if(!this.isInternalNode())throw new Error("ouch");return this},e.prototype.asLeafNode=function(){if(!this.isLeafNode())throw new Error("ouch");return this},e.prototype.ensureNotDeleted=function(e){if(void 0===e&&(e="unknown"),this.deleted)throw new Error("forbidden operation "+e+" on deleted node "+this.id)},e.prototype.log=function(){console.log(JSON.stringify(this.toJSON(!0),null,2))},e.prototype.applyEliminationRule=function(e){var t=this;this.ensureNotDeleted("applyEliminationRule"),e||(e=this.rootNode.getNodesOfLevel(this.level));var r=i.findSimilarNode(this,e);if(r){var n=this.parents.getAll(),o=[];return n.forEach((function(e){var n=e.branches.getKeyOfNode(t);e.branches.setBranch(n,r),e.branches.areBranchesStrictEqual()&&o.push(e),t.parents.remove(e)})),o.forEach((function(e){e.isInternalNode()&&e.applyReductionRule()})),!0}return!1},e}();r.AbstractNode=o},{"./find-similar-node":96,"./util":109}],92:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e){this.node=e,this.deleted=!1,this.branches={}}return e.prototype.setBranch=function(e,t){this.branches[e]!==t&&(this.branches[e]=t,t.parents.add(this.node))},e.prototype.getKeyOfNode=function(e){if(this.getBranch("0")===e)return"0";if(this.getBranch("1")===e)return"1";throw new Error("none matched")},e.prototype.getBranch=function(e){return this.branches[e]},e.prototype.getBothBranches=function(){return[this.getBranch("0"),this.getBranch("1")]},e.prototype.hasBranchAsNode=function(e){return this.getBranch("0")===e||this.getBranch("1")===e},e.prototype.hasNodeIdAsBranch=function(e){return this.getBranch("0").id===e||this.getBranch("1").id===e},e.prototype.areBranchesStrictEqual=function(){return this.branches[0]===this.branches[1]},e.prototype.hasEqualBranches=function(){return JSON.stringify(this.branches[0])===JSON.stringify(this.branches[1])},e}();r.Branches=n,r.ensureNodesNotStrictEqual=function(e,t){if(e===t)throw new Error("cannot have two strict equal branches")}},{}],93:[function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a};Object.defineProperty(r,"__esModule",{value:!0});var o=e("./root-node"),a=e("./util"),s=e("./internal-node"),u=e("./leaf-node");r.createBddFromTruthTable=function(e){var t,r,c=new o.RootNode,f=e.keys().next().value.length,l=Math.pow(2,f);if(e.size!==l)throw new Error("truth table has missing entries");try{for(var d=n(e),h=d.next();!h.done;h=d.next()){for(var p=i(h.value,2),b=p[0],v=p[1],y=c,m=0;mr.length){var u=s[0],c=r.find((function(e){return!!e.isInternalNode()&&e.branches.hasNodeIdAsBranch(u)}));console.log("referenceToFirst:"),null==c||c.log()}throw new Error("ensureCorrectBdd() nodes in list not equal size to recursive nodes allNodes: "+r.length+" recursiveNodes: "+o.size+" nodesOnlyInRecursive: "+s.join(", ")+" ")}if(r.forEach((function(e){if(!e.isRootNode()){var t=e;if(e.deleted)throw new Error("ensureCorrectBdd() bdd includes a deleted node");if(0===t.parents.size)throw new Error("ensureCorrectBdd() node has no parent "+t.id);if(t.isInternalNode()){var r=t,n=r.branches.getBothBranches();if(r.branches.areBranchesStrictEqual())throw new Error("ensureCorrectBdd() node has two equal branches: "+n.map((function(e){return e.id})).join(", "));n.forEach((function(e){if(!e.parents.has(r))throw new Error("ensureCorrectBdd() branch must have the node as parent")}))}t.parents.getAll().forEach((function(e){if(!e.branches.hasBranchAsNode(t))throw new Error("ensureCorrectBdd() parent node does not have child as branch")}))}})),t.includes('"deleted":true'))throw new Error("ensureCorrectBdd() bdd includes a deleted node")},r.getNodesRecursive=n},{}],95:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./util");r.fillTruthTable=function(e,t,r){for(var i=n.maxBinaryWithLength(t),o=n.minBinaryWithLength(t),a=!1;!a;)e.has(o)||e.set(o,r),o===i?a=!0:o=n.getNextStateSet(o)}},{"./util":109}],96:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.findSimilarNode=function(e,t){for(var r=e.toString(),n=0;n99)throw new Error("cannot build string with too many leaf nodes");t+=n.toString().padStart(2,"0");var a=e.levels.slice().reverse(),s=new Map;return a.forEach((function(n){e.getNodesOfLevel(n).forEach((function(e){var n=o(e,s,r);r=n.nextCode,s.set(e,n.id),t+=n.str}))})),t},r.nodeToString=o},{"./string-format":105}],101:[function(e,t,r){"use strict";function n(e){var t=e.branches.getBranch("0"),r=e.branches.getBranch("1");return{l:e.level,0:t.isLeafNode()?t.asLeafNode().value:n(t),1:r.isLeafNode()?r.asLeafNode().value:n(r)}}Object.defineProperty(r,"__esModule",{value:!0}),r.bddToSimpleBdd=function(e){return n(e)},r.nodeToSimpleBddNode=n},{}],102:[function(e,t,r){"use strict";function n(e){for(var t in e)r.hasOwnProperty(t)||(r[t]=e[t])}Object.defineProperty(r,"__esModule",{value:!0}),n(e("./bdd-to-minimal-string")),n(e("./minimal-string-to-simple-bdd")),n(e("./resolve-with-simple-bdd")),n(e("./string-format")),n(e("./bdd-to-simple-bdd"))},{"./bdd-to-minimal-string":100,"./bdd-to-simple-bdd":101,"./minimal-string-to-simple-bdd":103,"./resolve-with-simple-bdd":104,"./string-format":105}],103:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("../util"),i=e("./string-format");r.minimalStringToSimpleBdd=function(e){for(var t=new Map,r=2+2*parseInt(e.charAt(0)+e.charAt(1),10),o=e.substring(2,r),a=n.splitStringToChunks(o,2),s=0;s=128&&e<=160&&(e=161),{char:String.fromCharCode(e),nextCode:e+1}}},{}],106:[function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function a(e){try{u(n.next(e))}catch(e){o(e)}}function s(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}u((n=n.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var r,n,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a};Object.defineProperty(r,"__esModule",{value:!0});var s=e("./create-bdd-from-truth-table"),u=e("./util");function c(e){var t,r,n=l(u.firstKeyOfMap(e).length),i=u.shuffleArray(n),s={},c={};i.forEach((function(e,t){s[t]=e,c[e]=t}));var d=new Map;try{for(var h=o(e.entries()),p=h.next();!p.done;p=h.next()){var b=a(p.value,2),v=b[0],y=b[1],m=f(v,s);d.set(m,y)}}catch(e){t={error:e}}finally{try{p&&!p.done&&(r=h.return)&&r.call(h)}finally{if(t)throw t.error}}return{newTable:d,mapping:s,mappingBeforeToAfter:c}}function f(e,t){return e.split("").map((function(e,r){return{char:e,indexBefore:r,indexAfter:t[r]}})).sort((function(e,t){return e.indexAfter-t.indexAfter})).map((function(e){return e.char})).join("")}function l(e){for(var t=[],r=0;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function e(e){this.node=e,this.parents=new Set}return e.prototype.remove=function(e){this.parents.delete(e),0===this.parents.size&&this.node.remove()},e.prototype.getAll=function(){return Array.from(this.parents)},e.prototype.add=function(e){if(this.node.level===e.level)throw new Error("a node cannot be parent of a node with the same level");this.parents.add(e)},e.prototype.has=function(e){return this.parents.has(e)},e.prototype.toString=function(){var e,t,r=[];try{for(var i=n(this.parents),o=i.next();!o.done;o=i.next()){var a=o.value;r.push(a.id)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return r.join(", ")},Object.defineProperty(e.prototype,"size",{get:function(){return this.parents.size},enumerable:!0,configurable:!0}),e}();r.Parents=i},{}],108:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var a=e("./abstract-node"),s=e("./branches"),u=e("./util"),c=e("./minimal-string"),f=function(e){function t(){var t=e.call(this,0,null,"RootNode")||this;t.branches=new s.Branches(t),t.levels=[],t.nodesByLevel=new Map,t.levels.push(0);var r=new Set;return r.add(t),t.nodesByLevel.set(0,r),t}return i(t,e),t.prototype.addNode=function(e){var t=e.level;this.levels.includes(t)||this.levels.push(t),this.ensureLevelSetExists(t);var r=this.nodesByLevel.get(t);null==r||r.add(e)},t.prototype.removeNode=function(e){var t=this.nodesByLevel.get(e.level);if(!t.has(e))throw new Error("removed non-existing node "+e.id);t.delete(e)},t.prototype.ensureLevelSetExists=function(e){this.nodesByLevel.has(e)||this.nodesByLevel.set(e,new Set)},t.prototype.getLevels=function(){return Array.from(this.levels).sort((function(e,t){return e-t}))},t.prototype.getNodesOfLevel=function(e){this.ensureLevelSetExists(e);var t=this.nodesByLevel.get(e);return Array.from(t)},t.prototype.countNodes=function(){var e=this,t=0;return this.getLevels().forEach((function(r){var n=e.getNodesOfLevel(r).length;t+=n})),t},t.prototype.minimize=function(e){var t,r;void 0===e&&(e=!1);for(var n=!1;!n;){e&&console.log("minimize() itterate once");for(var i=0,a=u.lastOfArray(this.getLevels());a>0;){var s=this.getNodesOfLevel(a);e&&console.log("minimize() run for level "+a+" with "+s.length+" nodes");var c=0;try{for(var f=(t=void 0,o(s)),l=f.next();!l.done;l=f.next()){var d=l.value;if(c++,e&&c%4e3==0&&console.log("minimize() node #"+d.id),d.isLeafNode())(p=d.asLeafNode().applyEliminationRule())&&i++;if(!d.deleted&&d.isInternalNode()){var h=d,p=h.applyReductionRule(),b=!1;h.deleted||(b=h.applyEliminationRule(s)),(p||b)&&i++}}}catch(e){t={error:e}}finally{try{l&&!l.done&&(r=f.return)&&r.call(f)}finally{if(t)throw t.error}}a--}0===i?n=!0:e&&console.log("minimize() itteration done with "+i+" minimisations")}},t.prototype.getLeafNodes=function(){var e=u.lastOfArray(this.getLevels());return this.getNodesOfLevel(e).reverse()},t.prototype.removeIrrelevantLeafNodes=function(e){for(var t,r,n=!1;!n;){var i=0,a=this.getLeafNodes();try{for(var s=(t=void 0,o(a)),u=s.next();!u.done;u=s.next()){u.value.removeIfValueEquals(e)&&i++}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}this.minimize(),0===i&&(n=!0)}},t.prototype.resolve=function(e,t){for(var r=this;;){var n=e[r.level](t),i=u.booleanToBooleanString(n);if((r=r.branches.getBranch(i)).isLeafNode())return r.asLeafNode().value}},t.prototype.toSimpleBdd=function(){return c.bddToSimpleBdd(this)},t}(a.AbstractNode);r.RootNode=f},{"./abstract-node":91,"./branches":92,"./minimal-string":102,"./util":109}],109:[function(e,t,r){"use strict";var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a};Object.defineProperty(r,"__esModule",{value:!0}),r.booleanStringToBoolean=function(e){return"1"===e},r.booleanToBooleanString=function(e){return e?"1":"0"},r.oppositeBoolean=function(e){return"1"===e?"0":"1"},r.lastChar=function(e){return e.slice(-1)};var i=function(e){void 0===e&&(e=6);for(var t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;i>>0).toString(2).padStart(t,"0")}function s(e){return parseInt(e,2)}r.nextNodeId=function(){var e="node_"+i+"_"+o;return o++,e},r.decimalToPaddedBinary=a,r.oppositeBinary=function(e){if("1"===e)return"0";if("0"===e)return"1";throw new Error("non-binary given")},r.binaryToDecimal=s,r.minBinaryWithLength=function(e){return new Array(e).fill(0).map((function(){return"0"})).join("")},r.maxBinaryWithLength=function(e){return new Array(e).fill(0).map((function(){return"1"})).join("")},r.getNextStateSet=function(e){return a(s(e)+1,e.length)},r.firstKeyOfMap=function(e){return e.keys().next().value},r.shuffleArray=function(e){for(var t,r=e.length-1;r>0;r--){var i=Math.floor(Math.random()*(r+1));t=n([e[i],e[r]],2),e[r]=t[0],e[i]=t[1]}return e},r.lastOfArray=function(e){return e[e.length-1]},r.splitStringToChunks=function(e,t){for(var r=[],n=0,i=e.length;n=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function u(e,t,r){var n=s(e,r);return r-1>=t&&(n|=s(e,r-1)<<4),n}function c(e,t,r,i){for(var o=0,a=0,s=Math.min(e.length,r),u=t;u=49?c-49+10:c>=17?c-17+10:c,n(c>=0&&a0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this._strip()},o.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)i=u(e,t,n)<=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;this._strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,u=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(e){o.prototype.inspect=l}else o.prototype.inspect=l;function l(){return(this.red?""}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?d[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var c=h[e],f=p[e];r="";var l=this.clone();for(l.negative=0;!l.isZero();){var b=l.modrn(f).toString(e);r=(l=l.idivn(f)).isZero()?b+r:d[c-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},a&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(a,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function b(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,l=67108863&u,d=Math.min(c,t.length-1),h=Math.max(0,c-e.length+1);h<=d;h++){var p=c-h|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[h])+l)/67108864|0,l=67108863&a}r.words[c]=0|l,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r._strip()}o.prototype.toArrayLike=function(e,t,r){this._strip();var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var a=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](a,i),a},o.prototype._toArrayLikeLE=function(e,t){for(var r=0,n=0,i=0,o=0;i>8&255),r>16&255),6===o?(r>24&255),n=0,o=0):(n=a>>>24,o+=2)}if(r=0&&(e[r--]=a>>8&255),r>=0&&(e[r--]=a>>16&255),6===o?(r>=0&&(e[r--]=a>>24&255),n=0,o=0):(n=a>>>24,o+=2)}if(r>=0)for(e[r--]=n;r>=0;)e[r--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,h=0|a[1],p=8191&h,b=h>>>13,v=0|a[2],y=8191&v,m=v>>>13,g=0|a[3],_=8191&g,w=g>>>13,S=0|a[4],x=8191&S,O=S>>>13,j=0|a[5],E=8191&j,M=j>>>13,k=0|a[6],A=8191&k,P=k>>>13,R=0|a[7],C=8191&R,I=R>>>13,D=0|a[8],B=8191&D,T=D>>>13,L=0|a[9],N=8191&L,F=L>>>13,q=0|s[0],U=8191&q,z=q>>>13,$=0|s[1],W=8191&$,H=$>>>13,V=0|s[2],K=8191&V,G=V>>>13,Q=0|s[3],J=8191&Q,Y=Q>>>13,X=0|s[4],Z=8191&X,ee=X>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],le=8191&fe,de=fe>>>13,he=0|s[9],pe=8191&he,be=he>>>13;r.negative=e.negative^t.negative,r.length=19;var ve=(c+(n=Math.imul(l,U))|0)+((8191&(i=(i=Math.imul(l,z))+Math.imul(d,U)|0))<<13)|0;c=((o=Math.imul(d,z))+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,U),i=(i=Math.imul(p,z))+Math.imul(b,U)|0,o=Math.imul(b,z);var ye=(c+(n=n+Math.imul(l,W)|0)|0)+((8191&(i=(i=i+Math.imul(l,H)|0)+Math.imul(d,W)|0))<<13)|0;c=((o=o+Math.imul(d,H)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(y,U),i=(i=Math.imul(y,z))+Math.imul(m,U)|0,o=Math.imul(m,z),n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,H)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,H)|0;var me=(c+(n=n+Math.imul(l,K)|0)|0)+((8191&(i=(i=i+Math.imul(l,G)|0)+Math.imul(d,K)|0))<<13)|0;c=((o=o+Math.imul(d,G)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(_,U),i=(i=Math.imul(_,z))+Math.imul(w,U)|0,o=Math.imul(w,z),n=n+Math.imul(y,W)|0,i=(i=i+Math.imul(y,H)|0)+Math.imul(m,W)|0,o=o+Math.imul(m,H)|0,n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,G)|0;var ge=(c+(n=n+Math.imul(l,J)|0)|0)+((8191&(i=(i=i+Math.imul(l,Y)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,Y)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(x,U),i=(i=Math.imul(x,z))+Math.imul(O,U)|0,o=Math.imul(O,z),n=n+Math.imul(_,W)|0,i=(i=i+Math.imul(_,H)|0)+Math.imul(w,W)|0,o=o+Math.imul(w,H)|0,n=n+Math.imul(y,K)|0,i=(i=i+Math.imul(y,G)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,G)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,Y)|0;var _e=(c+(n=n+Math.imul(l,Z)|0)|0)+((8191&(i=(i=i+Math.imul(l,ee)|0)+Math.imul(d,Z)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(E,U),i=(i=Math.imul(E,z))+Math.imul(M,U)|0,o=Math.imul(M,z),n=n+Math.imul(x,W)|0,i=(i=i+Math.imul(x,H)|0)+Math.imul(O,W)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(_,K)|0,i=(i=i+Math.imul(_,G)|0)+Math.imul(w,K)|0,o=o+Math.imul(w,G)|0,n=n+Math.imul(y,J)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(m,J)|0,o=o+Math.imul(m,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,ee)|0;var we=(c+(n=n+Math.imul(l,re)|0)|0)+((8191&(i=(i=i+Math.imul(l,ne)|0)+Math.imul(d,re)|0))<<13)|0;c=((o=o+Math.imul(d,ne)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(A,U),i=(i=Math.imul(A,z))+Math.imul(P,U)|0,o=Math.imul(P,z),n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,H)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(x,K)|0,i=(i=i+Math.imul(x,G)|0)+Math.imul(O,K)|0,o=o+Math.imul(O,G)|0,n=n+Math.imul(_,J)|0,i=(i=i+Math.imul(_,Y)|0)+Math.imul(w,J)|0,o=o+Math.imul(w,Y)|0,n=n+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(m,Z)|0,o=o+Math.imul(m,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Se=(c+(n=n+Math.imul(l,oe)|0)|0)+((8191&(i=(i=i+Math.imul(l,ae)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,ae)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(C,U),i=(i=Math.imul(C,z))+Math.imul(I,U)|0,o=Math.imul(I,z),n=n+Math.imul(A,W)|0,i=(i=i+Math.imul(A,H)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,H)|0,n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,G)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,G)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,Y)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Y)|0,n=n+Math.imul(_,Z)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,n=n+Math.imul(y,re)|0,i=(i=i+Math.imul(y,ne)|0)+Math.imul(m,re)|0,o=o+Math.imul(m,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var xe=(c+(n=n+Math.imul(l,ue)|0)|0)+((8191&(i=(i=i+Math.imul(l,ce)|0)+Math.imul(d,ue)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(B,U),i=(i=Math.imul(B,z))+Math.imul(T,U)|0,o=Math.imul(T,z),n=n+Math.imul(C,W)|0,i=(i=i+Math.imul(C,H)|0)+Math.imul(I,W)|0,o=o+Math.imul(I,H)|0,n=n+Math.imul(A,K)|0,i=(i=i+Math.imul(A,G)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,G)|0,n=n+Math.imul(E,J)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(x,Z)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(_,re)|0,i=(i=i+Math.imul(_,ne)|0)+Math.imul(w,re)|0,o=o+Math.imul(w,ne)|0,n=n+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,ae)|0)+Math.imul(m,oe)|0,o=o+Math.imul(m,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var Oe=(c+(n=n+Math.imul(l,le)|0)|0)+((8191&(i=(i=i+Math.imul(l,de)|0)+Math.imul(d,le)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(N,U),i=(i=Math.imul(N,z))+Math.imul(F,U)|0,o=Math.imul(F,z),n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,H)|0)+Math.imul(T,W)|0,o=o+Math.imul(T,H)|0,n=n+Math.imul(C,K)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,G)|0,n=n+Math.imul(A,J)|0,i=(i=i+Math.imul(A,Y)|0)+Math.imul(P,J)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(x,re)|0,i=(i=i+Math.imul(x,ne)|0)+Math.imul(O,re)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(_,oe)|0,i=(i=i+Math.imul(_,ae)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,ae)|0,n=n+Math.imul(y,ue)|0,i=(i=i+Math.imul(y,ce)|0)+Math.imul(m,ue)|0,o=o+Math.imul(m,ce)|0,n=n+Math.imul(p,le)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(b,le)|0,o=o+Math.imul(b,de)|0;var je=(c+(n=n+Math.imul(l,pe)|0)|0)+((8191&(i=(i=i+Math.imul(l,be)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(N,W),i=(i=Math.imul(N,H))+Math.imul(F,W)|0,o=Math.imul(F,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,G)|0)+Math.imul(T,K)|0,o=o+Math.imul(T,G)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,Y)|0)+Math.imul(I,J)|0,o=o+Math.imul(I,Y)|0,n=n+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,ee)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,ae)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,ae)|0,n=n+Math.imul(_,ue)|0,i=(i=i+Math.imul(_,ce)|0)+Math.imul(w,ue)|0,o=o+Math.imul(w,ce)|0,n=n+Math.imul(y,le)|0,i=(i=i+Math.imul(y,de)|0)+Math.imul(m,le)|0,o=o+Math.imul(m,de)|0;var Ee=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,K),i=(i=Math.imul(N,G))+Math.imul(F,K)|0,o=Math.imul(F,G),n=n+Math.imul(B,J)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(T,J)|0,o=o+Math.imul(T,Y)|0,n=n+Math.imul(C,Z)|0,i=(i=i+Math.imul(C,ee)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,ee)|0,n=n+Math.imul(A,re)|0,i=(i=i+Math.imul(A,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,ce)|0,n=n+Math.imul(_,le)|0,i=(i=i+Math.imul(_,de)|0)+Math.imul(w,le)|0,o=o+Math.imul(w,de)|0;var Me=(c+(n=n+Math.imul(y,pe)|0)|0)+((8191&(i=(i=i+Math.imul(y,be)|0)+Math.imul(m,pe)|0))<<13)|0;c=((o=o+Math.imul(m,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(N,J),i=(i=Math.imul(N,Y))+Math.imul(F,J)|0,o=Math.imul(F,Y),n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(C,re)|0,i=(i=i+Math.imul(C,ne)|0)+Math.imul(I,re)|0,o=o+Math.imul(I,ne)|0,n=n+Math.imul(A,oe)|0,i=(i=i+Math.imul(A,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(x,le)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(O,le)|0,o=o+Math.imul(O,de)|0;var ke=(c+(n=n+Math.imul(_,pe)|0)|0)+((8191&(i=(i=i+Math.imul(_,be)|0)+Math.imul(w,pe)|0))<<13)|0;c=((o=o+Math.imul(w,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(N,Z),i=(i=Math.imul(N,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(T,re)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(C,oe)|0,i=(i=i+Math.imul(C,ae)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,ae)|0,n=n+Math.imul(A,ue)|0,i=(i=i+Math.imul(A,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(E,le)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,le)|0,o=o+Math.imul(M,de)|0;var Ae=(c+(n=n+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,be)|0)+Math.imul(O,pe)|0))<<13)|0;c=((o=o+Math.imul(O,be)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(N,re),i=(i=Math.imul(N,ne))+Math.imul(F,re)|0,o=Math.imul(F,ne),n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,ae)|0,n=n+Math.imul(C,ue)|0,i=(i=i+Math.imul(C,ce)|0)+Math.imul(I,ue)|0,o=o+Math.imul(I,ce)|0,n=n+Math.imul(A,le)|0,i=(i=i+Math.imul(A,de)|0)+Math.imul(P,le)|0,o=o+Math.imul(P,de)|0;var Pe=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(N,oe),i=(i=Math.imul(N,ae))+Math.imul(F,oe)|0,o=Math.imul(F,ae),n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(T,ue)|0,o=o+Math.imul(T,ce)|0,n=n+Math.imul(C,le)|0,i=(i=i+Math.imul(C,de)|0)+Math.imul(I,le)|0,o=o+Math.imul(I,de)|0;var Re=(c+(n=n+Math.imul(A,pe)|0)|0)+((8191&(i=(i=i+Math.imul(A,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(N,ue),i=(i=Math.imul(N,ce))+Math.imul(F,ue)|0,o=Math.imul(F,ce),n=n+Math.imul(B,le)|0,i=(i=i+Math.imul(B,de)|0)+Math.imul(T,le)|0,o=o+Math.imul(T,de)|0;var Ce=(c+(n=n+Math.imul(C,pe)|0)|0)+((8191&(i=(i=i+Math.imul(C,be)|0)+Math.imul(I,pe)|0))<<13)|0;c=((o=o+Math.imul(I,be)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(N,le),i=(i=Math.imul(N,de))+Math.imul(F,le)|0,o=Math.imul(F,de);var Ie=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(T,pe)|0))<<13)|0;c=((o=o+Math.imul(T,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863;var De=(c+(n=Math.imul(N,pe))|0)+((8191&(i=(i=Math.imul(N,be))+Math.imul(F,pe)|0))<<13)|0;return c=((o=Math.imul(F,be))+(i>>>13)|0)+(De>>>26)|0,De&=67108863,u[0]=ve,u[1]=ye,u[2]=me,u[3]=ge,u[4]=_e,u[5]=we,u[6]=Se,u[7]=xe,u[8]=Oe,u[9]=je,u[10]=Ee,u[11]=Me,u[12]=ke,u[13]=Ae,u[14]=Pe,u[15]=Re,u[16]=Ce,u[17]=Ie,u[18]=De,0!==c&&(u[19]=c,r.length++),r};function y(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r._strip()}function m(e,t,r){return y(e,t,r)}function g(e,t){this.x=e,this.y=t}Math.imul||(v=b),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?v(this,e,t):r<63?b(this,e,t):r<1024?y(this,e,t):m(this,e,t)},g.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},g.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,r+=o/67108864|0,r+=a>>>26,this.words[i]=67108863&a}return 0!==r&&(this.words[i]=r,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i&1}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var l=0|this.words[c];this.words[c]=f<<26-o|l>>>o,f=l&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this._strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;l--){var d=67108864*(0|n.words[i.length+l])+(0|n.words[i.length+l-1]);for(d=Math.min(d/a|0,67108863),n._ishlnsubmul(i,d,l);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(i,1,l),n.isZero()||(n.negative^=1);s&&(s.words[l]=d)}return s&&s._strip(),n._strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(r*i+(0|this.words[o]))%e;return t?-i:i},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var o=(0|this.words[i])+67108864*r;this.words[i]=o/e|0,r=o%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),l=t.clone();!t.isZero();){for(var d=0,h=1;0==(t.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(l)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(l)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var l=0,d=1;0==(r.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(r.iushrn(l);l-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new E(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var _={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function S(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function x(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function O(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function j(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function M(e){E.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},i(S,w),S.prototype.split=function(e,t){for(var r=4194303,n=Math.min(e.length,9),i=0;i>>22,o=a}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},S.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(_[e])return _[e];var t;if("k256"===e)t=new S;else if("p224"===e)t=new x;else if("p192"===e)t=new O;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new j}return _[e]=t,t},E.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},E.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(f(e,e.umod(this.m)._forceRed(this)),e)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var l=this.pow(f,i),d=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=a;0!==h.cmp(s);){for(var b=h,v=0;0!==b.cmp(s);v++)b=b.redSqr();n(v=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var l=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==l||0!==a?(a<<=1,a|=l,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new M(e)},i(M,E),M.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},M.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},M.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},M.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},M.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:124}],111:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.clearNodeFolder=function(e){e=(0,a.fillOptionsWithDefaults)(e);var t=(0,o.chooseMethod)(e);return"node"===t.type?t.clearNodeFolder().then((function(){return!0})):Promise.resolve(!1)},r.enforceOptions=function(e){n=e},r.BroadcastChannel=void 0;var n,i=e("./util.js"),o=e("./method-chooser.js"),a=e("./options.js"),s=function(e,t){var r,s;this.name=e,n&&(t=n),this.options=(0,a.fillOptionsWithDefaults)(t),this.method=(0,o.chooseMethod)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,s=(r=this).method.create(r.name,r.options),(0,i.isPromise)(s)?(r._prepP=s,s.then((function(e){r._state=e}))):r._state=s};function u(e,t,r){var n={time:e.method.microSeconds(),type:t,data:r};return(e._prepP?e._prepP:Promise.resolve()).then((function(){var t=e.method.postMessage(e._state,n);return e._uMP.add(t),t.catch().then((function(){return e._uMP.delete(t)})),t}))}function c(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function f(e,t,r){e._addEL[t].push(r),function(e){if(!e._iL&&c(e)){var t=function(t){e._addEL[t.type].forEach((function(e){t.time>=e.time&&e.fn(t.data)}))},r=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,r)})):(e._iL=!0,e.method.onMessage(e._state,t,r))}}(e)}function l(e,t,r){e._addEL[t]=e._addEL[t].filter((function(e){return e!==r})),function(e){if(e._iL&&!c(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}r.BroadcastChannel=s,s._pubkey=!0,s.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return u(this,"message",e)},postInternal:function(e){return u(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,f(this,"message",t)):this._onML=null},addEventListener:function(e,t){f(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){l(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type}}},{"./method-chooser.js":115,"./options.js":121,"./util.js":122}],112:[function(e,t,r){"use strict";var n=e("./index.js");t.exports={BroadcastChannel:n.BroadcastChannel,createLeaderElection:n.createLeaderElection,clearNodeFolder:n.clearNodeFolder,enforceOptions:n.enforceOptions,beLeader:n.beLeader}},{"./index.js":113}],113:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"BroadcastChannel",{enumerable:!0,get:function(){return n.BroadcastChannel}}),Object.defineProperty(r,"clearNodeFolder",{enumerable:!0,get:function(){return n.clearNodeFolder}}),Object.defineProperty(r,"enforceOptions",{enumerable:!0,get:function(){return n.enforceOptions}}),Object.defineProperty(r,"createLeaderElection",{enumerable:!0,get:function(){return i.createLeaderElection}}),Object.defineProperty(r,"beLeader",{enumerable:!0,get:function(){return i.beLeader}});var n=e("./broadcast-channel"),i=e("./leader-election")},{"./broadcast-channel":111,"./leader-election":114}],114:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.beLeader=u,r.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e||(e={});(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var r=new a(e,t);return e._befC.push((function(){return r.die()})),e._leaderElector=r,r};var i=e("./util.js"),o=n(e("unload")),a=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[],this._dpL=function(){},this._dpLC=!1};function s(e,t){var r={context:"leader",action:t,token:e.token};return e._channel.postInternal(r)}function u(e){e.isLeader=!0;var t=o.default.add((function(){return e.die()}));e._unl.push(t);var r=function(t){"leader"===t.context&&"apply"===t.action&&s(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),s(e,"tell"))};return e._channel.addEventListener("internal",r),e._lstns.push(r),s(e,"tell")}a.prototype={applyOnce:function(){var e=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);this._isApl=!0;var t=!1,r=[],n=function(n){"leader"===n.context&&n.token!=e.token&&(r.push(n),"apply"===n.action&&n.token>e.token&&(t=!0),"tell"===n.action&&(t=!0))};return this._channel.addEventListener("internal",n),s(this,"apply").then((function(){return(0,i.sleep)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):s(e,"apply")})).then((function(){return(0,i.sleep)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):s(e)})).then((function(){return u(e)})).then((function(){return!0})).catch((function(){return!1})).then((function(t){return e._channel.removeEventListener("internal",n),e._isApl=!1,!t&&e._reApply?(e._reApply=!1,e.applyOnce()):t}))},awaitLeadership:function(){var e;return this._aLP||(this._aLP=(e=this).isLeader?Promise.resolve():new Promise((function(t){var r=!1;function n(){r||(r=!0,clearInterval(i),e._channel.removeEventListener("internal",o),t(!0))}e.applyOnce().then((function(){e.isLeader&&n()}));var i=setInterval((function(){e.applyOnce().then((function(){e.isLeader&&n()}))}),e._options.fallbackInterval);e._invs.push(i);var o=function(t){"leader"===t.context&&"death"===t.action&&e.applyOnce().then((function(){e.isLeader&&n()}))};e._channel.addEventListener("internal",o),e._lstns.push(o)}))),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach((function(t){return e._channel.removeEventListener("internal",t)})),this._invs.forEach((function(e){return clearInterval(e)})),this._unl.forEach((function(e){e.remove()})),s(this,"death")}}},{"./util.js":122,"@babel/runtime/helpers/interopRequireDefault":65,unload:938}],115:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.chooseMethod=function(e){var t=[].concat(e.methods,c).filter(Boolean);if(e.type){if("simulate"===e.type)return s.default;var r=t.find((function(t){return t.type===e.type}));if(r)return r;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||u.isNode||(t=t.filter((function(e){return"idb"!==e.type})));var n=t.find((function(e){return e.canBeUsed()}));if(n)return n;throw new Error("No useable methode found:"+JSON.stringify(c.map((function(e){return e.type}))))};var i=n(e("./methods/native.js")),o=n(e("./methods/indexed-db.js")),a=n(e("./methods/localstorage.js")),s=n(e("./methods/simulate.js")),u=e("./util"),c=[i.default,o.default,a.default];if(u.isNode){var f=e("../../src/methods/node.js");"function"==typeof f.canBeUsed&&c.push(f)}},{"./methods/indexed-db.js":116,"./methods/localstorage.js":117,"./methods/native.js":118,"./methods/simulate.js":119,"./util":122,"@babel/runtime/helpers/interopRequireDefault":65}],116:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.getIdb=c,r.createDatabase=f,r.writeMessage=l,r.getAllMessages=function(e){var t=e.transaction(u).objectStore(u),r=[];return new Promise((function(e){t.openCursor().onsuccess=function(t){var n=t.target.result;n?(r.push(n.value),n.continue()):e(r)}}))},r.getMessagesHigherThan=d,r.removeMessageById=h,r.getOldMessages=p,r.cleanOldMessages=b,r.create=v,r.close=g,r.postMessage=_,r.onMessage=w,r.canBeUsed=S,r.averageResponseTime=x,r.default=r.type=r.microSeconds=void 0;var i=e("../util.js"),o=n(e("../oblivious-set")),a=e("../options"),s=i.microSeconds;r.microSeconds=s;var u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function f(e){var t="pubkey.broadcast-channel-0-"+e,r=c().open(t,1);return r.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise((function(e,t){r.onerror=function(e){return t(e)},r.onsuccess=function(){e(r.result)}}))}function l(e,t,r){var n={uuid:t,time:(new Date).getTime(),data:r},i=e.transaction([u],"readwrite");return new Promise((function(e,t){i.oncomplete=function(){return e()},i.onerror=function(e){return t(e)},i.objectStore(u).add(n)}))}function d(e,t){var r=e.transaction(u).objectStore(u),n=[];return new Promise((function(e){(function(){try{var e=IDBKeyRange.bound(t+1,1/0);return r.openCursor(e)}catch(e){return r.openCursor()}}()).onsuccess=function(r){var i=r.target.result;i?i.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return!(e.uuid===t.uuid||t.eMIs.has(e.id)||e.data.time0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0);t.idb||(t.idb={});t.idb.ttl||(t.idb.ttl=45e3);t.idb.fallbackInterval||(t.idb.fallbackInterval=150);e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose);t.localstorage||(t.localstorage={});t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4);e.methods&&(t.methods=e.methods);t.node||(t.node={});t.node.ttl||(t.node.ttl=12e4);void 0===t.node.useFastPath&&(t.node.useFastPath=!0);return t}},{}],122:[function(e,t,r){(function(e){(function(){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.isPromise=function(e){return!(!e||"function"!=typeof e.then)},r.sleep=function(e){e||(e=0);return new Promise((function(t){return setTimeout(t,e)}))},r.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},r.randomToken=function(){return Math.random().toString(36).substring(2)},r.microSeconds=function(){var e=(new Date).getTime();return e===t?(n++,1e3*e+n):(t=e,n=0,1e3*e)},r.isNode=void 0;var t=0,n=0;var i="[object process]"===Object.prototype.toString.call(void 0!==e?e:0);r.isNode=i}).call(this)}).call(this,e("_process"))},{_process:667}],123:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r>>24]^f[p>>>16&255]^l[b>>>8&255]^d[255&v]^t[y++],a=c[p>>>24]^f[b>>>16&255]^l[v>>>8&255]^d[255&h]^t[y++],s=c[b>>>24]^f[v>>>16&255]^l[h>>>8&255]^d[255&p]^t[y++],u=c[v>>>24]^f[h>>>16&255]^l[p>>>8&255]^d[255&b]^t[y++],h=o,p=a,b=s,v=u;return o=(n[h>>>24]<<24|n[p>>>16&255]<<16|n[b>>>8&255]<<8|n[255&v])^t[y++],a=(n[p>>>24]<<24|n[b>>>16&255]<<16|n[v>>>8&255]<<8|n[255&h])^t[y++],s=(n[b>>>24]<<24|n[v>>>16&255]<<16|n[h>>>8&255]<<8|n[255&p])^t[y++],u=(n[v>>>24]<<24|n[h>>>16&255]<<16|n[p>>>8&255]<<8|n[255&b])^t[y++],[o>>>=0,a>>>=0,s>>>=0,u>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,u=0;u<256;++u){var c=s^s<<1^s<<2^s<<3^s<<4;c=c>>>8^255&c^99,r[a]=c,n[c]=a;var f=e[a],l=e[f],d=e[l],h=257*e[c]^16843008*c;i[0][a]=h<<24|h>>>8,i[1][a]=h<<16|h>>>16,i[2][a]=h<<8|h>>>24,i[3][a]=h,h=16843009*d^65537*l^257*f^16843008*a,o[0][c]=h<<24|h>>>8,o[1][c]=h<<16|h>>>16,o[2][c]=h<<8|h>>>24,o[3][c]=h,0===a?a=s=1:(a=f^e[e[e[d^f]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a]),i[o]=i[o-t]^a}for(var c=[],f=0;f>>24]]^u.INV_SUB_MIX[1][u.SBOX[d>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[d>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&d]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=c},{"safe-buffer":909}],126:[function(e,t,r){var n=e("./aes"),i=e("safe-buffer").Buffer,o=e("cipher-base"),a=e("inherits"),s=e("./ghash"),u=e("buffer-xor"),c=e("./incr32");function f(e,t,r,a){o.call(this);var u=i.alloc(4,0);this._cipher=new n.AES(t);var f=this._cipher.encryptBlock(u);this._ghash=new s(f),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var u=8*o,f=i.alloc(8);f.writeUIntBE(u,0,8),n.update(f),e._finID=n.state;var l=i.from(e._finID);return c(l),l}(this,r,f),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(f,o),f.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},f.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=u(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i16)throw new Error("unable to decrypt data");var r=-1;for(;++r16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},l.prototype.flush=function(){if(this.cache.length)return this.cache},r.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=c(t,!1,r.key,r.iv);return d(e,n.key,n.iv)},r.createDecipheriv=d},{"./aes":125,"./authCipher":126,"./modes":138,"./streamCipher":141,"cipher-base":172,evp_bytestokey:540,inherits:587,"safe-buffer":909}],129:[function(e,t,r){var n=e("./modes"),i=e("./authCipher"),o=e("safe-buffer").Buffer,a=e("./streamCipher"),s=e("cipher-base"),u=e("./aes"),c=e("evp_bytestokey");function f(e,t,r){s.call(this),this._cache=new d,this._cipher=new u.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}e("inherits")(f,s),f.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var l=o.alloc(16,16);function d(){this.cache=o.allocUnsafe(0)}function h(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new f(s.module,t,r)}f.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(l))throw this._cipher.scrub(),new Error("data not multiple of block length")},f.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},d.prototype.add=function(e){this.cache=o.concat([this.cache,e])},d.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},d.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":909}],131:[function(e,t,r){t.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},{}],132:[function(e,t,r){var n=e("buffer-xor");r.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},r.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},{"buffer-xor":168}],133:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("buffer-xor");function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}r.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},{"buffer-xor":168,"safe-buffer":909}],134:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}r.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function a(e,t){var i=function(e){var t=o(e);return{blinder:t.toRed(n.mont(e.modulus)).redPow(new n(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(t),a=t.modulus.byteLength(),s=new n(e).mul(i.blinder).umod(t.modulus),u=s.toRed(n.mont(t.prime1)),c=s.toRed(n.mont(t.prime2)),f=t.coefficient,l=t.prime1,d=t.prime2,h=u.redPow(t.exponent1).fromRed(),p=c.redPow(t.exponent2).fromRed(),b=h.isub(p).imul(f).umod(l).imul(d);return p.iadd(b).imul(i.unblinder).umod(t.modulus).toArrayLike(r,"be",a)}a.getr=o,t.exports=a}).call(this)}).call(this,e("buffer").Buffer)},{"bn.js":110,buffer:169,randombytes:676}],146:[function(e,t,r){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":147}],147:[function(e,t,r){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],148:[function(e,t,r){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],149:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("create-hash"),o=e("readable-stream"),a=e("inherits"),s=e("./sign"),u=e("./verify"),c=e("./algorithms.json");function f(e){o.Writable.call(this);var t=c[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function l(e){o.Writable.call(this);var t=c[e];if(!t)throw new Error("Unknown message digest");this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function d(e){return new f(e)}function h(e){return new l(e)}Object.keys(c).forEach((function(e){c[e].id=n.from(c[e].id,"hex"),c[e.toLowerCase()]=c[e]})),a(f,o.Writable),f.prototype._write=function(e,t,r){this._hash.update(e),r()},f.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},f.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=s(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},a(l,o.Writable),l.prototype._write=function(e,t,r){this._hash.update(e),r()},l.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},l.prototype.verify=function(e,t,r){"string"==typeof t&&(t=n.from(t,r)),this.end();var i=this._hash.digest();return u(t,i,e,this._signType,this._tag)},t.exports={Sign:d,Verify:h,createSign:d,createVerify:h}},{"./algorithms.json":147,"./sign":150,"./verify":151,"create-hash":480,inherits:587,"readable-stream":166,"safe-buffer":167}],150:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("create-hmac"),o=e("browserify-rsa"),a=e("elliptic").ec,s=e("bn.js"),u=e("parse-asn1"),c=e("./curves.json");function f(e,t,r,o){if((e=n.from(e.toArray())).length0&&r.ishrn(n),r}function d(e,t,r){var o,a;do{for(o=n.alloc(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,r,c,f){var l=a(r);if("ec"===l.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=s[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var i=new o(n),a=r.data.subjectPrivateKey.data;return i.verify(t,e,a)}(e,t,l)}if("dsa"===l.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=r.data.p,o=r.data.q,s=r.data.g,c=r.data.pub_key,f=a.signature.decode(e,"der"),l=f.s,d=f.r;u(l,o),u(d,o);var h=i.mont(n),p=l.invm(o);return 0===s.toRed(h).redPow(new i(t).mul(p).mod(o)).fromRed().mul(c.toRed(h).redPow(d.mul(p).mod(o)).fromRed()).mod(n).mod(o).cmp(d)}(e,t,l)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=n.concat([f,t]);for(var d=l.modulus.byteLength(),h=[1],p=0;t.length+h.length+22?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}i("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),i("ERR_INVALID_ARG_TYPE",(function(e,t,r){var n,i,a,s;if("string"==typeof t&&(i="not ",t.substr(!a||a<0?0:+a,i.length)===i)?(n="must not be",t=t.replace(/^not /,"")):n="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))s="The ".concat(e," ").concat(n," ").concat(o(t,"type"));else{var u=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(u," ").concat(n," ").concat(o(t,"type"))}return s+=". Received type ".concat(typeof r)}),TypeError),i("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),i("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),i("ERR_STREAM_PREMATURE_CLOSE","Premature close"),i("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),i("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),i("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),i("ERR_STREAM_WRITE_AFTER_END","write after end"),i("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),i("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=n},{}],153:[function(e,t,r){(function(r){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=c;var i=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(c,i);for(var a=n(o.prototype),s=0;s0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===s.prototype||(t=function(e){return s.from(e)}(t)),n)a.endEmitted?S(e,new w):M(e,a,t,!0);else if(a.ended)S(e,new g);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?M(e,a,t,!1):C(e,a)):M(e,a,t,!1)}else n||(a.reading=!1,C(e,a));return!a.ended&&(a.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function P(e){var t=e._readableState;c("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(c("emitReadable",t.flowing),t.emittedReadable=!0,r.nextTick(R,e))}function R(e){var t=e._readableState;c("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,L(e)}function C(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(I,e,t))}function I(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function B(e){c("readable nexttick read 0"),e.read(0)}function T(e,t){c("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),L(e),t.flowing&&!t.reading&&e.read(0)}function L(e){var t=e._readableState;for(c("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function F(e){var t=e._readableState;c("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,r.nextTick(q,t,e))}function q(e,t){if(c("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function U(e,t){for(var r=0,n=e.length;r=t.highWaterMark:t.length>0)||t.ended))return c("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?F(this):P(this),null;if(0===(e=A(e,t))&&t.ended)return 0===t.length&&F(this),null;var n,i=t.needReadable;return c("need readable",i),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&F(this)),null!==n&&this.emit("data",n),n},j.prototype._read=function(e){S(this,new _("_read()"))},j.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,c("pipe count=%d opts=%j",i.pipesCount,t);var a=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?u:v;function s(t,r){c("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,c("cleanup"),e.removeListener("close",p),e.removeListener("finish",b),e.removeListener("drain",f),e.removeListener("error",h),e.removeListener("unpipe",s),n.removeListener("end",u),n.removeListener("end",v),n.removeListener("data",d),l=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function u(){c("onend"),e.end()}i.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",s);var f=function(e){return function(){var t=e._readableState;c("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,L(e))}}(n);e.on("drain",f);var l=!1;function d(t){c("ondata");var r=e.write(t);c("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==U(i.pipes,e))&&!l&&(c("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function h(t){c("onerror",t),v(),e.removeListener("error",h),0===o(e,"error")&&S(e,t)}function p(){e.removeListener("finish",b),v()}function b(){c("onfinish"),e.removeListener("close",p),v()}function v(){c("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",h),e.once("close",p),e.once("finish",b),e.emit("pipe",n),i.flowing||(c("pipe resume"),n.resume()),e},j.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,c("on readable",i.length,i.reading),i.length?P(this):i.reading||r.nextTick(B,this))),n},j.prototype.addListener=j.prototype.on,j.prototype.removeListener=function(e,t){var n=a.prototype.removeListener.call(this,e,t);return"readable"===e&&r.nextTick(D,this),n},j.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||r.nextTick(D,this),t},j.prototype.resume=function(){var e=this._readableState;return e.flowing||(c("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(T,e,t))}(this,e)),e.paused=!1,this},j.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},j.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var i in e.on("end",(function(){if(c("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(c("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(t.push(i)||(n=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(j.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(j.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),j.prototype._write=function(e,t,r){r(new b("_write()"))},j.prototype._writev=null,j.prototype.end=function(e,t,n){var i=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,t,n){t.ending=!0,R(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,i,n),this},Object.defineProperty(j.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(j.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),j.prototype.destroy=l.destroy,j.prototype._undestroy=l.undestroy,j.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":152,"./_stream_duplex":153,"./internal/streams/destroy":160,"./internal/streams/state":164,"./internal/streams/stream":165,_process:667,buffer:169,inherits:587,"util-deprecate":939}],158:[function(e,t,r){(function(r){(function(){"use strict";var n;function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var o=e("./end-of-stream"),a=Symbol("lastResolve"),s=Symbol("lastReject"),u=Symbol("error"),c=Symbol("ended"),f=Symbol("lastPromise"),l=Symbol("handlePromise"),d=Symbol("stream");function h(e,t){return{value:e,done:t}}function p(e){var t=e[a];if(null!==t){var r=e[d].read();null!==r&&(e[f]=null,e[a]=null,e[s]=null,t(h(r,!1)))}}function b(e){r.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),y=Object.setPrototypeOf((i(n={get stream(){return this[d]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[c])return Promise.resolve(h(void 0,!0));if(this[d].destroyed)return new Promise((function(t,n){r.nextTick((function(){e[u]?n(e[u]):t(h(void 0,!0))}))}));var n,i=this[f];if(i)n=new Promise(function(e,t){return function(r,n){e.then((function(){t[c]?r(h(void 0,!0)):t[l](r,n)}),n)}}(i,this));else{var o=this[d].read();if(null!==o)return Promise.resolve(h(o,!1));n=new Promise(this[l])}return this[f]=n,n}},Symbol.asyncIterator,(function(){return this})),i(n,"return",(function(){var e=this;return new Promise((function(t,r){e[d].destroy(null,(function(e){e?r(e):t(h(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,r=Object.create(y,(i(t={},d,{value:e,writable:!0}),i(t,a,{value:null,writable:!0}),i(t,s,{value:null,writable:!0}),i(t,u,{value:null,writable:!0}),i(t,c,{value:e._readableState.endEmitted,writable:!0}),i(t,l,{value:function(e,t){var n=r[d].read();n?(r[f]=null,r[a]=null,r[s]=null,e(h(n,!1))):(r[a]=e,r[s]=t)},writable:!0}),t));return r[f]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=r[s];return null!==t&&(r[f]=null,r[a]=null,r[s]=null,t(e)),void(r[u]=e)}var n=r[a];null!==n&&(r[f]=null,r[a]=null,r[s]=null,n(h(void 0,!0))),r[c]=!0})),e.on("readable",b.bind(null,r)),r}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":161,_process:667}],159:[function(e,t,r){"use strict";function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){for(var r=0;r0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return a.alloc(0);for(var t,r,n,i=a.allocUnsafe(e>>>0),o=this.head,s=0;o;)t=o.data,r=i,n=s,a.prototype.copy.call(t,r,n),s+=o.data.length,o=o.next;return i}},{key:"consume",value:function(e,t){var r;return ei.length?i.length:e;if(o===i.length?n+=i:n+=i.slice(0,e),0==(e-=o)){o===i.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=a.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var i=r.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0==(e-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,t}},{key:u,value:function(e,t){return s(this,function(e){for(var t=1;t0,(function(e){n||(n=e),e&&a.forEach(c),o||(a.forEach(c),i(n))}))}));return t.reduce(f)}},{"../../../errors":152,"./end-of-stream":161}],164:[function(e,t,r){"use strict";var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;t.exports={getHighWaterMark:function(e,t,r,i){var o=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,i,r);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new n(i?r:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}}},{"../../../errors":152}],165:[function(e,t,r){t.exports=e("events").EventEmitter},{events:539}],166:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js"),r.finished=e("./lib/internal/streams/end-of-stream.js"),r.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":153,"./lib/_stream_passthrough.js":154,"./lib/_stream_readable.js":155,"./lib/_stream_transform.js":156,"./lib/_stream_writable.js":157,"./lib/internal/streams/end-of-stream.js":161,"./lib/internal/streams/pipeline.js":163}],167:[function(e,t,r){ +!function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=r[a]={exports:{}};t[a][0].call(f.exports,(function(e){return i(t[a][1][e]||e)}),f,f.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;athis.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return e0;){t--;var r=this.buffer[t];if(r.documentData&&r.documentData._rev===e)return!0}return!1},t.destroy=function(){this.subs.forEach((function(e){return e.unsubscribe()}))},e}();r.ChangeEventBuffer=i},{"rxjs/operators":908}],3:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={addRxPlugin:!0,createRxDatabase:!0,removeRxDatabase:!0,isRxDatabase:!0,dbCount:!0,_collectionNamePrimary:!0,isRxCollection:!0,RxCollectionBase:!0,createRxCollection:!0,_handleFromStorageInstance:!0,_handleToStorageInstance:!0,fillObjectDataBeforeInsert:!0,isRxDocument:!0,getDocumentOrmPrototype:!0,getDocumentPrototype:!0,isRxQuery:!0,isRxSchema:!0,createRxSchema:!0,RxSchema:!0,getIndexes:!0,normalize:!0,getFinalFields:!0,getPreviousVersions:!0,getPseudoSchemaForVersion:!0,getSchemaByObjectPath:!0,findLocalDocument:!0,getSingleDocument:!0,getNewestSequence:!0,getAllDocuments:!0,writeSingleLocal:!0,writeSingle:!0,countAllUndeleted:!0,getBatch:!0,_clearHook:!0,createCrypter:!0};Object.defineProperty(r,"addRxPlugin",{enumerable:!0,get:function(){return i.addRxPlugin}}),Object.defineProperty(r,"createRxDatabase",{enumerable:!0,get:function(){return o.createRxDatabase}}),Object.defineProperty(r,"removeRxDatabase",{enumerable:!0,get:function(){return o.removeRxDatabase}}),Object.defineProperty(r,"isRxDatabase",{enumerable:!0,get:function(){return o.isRxDatabase}}),Object.defineProperty(r,"dbCount",{enumerable:!0,get:function(){return o.dbCount}}),Object.defineProperty(r,"_collectionNamePrimary",{enumerable:!0,get:function(){return o._collectionNamePrimary}}),Object.defineProperty(r,"isRxCollection",{enumerable:!0,get:function(){return a.isRxCollection}}),Object.defineProperty(r,"RxCollectionBase",{enumerable:!0,get:function(){return a.RxCollectionBase}}),Object.defineProperty(r,"createRxCollection",{enumerable:!0,get:function(){return a.createRxCollection}}),Object.defineProperty(r,"_handleFromStorageInstance",{enumerable:!0,get:function(){return s._handleFromStorageInstance}}),Object.defineProperty(r,"_handleToStorageInstance",{enumerable:!0,get:function(){return s._handleToStorageInstance}}),Object.defineProperty(r,"fillObjectDataBeforeInsert",{enumerable:!0,get:function(){return s.fillObjectDataBeforeInsert}}),Object.defineProperty(r,"isRxDocument",{enumerable:!0,get:function(){return u.isRxDocument}}),Object.defineProperty(r,"getDocumentOrmPrototype",{enumerable:!0,get:function(){return c.getDocumentOrmPrototype}}),Object.defineProperty(r,"getDocumentPrototype",{enumerable:!0,get:function(){return c.getDocumentPrototype}}),Object.defineProperty(r,"isRxQuery",{enumerable:!0,get:function(){return f.isInstanceOf}}),Object.defineProperty(r,"isRxSchema",{enumerable:!0,get:function(){return l.isInstanceOf}}),Object.defineProperty(r,"createRxSchema",{enumerable:!0,get:function(){return l.createRxSchema}}),Object.defineProperty(r,"RxSchema",{enumerable:!0,get:function(){return l.RxSchema}}),Object.defineProperty(r,"getIndexes",{enumerable:!0,get:function(){return l.getIndexes}}),Object.defineProperty(r,"normalize",{enumerable:!0,get:function(){return l.normalize}}),Object.defineProperty(r,"getFinalFields",{enumerable:!0,get:function(){return l.getFinalFields}}),Object.defineProperty(r,"getPreviousVersions",{enumerable:!0,get:function(){return l.getPreviousVersions}}),Object.defineProperty(r,"getPseudoSchemaForVersion",{enumerable:!0,get:function(){return d.getPseudoSchemaForVersion}}),Object.defineProperty(r,"getSchemaByObjectPath",{enumerable:!0,get:function(){return d.getSchemaByObjectPath}}),Object.defineProperty(r,"findLocalDocument",{enumerable:!0,get:function(){return h.findLocalDocument}}),Object.defineProperty(r,"getSingleDocument",{enumerable:!0,get:function(){return h.getSingleDocument}}),Object.defineProperty(r,"getNewestSequence",{enumerable:!0,get:function(){return h.getNewestSequence}}),Object.defineProperty(r,"getAllDocuments",{enumerable:!0,get:function(){return h.getAllDocuments}}),Object.defineProperty(r,"writeSingleLocal",{enumerable:!0,get:function(){return h.writeSingleLocal}}),Object.defineProperty(r,"writeSingle",{enumerable:!0,get:function(){return h.writeSingle}}),Object.defineProperty(r,"countAllUndeleted",{enumerable:!0,get:function(){return h.countAllUndeleted}}),Object.defineProperty(r,"getBatch",{enumerable:!0,get:function(){return h.getBatch}}),Object.defineProperty(r,"_clearHook",{enumerable:!0,get:function(){return p._clearHook}}),Object.defineProperty(r,"createCrypter",{enumerable:!0,get:function(){return b.createCrypter}}),e("./types/modules/crypto-js.d"),e("./types/modules/graphql-client.d"),e("./types/modules/mocha.parallel.d"),e("./types/modules/modifiyjs.d"),e("./types/modules/random-token.d");var i=e("./plugin"),o=e("./rx-database"),a=e("./rx-collection"),s=e("./rx-collection-helper"),u=e("./rx-document"),c=e("./rx-document-prototype-merge"),f=e("./rx-query"),l=e("./rx-schema"),d=e("./rx-schema-helper"),h=e("./rx-storage-helper"),p=e("./hooks"),b=e("./crypter"),v=e("./query-cache");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===v[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./util");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===m[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return m[e]}}))}))},{"./crypter":4,"./hooks":7,"./plugin":10,"./query-cache":41,"./rx-collection":44,"./rx-collection-helper":43,"./rx-database":45,"./rx-document":47,"./rx-document-prototype-merge":46,"./rx-query":49,"./rx-schema":51,"./rx-schema-helper":50,"./rx-storage-helper":52,"./types/modules/crypto-js.d":53,"./types/modules/graphql-client.d":54,"./types/modules/mocha.parallel.d":55,"./types/modules/modifiyjs.d":56,"./types/modules/random-token.d":57,"./util":58}],4:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.createCrypter=function(e,t){return new a(e,t)},r.Crypter=void 0;var i=n(e("object-path")),o=e("./util"),a=function(){function e(e,t){this.password=e,this.schema=t}var t=e.prototype;return t._encryptString=function(e){throw(0,o.pluginMissing)("encryption")},t._decryptString=function(e){throw(0,o.pluginMissing)("encryption")},t.encrypt=function(e){var t=this;return this.password?(e=(0,o.clone)(e),this.schema.encryptedPaths.forEach((function(r){var n=i.default.get(e,r);if(void 0!==n){var o=JSON.stringify(n),a=t._encryptString(o);i.default.set(e,r,a)}})),e):e},t.decrypt=function(e){var t=this;return this.password?(e=(0,o.clone)(e),this.schema.encryptedPaths.forEach((function(r){var n=i.default.get(e,r);if(void 0!==n){var o=t._decryptString(n),a=JSON.parse(o);i.default.set(e,r,a)}})),e):e},e}();r.Crypter=a},{"./util":58,"@babel/runtime/helpers/interopRequireDefault":67,"object-path":629}],5:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createDocCache=function(){return new n},r.DocCache=void 0;var n=function(){function e(){this._map=new Map,this._map=new Map}var t=e.prototype;return t.get=function(e){return this._map.get(e)},t.set=function(e,t){return this._map.set(e,t)},t.delete=function(e){return this._map.delete(e)},e}();r.DocCache=n},{}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getSortFieldsOfQuery=a,r.getQueryParams=u,r.calculateNewResults=function(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=u(e),i=e._resultsData.slice(),a=e._resultsDataMap,s=!1;return t.find((function(e){var t=(0,o.rxChangeEventToEventReduceChangeEvent)(e),u=(0,n.calculateActionName)({queryParams:r,changeEvent:t,previousResults:i,keyDocumentMap:a});return"runFullQueryAgain"===u||("doNothing"!==u?(s=!0,(0,n.runAction)(u,r,t,i,a),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:i}},r.RXQUERY_QUERY_PARAMS_CACHE=void 0;var n=e("event-reduce-js"),i=e("./hooks"),o=e("./rx-change-event");function a(e,t){return t.sort&&0!==t.sort.length?t.sort.map((function(e){return Object.keys(e)[0]})):[e]}var s=new WeakMap;function u(e){if(s.has(e))return s.get(e);var t=e.collection,r=e.toJSON(),n=t.schema.primaryPath,o=t.storageInstance.getSortComparator(r),u=t.storageInstance.getQueryMatcher(r),c={primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:a(n,r),sortComparator:function(t,r){var n={docA:t,docB:r,rxQuery:e};return(0,i.runPluginHooks)("preSortComparator",n),o(n.docA,n.docB)},queryMatcher:function(t){var r={doc:t,rxQuery:e};return(0,i.runPluginHooks)("preQueryMatcher",r),u(r.doc)}};return s.set(e,c),c}r.RXQUERY_QUERY_PARAMS_CACHE=s},{"./hooks":7,"./rx-change-event":42,"event-reduce-js":534}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.runPluginHooks=function(e,t){n[e].forEach((function(e){return e(t)}))},r.runAsyncPluginHooks=function(e,t){return Promise.all(n[e].map((function(e){return e(t)})))},r._clearHook=function(e,t){n[e]=n[e].filter((function(e){return e!==t}))},r.HOOKS=void 0;var n={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],createRxQuery:[],preQueryMatcher:[],preSortComparator:[],prePrepareQuery:[],preWriteToStorageInstance:[],postReadFromInstance:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[]};r.HOOKS=n},{}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./core");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===n[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return n[e]}}))}));var i=e("./plugins/dev-mode"),o=e("./plugins/validate"),a=e("./plugins/key-compression"),s=e("./plugins/migration"),u=e("./plugins/leader-election"),c=e("./plugins/encryption"),f=e("./plugins/update"),l=e("./plugins/replication-couchdb"),d=e("./plugins/json-dump"),h=e("./plugins/in-memory"),p=e("./plugins/attachments"),b=e("./plugins/local-documents"),v=e("./plugins/query-builder"),m=e("./plugins/pouchdb");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===m[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return m[e]}}))})),(0,n.addRxPlugin)(i.RxDBDevModePlugin),(0,n.addRxPlugin)(o.RxDBValidatePlugin),(0,n.addRxPlugin)(a.RxDBKeyCompressionPlugin),(0,n.addRxPlugin)(s.RxDBMigrationPlugin),(0,n.addRxPlugin)(u.RxDBLeaderElectionPlugin),(0,n.addRxPlugin)(c.RxDBEncryptionPlugin),(0,n.addRxPlugin)(f.RxDBUpdatePlugin),(0,n.addRxPlugin)(l.RxDBReplicationCouchDBPlugin),(0,n.addRxPlugin)(d.RxDBJsonDumpPlugin),(0,n.addRxPlugin)(h.RxDBInMemoryPlugin),(0,n.addRxPlugin)(p.RxDBAttachmentsPlugin),(0,n.addRxPlugin)(b.RxDBLocalDocumentsPlugin),(0,n.addRxPlugin)(v.RxDBQueryBuilderPlugin)},{"./core":3,"./plugins/attachments":11,"./plugins/dev-mode":19,"./plugins/encryption":21,"./plugins/in-memory":22,"./plugins/json-dump":23,"./plugins/key-compression":24,"./plugins/leader-election":25,"./plugins/local-documents":26,"./plugins/migration":28,"./plugins/pouchdb":32,"./plugins/query-builder":35,"./plugins/replication-couchdb":38,"./plugins/update":39,"./plugins/validate":40}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.overwritable=void 0;var n=e("./util"),i={isDevMode:function(){return!1},deepFreezeWhenDevMode:function(e){return e},validatePassword:function(e){throw(0,n.pluginMissing)("encryption")},tunnelErrorMessage:function(e){return"RxDB Error-Code "+e+".\n - To find out what this means, use the dev-mode-plugin https://pubkey.github.io/rxdb/custom-build.html#dev-mode\n - Or search for this code https://github.com/pubkey/rxdb/search?q="+e+"\n "}};r.overwritable=i},{"./util":58}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.addRxPlugin=function(e){if((0,f.runPluginHooks)("preAddRxPlugin",{plugin:e,plugins:h}),h.has(e))return;h.add(e);if(!e.rxdb)throw(0,l.newRxTypeError)("PL1",{plugin:e});e.prototypes&&Object.entries(e.prototypes).forEach((function(e){var t=e[0];return(0,e[1])(d[t])}));e.overwritable&&Object.assign(c.overwritable,e.overwritable);e.hooks&&Object.entries(e.hooks).forEach((function(e){var t=e[0],r=e[1];return f.HOOKS[t].push(r)}))};var n=e("./rx-schema"),i=e("./crypter"),o=e("./rx-document"),a=e("./rx-query"),s=e("./rx-collection"),u=e("./rx-database"),c=e("./overwritable"),f=e("./hooks"),l=e("./rx-error"),d={RxSchema:n.RxSchema.prototype,Crypter:i.Crypter.prototype,RxDocument:o.basePrototype,RxQuery:a.RxQueryBase.prototype,RxCollection:s.RxCollectionBase.prototype,RxDatabase:u.RxDatabaseBase.prototype},h=new Set},{"./crypter":4,"./hooks":7,"./overwritable":9,"./rx-collection":44,"./rx-database":45,"./rx-document":47,"./rx-error":48,"./rx-query":49,"./rx-schema":51}],11:[function(e,t,r){(function(t){(function(){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.fromStorageInstanceResult=d,r.putAttachment=p,r.getAttachment=v,r.allAttachments=m,r.preMigrateDocument=y,r.postMigrateDocument=_,r.RxDBAttachmentsPlugin=r.hooks=r.overwritable=r.prototypes=r.rxdb=r.RxAttachment=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=e("rxjs/operators"),s=e("./../util"),u=e("../rx-error"),c=e("../rx-storage-helper");function f(e){if(!e.collection.schema.jsonSchema.attachments)throw(0,u.newRxError)("AT1",{link:"https://pubkey.github.io/rxdb/rx-attachment.html"})}var l=function(){function e(e){var t,r=e.doc,n=e.id,i=e.type,o=e.length,a=e.digest;this.doc=r,this.id=n,this.type=i,this.length=o,this.digest=a,t=this,Object.entries(t.doc.collection.attachments).forEach((function(e){var r=e[0],n=e[1];Object.defineProperty(t,r,{get:function(){return n.bind(t)}})}))}var t=e.prototype;return t.remove=function(){var e=(0,o.default)(i.default.mark((function e(){var t=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.doc._atomicQueue=this.doc._atomicQueue.then((0,o.default)(i.default.mark((function e(){var r,n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(r=(0,s.flatClone)(t.doc._data))._attachments=(0,s.flatClone)(r._attachments),delete r._attachments[t.id],e.next=5,(0,c.writeSingle)(t.doc.collection.storageInstance,{previous:t.doc._data,document:r});case 5:n=e.sent,(o=(0,s.flatClone)(t.doc._data))._rev=n._rev,o._attachments=n._attachments,t.doc._dataSync$.next(o);case 10:case"end":return e.stop()}}),e)})))),e.abrupt("return",this.doc._atomicQueue);case 2:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}(),t.getData=function(){var e=(0,o.default)(i.default.mark((function e(){var t,r,n;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.doc.collection.storageInstance.getAttachmentData(this.doc.primary,this.id);case 2:if(t=e.sent,!h(this.doc.collection.schema)){e.next=11;break}return e.next=6,s.blobBufferUtil.toString(t);case 6:return r=e.sent,n=s.blobBufferUtil.createBlobBuffer(this.doc.collection._crypter._decryptString(r),this.type),e.abrupt("return",n);case 11:return e.abrupt("return",t);case 12:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}(),t.getStringData=function(){return this.getData().then((function(e){return s.blobBufferUtil.toString(e)}))},e}();function d(e,t,r){return new l({doc:r,id:e,type:t.type,length:t.length,digest:t.digest})}function h(e){return!(!e.jsonSchema.attachments||!e.jsonSchema.attachments.encrypted)}function p(e){return b.apply(this,arguments)}function b(){return(b=(0,o.default)(i.default.mark((function e(r){var n,a,u,l,p,b,v,m=this,y=arguments;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=r.id,a=r.data,u=r.type,l=void 0===u?"text/plain":u,p=!(y.length>1&&void 0!==y[1])||y[1],f(this),!h(this.collection.schema)){e.next=9;break}return e.next=6,s.blobBufferUtil.toString(a);case 6:b=e.sent,v=this.collection._crypter._encryptString(b),a=s.blobBufferUtil.createBlobBuffer(v,"text/plain");case 9:return this._atomicQueue=this._atomicQueue.then((0,o.default)(i.default.mark((function e(){var r,o,u,f,h,b,v,y;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(p&&m._data._attachments&&m._data._attachments[n])){e.next=7;break}return r=m._data._attachments[n],e.next=4,m.collection.database.storage.hash(a);case 4:if(o=e.sent,r.type!==l||r.digest!==o){e.next=7;break}return e.abrupt("return",m.getAttachment(n));case 7:return(u=(0,s.flatClone)(m._data))._attachments=(0,s.flatClone)(u._attachments),f="string"==typeof a?t.from(a):a,u._attachments[n]={type:l,data:f},e.next=13,(0,c.writeSingle)(m.collection.storageInstance,{previous:m._data,document:u});case 13:return h=e.sent,b=h._attachments[n],v=d(n,b,m),(y=(0,s.flatClone)(m._data))._rev=h._rev,y._attachments=h._attachments,m._dataSync$.next(y),e.abrupt("return",v);case 21:case"end":return e.stop()}}),e)})))),e.abrupt("return",this._atomicQueue);case 11:case"end":return e.stop()}}),e,this)})))).apply(this,arguments)}function v(e){f(this);var t=this._dataSync$.getValue();return t._attachments&&t._attachments[e]?d(e,t._attachments[e],this):null}function m(){var e=this;f(this);var t=this._dataSync$.getValue();return t._attachments?Object.keys(t._attachments).map((function(r){return d(r,t._attachments[r],e)})):[]}function y(e){return g.apply(this,arguments)}function g(){return(g=(0,o.default)(i.default.mark((function e(t){var r,n,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(r=t.docData._attachments)){e.next=7;break}return n=!!h(t.oldCollection.schema),a={},e.next=6,Promise.all(Object.keys(r).map(function(){var e=(0,o.default)(i.default.mark((function e(o){var u,c,f;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return u=r[o],c=t.docData[t.oldCollection.schema.primaryPath],e.next=4,t.oldCollection.storageInstance.getAttachmentData(c,o);case 4:if(f=e.sent,!n){e.next=9;break}return e.next=8,s.blobBufferUtil.toString(f).then((function(e){return s.blobBufferUtil.createBlobBuffer(t.oldCollection._crypter._decryptString(e),u.type)}));case 8:f=e.sent;case 9:a[o]={type:u.type,data:f};case 10:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 6:t.docData._attachments=a;case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function _(e){return w.apply(this,arguments)}function w(){return(w=(0,o.default)(i.default.mark((function e(t){return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return");case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}r.RxAttachment=l;r.rxdb=true;var S={RxDocument:function(e){e.putAttachment=p,e.getAttachment=v,e.allAttachments=m,Object.defineProperty(e,"allAttachments$",{get:function(){var e=this;return this._dataSync$.pipe((0,a.map)((function(e){return e._attachments?e._attachments:{}})),(0,a.map)((function(e){return Object.entries(e)})),(0,a.map)((function(t){return t.map((function(t){return d(t[0],t[1],e)}))})))}})}};r.prototypes=S;var x={};r.overwritable=x;var O={preMigrateDocument:y,postMigrateDocument:_};r.hooks=O;var j={name:"attachments",rxdb:true,prototypes:S,overwritable:x,hooks:O};r.RxDBAttachmentsPlugin=j}).call(this)}).call(this,e("buffer").Buffer)},{"../rx-error":48,"../rx-storage-helper":52,"./../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,buffer:170,"rxjs/operators":908}],12:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkMigrationStrategies=function(e,t){if("object"!=typeof t||Array.isArray(t))throw(0,n.newRxTypeError)("COL11",{schema:e});var r=(0,i.getPreviousVersions)(e);if(r.length!==Object.keys(t).length)throw(0,n.newRxError)("COL12",{have:Object.keys(t),should:r});return r.map((function(e){return{v:e,s:t[e+1]}})).filter((function(e){return"function"!=typeof e.s})).forEach((function(t){throw(0,n.newRxTypeError)("COL13",{version:t.v,type:typeof t,schema:e})})),!0};var n=e("../../rx-error"),i=e("../../rx-schema")},{"../../rx-error":48,"../../rx-schema":51}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.validateDatabaseName=function(e){if("string"!=typeof e||0===e.length)throw(0,n.newRxTypeError)("UT1",{name:e});if((0,i.isFolderPath)(e))return!0;if(!e.match(a))throw(0,n.newRxError)("UT2",{regex:o,givenName:e});return!0};var n=e("../../rx-error"),i=e("../../util"),o="^[a-z][_$a-z0-9]*$",a=new RegExp(o)},{"../../rx-error":48,"../../util":58}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkOrmMethods=function(e){if(!e)return;Object.entries(e).forEach((function(e){var t=e[0],r=e[1];if("string"!=typeof t)throw(0,n.newRxTypeError)("COL14",{name:t});if(t.startsWith("_"))throw(0,n.newRxTypeError)("COL15",{name:t});if("function"!=typeof r)throw(0,n.newRxTypeError)("COL16",{name:t,type:typeof t});if((0,i.rxCollectionProperties)().includes(t)||(0,i.rxDocumentProperties)().includes(t))throw(0,n.newRxError)("COL17",{name:t})}))};var n=e("../../rx-error"),i=e("./entity-properties")},{"../../rx-error":48,"./entity-properties":17}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkQuery=function(e){if("[object Object]"!==Object.prototype.toString.call(e.queryObj))throw(0,n.newRxTypeError)("QU11",{op:e.op,collection:e.collection.name,queryObj:e.queryObj});var t=["selector","limit","skip","sort"];Object.keys(e.queryObj).forEach((function(r){if(!t.includes(r))throw(0,n.newRxTypeError)("QU11",{op:e.op,collection:e.collection.name,queryObj:e.queryObj,key:r})}))};var n=e("../../rx-error")},{"../../rx-error":48}],16:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.checkFieldNameRegex=u,r.validateFieldsDeep=c,r.checkSchema=function(e){if(!e.primaryKey)throw(0,o.newRxError)("SC30",{schema:e});if(!e.hasOwnProperty("properties"))throw(0,o.newRxError)("SC29",{schema:e});if(e.properties._rev)throw(0,o.newRxError)("SC10",{schema:e});if(!e.hasOwnProperty("version")||"number"!=typeof e.version||e.version<0)throw(0,o.newRxError)("SC11",{version:e.version});if(c(e),Object.keys(e.properties).forEach((function(t){var r=e.properties[t];if(t===e.primaryKey){if(e.indexes&&e.indexes.includes(t))throw(0,o.newRxError)("SC13",{value:r});if(r.unique)throw(0,o.newRxError)("SC14",{value:r});if(e.encrypted&&e.encrypted.includes(t))throw(0,o.newRxError)("SC15",{value:r});if("string"!==r.type)throw(0,o.newRxError)("SC16",{value:r})}if((0,s.rxDocumentProperties)().includes(t))throw(0,o.newRxError)("SC17",{key:t})})),e.indexes){if(!Array.isArray(e.indexes))throw(0,o.newRxError)("SC18",{indexes:e.indexes});e.indexes.forEach((function(e){if("string"!=typeof e&&!Array.isArray(e))throw(0,o.newRxError)("SC19",{index:e});if(Array.isArray(e))for(var t=0;t2||!t.type.includes("string")||!t.type.includes("null"))throw(0,o.newRxError)("SC4",{fieldName:e})}else switch(t.type){case"string":break;case"array":if(!t.items||!t.items.type||"string"!==t.items.type)throw(0,o.newRxError)("SC3",{fieldName:e});break;default:throw(0,o.newRxError)("SC4",{fieldName:e})}var n=r.split(".").length>=2;if(n){if(t.primary)throw(0,o.newRxError)("SC6",{path:r,primary:t.primary});if(t.default)throw(0,o.newRxError)("SC7",{path:r})}if(!n&&"_"===e.charAt(0)){if("_deleted"===e)return;throw(0,o.newRxError)("SC8",{fieldName:e})}}(n,t[n],r);var i=r;"properties"!==n&&(i=i+"."+n),e(t[n],i)}))}(e,""),!0}function f(e){for(var t=e.split("."),r="",n=0;n 2",QU1:"RxQuery._execOverDatabase(): op not known",QU4:"RxQuery.regex(): You cannot use .regex() on the primary field",QU5:"RxQuery.sort(): does not work because key is not defined in the schema",QU6:"RxQuery.limit(): cannot be called on .findOne()",QU7:"query must be an object",QU8:"query cannot be an array",QU9:"throwIfMissing can only be used in findOne queries",QU10:"result empty and throwIfMissing: true",QU11:"RxQuery: no valid query params given",MQ1:"path must be a string or object",MQ2:"Invalid argument",MQ3:"Invalid sort() argument. Must be a string, object, or array",MQ4:"Invalid argument. Expected instanceof mquery or plain object",MQ5:"method must be used after where() when called with these arguments",MQ6:"Can't mix sort syntaxes. Use either array or object | .sort([['field', 1], ['test', -1]]) | .sort({ field: 1, test: -1 })",MQ7:"Invalid sort value",MQ8:"Can't mix sort syntaxes. Use either array or object",DB1:"RxDocument.prepare(): another instance on this adapter has a different password",DB2:"RxDatabase.addCollections(): collection-names cannot start with underscore _",DB3:"RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it",DB4:"RxDatabase.addCollections(): schema is missing",DB5:"RxDatabase.addCollections(): collection-name not allowed",DB6:"RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema",DB7:"RxDatabase.addCollections(): schema encrypted but no password given",DB8:"RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\nMake sure to use this combination only once or set ignoreDuplicate to true if you do this intentional",DB9:"RxDatabase.create(): Adapter not added. Use RxDB.plugin(require('pouchdb-adapter-[adaptername]');",DB10:"RxDatabase.create(): To use leveldown-adapters, you have to add the leveldb-plugin. Use RxDB.plugin(require('pouchdb-adapter-leveldb'));",DB11:"RxDatabase.create(): Invalid db-name, folder-paths must not have an ending slash",COL1:"RxDocument.insert() You cannot insert an existing document",COL3:"RxCollection.upsert() does not work without primary",COL4:"RxCollection.atomicUpsert() does not work without primary",COL5:"RxCollection.find() if you want to search by _id, use .findOne(_id)",COL6:"RxCollection.findOne() needs a queryObject or string",COL7:"hook must be a function",COL8:"hooks-when not known",COL9:"RxCollection.addHook() hook-name not known",COL10:"RxCollection .postCreate-hooks cannot be async",COL11:"migrationStrategies must be an object",COL12:"A migrationStrategy is missing or too much",COL13:"migrationStrategy must be a function",COL14:"given static method-name is not a string",COL15:"static method-names cannot start with underscore _",COL16:"given static method is not a function",COL17:"RxCollection.ORM: statics-name not allowed",COL18:"collection-method not allowed because fieldname is in the schema",COL19:"Pouchdb document update conflict",DOC1:"RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed",DOC2:"cannot observe primary path",DOC3:"final fields cannot be observed",DOC4:"RxDocument.get$ cannot observe a non-existed field",DOC5:"RxDocument.populate() cannot populate a non-existed field",DOC6:"RxDocument.populate() cannot populate because path has no ref",DOC7:"RxDocument.populate() ref-collection not in database",DOC8:"RxDocument.set(): primary-key cannot be modified",DOC9:"final fields cannot be modified",DOC10:"RxDocument.set(): cannot set childpath when rootPath not selected",DOC11:"RxDocument.save(): cant save deleted document",DOC13:"RxDocument.remove(): Document is already deleted",DOC14:"RxDocument.destroy() does not exist",DOC15:"query cannot be an array",DOC16:"Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments",DOC17:"Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents",DM1:"migrate() Migration has already run",DM2:"migration of document failed final document does not match final schema",DM3:"migration already running",AT1:"to use attachments, please define this in your schema",EN1:"password is no string",EN2:"validatePassword: min-length of password not complied",JD1:"You must create the collections before you can import their data",JD2:"RxCollection.importJSON(): the imported json relies on a different schema",JD3:"RxCollection.importJSON(): json.passwordHash does not match the own",LD1:"RxDocument.allAttachments$ cant use attachments on local documents",LD2:"RxDocument.get(): objPath must be a string",LD3:"RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed",LD4:"cannot observe primary path",LD5:"RxDocument.set() id cannot be modified",LD6:"LocalDocument: Function is not useable on local documents",LD7:"Local document already exists",RC1:"Replication: already added",RC2:"RxCollection.syncCouchDB() query must be from the same RxCollection",RC3:"RxCollection.syncCouchDB() Do not use a collection's pouchdb as remote, use the collection instead",RC4:"RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication when live: true",RC5:"RxCouchDBReplicationState.awaitInitialReplication() cannot await inital replication if multiInstance because the replication might run on another instance",SC1:"fieldnames do not match the regex",SC2:"SchemaCheck: name 'item' reserved for array-fields",SC3:"SchemaCheck: fieldname has a ref-array but items-type is not string",SC4:"SchemaCheck: fieldname has a ref but is not type string, [string,null] or array",SC6:"SchemaCheck: primary can only be defined at top-level",SC7:"SchemaCheck: default-values can only be defined at top-level",SC8:"SchemaCheck: first level-fields cannot start with underscore _",SC10:"SchemaCheck: schema defines ._rev, this will be done automatically",SC11:"SchemaCheck: schema needs a number >=0 as version",SC13:"SchemaCheck: primary is always index, do not declare it as index",SC14:"SchemaCheck: primary is always unique, do not declare it as index",SC15:"SchemaCheck: primary cannot be encrypted",SC16:"SchemaCheck: primary must have type: string",SC17:"SchemaCheck: top-level fieldname is not allowed",SC18:"SchemaCheck: indexes must be an array",SC19:"SchemaCheck: indexes must contain strings or arrays of strings",SC20:"SchemaCheck: indexes.array must contain strings",SC21:"SchemaCheck: given index is not defined in schema",SC22:"SchemaCheck: given indexKey is not type:string",SC23:"SchemaCheck: fieldname is not allowed",SC24:"SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required",SC25:"SchemaCheck: compoundIndexes needs to be specified in the indexes field",SC26:"SchemaCheck: indexes needs to be specified at collection schema level",SC27:"SchemaCheck: encrypted fields need to be specified at collection schema level",SC28:"SchemaCheck: encrypted fields is not defined in the schema",SC29:"SchemaCheck: missing object key 'properties'",SC30:"SchemaCheck: primaryKey is required",DEV1:"dev-mode added multiple times, this is likely because you have mixed up the import from the the plugins/core and the full RxDB",VD1:"Sub-schema not found, does the schemaPath exists in your schema?",VD2:"object does not match schema",IM1:"InMemory: Memory-Adapter must be added. Use addPouchPlugin(require('pouchdb-adapter-memory'));",IM2:"inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead",S1:"You cannot create collections after calling RxDatabase.server()",SNH:"This should never happen"}},{}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={deepFreezeWhenDevMode:!0,RxDBDevModePlugin:!0};r.deepFreezeWhenDevMode=h,r.RxDBDevModePlugin=void 0;var i=e("./error-messages"),o=e("./check-schema");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===o[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return o[e]}}))}));var a=e("./check-orm"),s=e("./check-migration-strategies"),u=e("./unallowed-properties"),c=e("./check-query"),f=e("../../rx-error"),l=e("./check-names");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===l[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return l[e]}}))}));var d=e("deep-freeze");function h(e){return e?d(e):e}var p="dev-mode",b={name:p,rxdb:!0,overwritable:{isDevMode:function(){return!0},deepFreezeWhenDevMode:h,tunnelErrorMessage:function(e){if(!i.ERROR_MESSAGES[e])throw console.error("RxDB: Error-Code not known: "+e),new Error("Error-Code "+e+" not known, contact the maintainer");return i.ERROR_MESSAGES[e]}},hooks:{preAddRxPlugin:function(e){if(e.plugin.name===p)throw(0,f.newRxError)("DEV1",{plugins:e.plugins})},preCreateRxSchema:o.checkSchema,preCreateRxDatabase:function(e){(0,u.ensureDatabaseNameIsValid)(e)},preCreateRxCollection:function(e){if((0,u.ensureCollectionNameValid)(e),"_"===e.name.charAt(0))throw(0,f.newRxError)("DB2",{name:e.name});if(!e.schema)throw(0,f.newRxError)("DB4",{name:e.name,args:e})},preCreateRxQuery:function(e){(0,c.checkQuery)(e)},createRxCollection:function(e){(0,a.checkOrmMethods)(e.statics),(0,a.checkOrmMethods)(e.methods),(0,a.checkOrmMethods)(e.attachments),e.schema&&e.migrationStrategies&&(0,s.checkMigrationStrategies)(e.schema,e.migrationStrategies)}}};r.RxDBDevModePlugin=b},{"../../rx-error":48,"./check-migration-strategies":12,"./check-names":13,"./check-orm":14,"./check-query":15,"./check-schema":16,"./error-messages":18,"./unallowed-properties":20,"deep-freeze":498}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ensureCollectionNameValid=function(e){if((0,i.rxDatabaseProperties)().includes(e.name))throw(0,n.newRxError)("DB5",{name:e.name})},r.ensureDatabaseNameIsValid=function(e){if((0,a.validateDatabaseName)(e.name),(0,o.isFolderPath)(e.name)&&(e.name.endsWith("/")||e.name.endsWith("\\")))throw(0,n.newRxError)("DB11",{name:e.name})};var n=e("../../rx-error"),i=e("./entity-properties"),o=e("../../util"),a=e("./check-names")},{"../../rx-error":48,"../../util":58,"./check-names":13,"./entity-properties":17}],21:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.encrypt=d,r.decrypt=h,r.storePasswordHashIntoDatabase=v,r.RxDBEncryptionPlugin=r.overwritable=r.prototypes=r.rxdb=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("crypto-js/aes")),s=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=l(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(n,o,a):n[o]=e[o]}n.default=e,r&&r.set(e,n);return n}(e("crypto-js/enc-utf8")),u=e("../rx-error"),c=e("../util"),f=e("../rx-storage-helper");function l(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(l=function(e){return e?r:t})(e)}function d(e,t){return a.default.encrypt(e,t).toString()}function h(e,t){return a.default.decrypt(e,t).toString(s)}var p=function(e){return d(e,this.password)},b=function(e){return h(e,this.password)};function v(e){return m.apply(this,arguments)}function m(){return(m=(0,o.default)(i.default.mark((function e(t){var r,n,o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.password){e.next=2;break}return e.abrupt("return",Promise.resolve(!1));case 2:return r=(0,c.hash)(t.password),n="pwHash",e.next=6,(0,f.findLocalDocument)(t.localDocumentsStore,n);case 6:if(o=e.sent){e.next=14;break}return a={_id:n,value:r,_attachments:{}},e.next=11,t.localDocumentsStore.bulkWrite([{document:a}]);case 11:return e.abrupt("return",!0);case 14:if(r===o.value){e.next=20;break}return e.next=17,t.destroy();case 17:throw(0,u.newRxError)("DB1",{passwordHash:(0,c.hash)(t.password),existingPasswordHash:o.value});case 20:return e.abrupt("return",!0);case 21:case"end":return e.stop()}}),e)})))).apply(this,arguments)}r.rxdb=true;var y={Crypter:function(e){e._encryptString=p,e._decryptString=b}};r.prototypes=y;var g={validatePassword:function(e){if(e&&"string"!=typeof e)throw(0,u.newRxTypeError)("EN1",{password:e});if(e&&e.length<8)throw(0,u.newRxError)("EN2",{minPassLength:8,password:e})}};r.overwritable=g;var _={name:"encryption",rxdb:true,prototypes:y,overwritable:g,hooks:{createRxDatabase:function(e){return v(e)}}};r.RxDBEncryptionPlugin=_},{"../rx-error":48,"../rx-storage-helper":52,"../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"crypto-js/aes":486,"crypto-js/enc-utf8":490}],22:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.replicateExistingDocuments=O,r.setIndexes=j,r.streamChangedDocuments=E,r.applyChangedDocumentToPouch=M,r.inMemory=A,r.prepareInMemoryRxCollection=R,r.RxDBInMemoryPlugin=r.prototypes=r.rxdb=r.InMemoryRxCollection=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("@babel/runtime/helpers/assertThisInitialized")),s=n(e("@babel/runtime/helpers/inheritsLoose")),u=e("rxjs"),c=e("rxjs/operators"),f=e("../rx-collection"),l=e("../util"),d=e("../plugins/pouchdb"),h=e("../crypter"),p=e("../change-event-buffer"),b=e("../rx-schema"),v=e("../rx-error"),m=e("../rx-change-event"),y=e("../rx-collection-helper"),g=new WeakMap,_=new WeakMap,w={new_edits:!0},S={new_edits:!1},x=function(e){function t(t,r){var n,i,o;(n=e.call(this,t.database,t.name,(i=t.schema,(o=(0,l.clone)(i.jsonSchema)).keyCompression=!1,delete o.properties._rev,delete o.properties._attachments,function e(t,r){delete t.encrypted,Object.values(t).filter((function(e){return"object"==typeof e})).forEach((function(t){return e(t,r)}))}(o,o),(0,b.createRxSchema)(o)),r,{},t._methods)||this)._eventCounter=0,n.parentCollection=t,n.pouchSettings=r,n._isInMemory=!0,t.onDestroy.then((function(){return n.destroy()})),n._crypter=(0,h.createCrypter)(n.database.password,n.schema),n._changeStreams=[],n.onDestroy.then((function(){n._changeStreams.forEach((function(e){return e.cancel()})),n.storageInstance.internals.pouch.destroy()})),n.options=t.options,Object.entries(t.statics).forEach((function(e){var t=e[0],r=e[1];Object.defineProperty((0,a.default)(n),t,{get:function(){return r.bind((0,a.default)(n))}})})),n._observable$=new u.Subject,n._changeEventBuffer=(0,p.createChangeEventBuffer)((0,a.default)(n));var s=Object.getPrototypeOf(t);return n._oldPouchPut=s._pouchPut.bind((0,a.default)(n)),n._nonPersistentRevisions=new Set,n._nonPersistentRevisionsSubject=new u.Subject,n}(0,s.default)(t,e);var r=t.prototype;return r.prepareChild=function(){var e=this;return j(this.schema,this.storageInstance.internals.pouch).then((function(){e._subs.push(e._observable$.subscribe((function(t){var r=e._docCache.get(t.documentId);r&&r._handleChangeEvent(t)})))})).then((function(){return O(e.parentCollection,e)})).then((function(){var t=E(e).pipe((0,c.mergeMap)((function(t){return M(e.parentCollection,t).then((function(){return t._rev}))}))).subscribe((function(t){e._nonPersistentRevisions.delete(t),e._nonPersistentRevisionsSubject.next(e._nonPersistentRevisions.size)}));e._subs.push(t);var r=E(e.parentCollection).subscribe((function(t){return M(e,t)}));e._subs.push(r)}))},r.awaitPersistence=function(){var e=this;return 0===this._nonPersistentRevisions.size?Promise.resolve():(0,u.firstValueFrom)(this._nonPersistentRevisionsSubject.pipe((0,c.filter)((function(){return 0===e._nonPersistentRevisions.size}))))},r._pouchPut=function(e,t){var r=this;return this._oldPouchPut(e,t).then((function(e){return r._nonPersistentRevisions.add(e.rev),e}))},r.$emit=function(e){var t=(0,m.getDocumentDataOfRxChangeEvent)(e);this._changeEventBuffer.hasChangeWithRevision(t&&t._rev)||(this._observable$.next(e),this._eventCounter++,10===this._eventCounter&&(this._eventCounter=0,this.storageInstance.internals.pouch.compact()))},r.syncCouchDB=function(){throw(0,v.newRxError)("IM2")},t}(f.RxCollectionBase);function O(e,t){return e.storageInstance.internals.pouch.allDocs({attachments:!1,include_docs:!0}).then((function(r){var n=r.rows.map((function(e){return e.doc})).filter((function(e){return!e.language})).map((function(t){return(0,y._handleFromStorageInstance)(e,t)})).map((function(t){var r=e.schema.primaryPath;return(0,d.pouchSwapPrimaryToId)(r,t)}));return 0===n.length?Promise.resolve([]):t.storageInstance.internals.pouch.bulkDocs({docs:n},S).then((function(){return n}))}))}function j(e,t){return Promise.all(e.indexes.map((function(e){var r="idx-rxdb-"+e.join(",");return t.createIndex({ddoc:r,name:r,index:{fields:e}})})))}function E(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return!0};e._doNotEmitSet||(e._doNotEmitSet=new Set);var r=(0,u.fromEvent)(e.storageInstance.internals.pouch.changes({since:"now",live:!0,include_docs:!0}),"change").pipe((0,c.delay)(0),(0,c.map)((function(e){return e[0]})),(0,c.filter)((function(t){var r=t.id+":"+t.doc._rev;return!e._doNotEmitSet.has(r)})),(0,c.filter)((function(e){return t(e)})),(0,c.map)((function(t){return(0,y._handleFromStorageInstance)(e,t.doc)})),(0,c.map)((function(t){var r=e.schema.primaryPath;return(0,d.pouchSwapIdToPrimary)(r,t)})));return r}function M(e,t){e._doNotEmitSet||(e._doNotEmitSet=new Set);var r=e.schema.primaryPath,n=(0,y._handleToStorageInstance)(e,t);return n=(0,d.pouchSwapPrimaryToId)(r,n),e.storageInstance.internals.pouch.get(n._id).then((function(e){return n._rev=e._rev})).catch((function(){delete n._rev})).then((function(){return e.storageInstance.internals.pouch.bulkDocs({docs:[n]},w)})).then((function(t){if(t.length>0&&!t[0].ok)throw new Error(JSON.stringify(t[0]));var r=n._id+":"+t[0].rev;return e._doNotEmitSet.add(r),setTimeout((function(){return e._doNotEmitSet.delete(r)}),3e4),n}))}r.InMemoryRxCollection=x;var k=!1;function A(){return P.apply(this,arguments)}function P(){return(P=(0,o.default)(i.default.mark((function e(){var t,r,n=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(k){e.next=4;break}if(k=!0,d.PouchDB.adapters&&d.PouchDB.adapters.memory){e.next=4;break}throw(0,v.newRxError)("IM1");case 4:if(!g.has(this)){e.next=6;break}return e.abrupt("return",_.get(this).then((function(){return g.get(n)})));case 6:return t=new x(this),e.next=9,R(t);case 9:return r=t.prepareChild(),g.set(this,t),_.set(this,r),e.abrupt("return",r.then((function(){return t})));case 13:case"end":return e.stop()}}),e,this)})))).apply(this,arguments)}function R(e){return C.apply(this,arguments)}function C(){return(C=(0,o.default)(i.default.mark((function e(t){var r;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=(0,d.getRxStoragePouch)("memory",{}),e.next=3,r.createStorageInstance({databaseName:"rxdb-in-memory",collectionName:(0,l.randomCouchString)(10),schema:t.schema.jsonSchema,options:t.pouchSettings});case 3:t.storageInstance=e.sent,t.pouch=t.storageInstance.internals.pouch;case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}r.rxdb=true;var I={RxCollection:function(e){e.inMemory=A}};r.prototypes=I;var D={name:"in-memory",rxdb:true,prototypes:I};r.RxDBInMemoryPlugin=D},{"../change-event-buffer":2,"../crypter":4,"../plugins/pouchdb":32,"../rx-change-event":42,"../rx-collection":44,"../rx-collection-helper":43,"../rx-error":48,"../rx-schema":51,"../util":58,"@babel/runtime/helpers/assertThisInitialized":61,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/inheritsLoose":66,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,rxjs:684,"rxjs/operators":908}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RxDBJsonDumpPlugin=r.overwritable=r.prototypes=r.rxdb=void 0;var n=e("../util"),i=e("../rx-query"),o=e("../rx-error"),a=e("../rx-collection-helper");function s(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=arguments.length>1?arguments[1]:void 0,i={name:this.name,instanceToken:this.token,encrypted:!1,passwordHash:null,collections:[]};this.password&&(i.passwordHash=(0,n.hash)(this.password),i.encrypted=!t);var o=Object.keys(this.collections).filter((function(e){return!r||r.includes(e)})).filter((function(e){return"_"!==e.charAt(0)})).map((function(t){return e.collections[t]}));return Promise.all(o.map((function(e){return e.exportJSON(t)}))).then((function(e){return i.collections=e,i}))}var u=function(e){var t=this,r=e.collections.filter((function(e){return!t.collections[e.name]})).map((function(e){return e.name}));if(r.length>0)throw(0,o.newRxError)("JD1",{missingCollections:r});return Promise.all(e.collections.map((function(e){return t.collections[e.name].importJSON(e)})))},c=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=!e,r={name:this.name,schemaHash:this.schema.hash,encrypted:!1,passwordHash:null,docs:[]};this.database.password&&t&&(r.passwordHash=(0,n.hash)(this.database.password),r.encrypted=!0);var o=(0,i.createRxQuery)("find",(0,i._getDefaultQuery)(this),this);return this._queryStorageInstance(o,void 0,t).then((function(e){return r.docs=e.map((function(e){return delete e._rev,delete e._attachments,e})),r}))};function f(e){var t=this;if(e.schemaHash!==this.schema.hash)throw(0,o.newRxError)("JD2",{schemaHash:e.schemaHash,own:this.schema.hash});if(e.encrypted&&e.passwordHash!==(0,n.hash)(this.database.password))throw(0,o.newRxError)("JD3",{passwordHash:e.passwordHash,own:(0,n.hash)(this.database.password)});var r=e.docs.map((function(e){return t._crypter.decrypt(e)})).map((function(e){return t.schema.validate(e)}));return this.database.lockedRun((function(){(0,n.now)();var e=r.map((function(e){return{document:(0,a._handleToStorageInstance)(t,e)}}));return t.storageInstance.bulkWrite(e)}))}r.rxdb=true;var l={RxDatabase:function(e){e.exportJSON=s,e.importJSON=u},RxCollection:function(e){e.exportJSON=c,e.importJSON=f}};r.prototypes=l;var d={};r.overwritable=d;var h={name:"json-dump",rxdb:true,prototypes:l,overwritable:d};r.RxDBJsonDumpPlugin=h},{"../rx-collection-helper":43,"../rx-error":48,"../rx-query":49,"../util":58}],24:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createCompressionState=o,r.getCompressionStateByStorageInstance=a,r.RxDBKeyCompressionPlugin=r.overwritable=r.prototypes=r.rxdb=void 0;var n=e("jsonschema-key-compression"),i=new WeakMap;function o(e){var t=e.primaryKey,r=(0,n.createCompressionTable)(e,n.DEFAULT_COMPRESSION_FLAG,[t,"_rev","_attachments","_deleted"]),i=(0,n.createCompressedJsonSchema)(r,e);if(e.indexes){var o=e.indexes.map((function(e){return Array.isArray(e)?e.map((function(e){return(0,n.compressedPath)(r,e)})):(0,n.compressedPath)(r,e)}));i.indexes=o}return{table:r,schema:i}}function a(e){var t=i.get(e);return t||(t=o(e.schema.jsonSchema),i.set(e,t)),t}r.rxdb=true;var s={};r.prototypes=s;var u={};r.overwritable=u;var c={name:"key-compression",rxdb:true,prototypes:s,overwritable:u,hooks:{prePrepareQuery:function(e){var t=e.rxQuery,r=e.mangoQuery;if(t.collection.schema.jsonSchema.keyCompression){var i=a(t.collection),o=(0,n.compressQuery)(i.table,r);e.mangoQuery=o}},preCreateRxStorageInstance:function(e){if(e.schema.keyCompression){var t=o(e.schema);e.schema=t.schema}},preQueryMatcher:function(e){if(e.rxQuery.collection.schema.jsonSchema.keyCompression){var t=a(e.rxQuery.collection);e.doc=(0,n.compressObject)(t.table,e.doc)}},preSortComparator:function(e){if(e.rxQuery.collection.schema.jsonSchema.keyCompression){var t=a(e.rxQuery.collection);e.docA=(0,n.compressObject)(t.table,e.docA),e.docB=(0,n.compressObject)(t.table,e.docB)}},preWriteToStorageInstance:function(e){if(e.collection.schema.jsonSchema.keyCompression){var t=a(e.collection);e.doc=(0,n.compressObject)(t.table,e.doc)}},postReadFromInstance:function(e){if(e.collection.schema.jsonSchema.keyCompression){var t=a(e.collection);e.doc=(0,n.decompressObject)(t.table,e.doc)}}}};r.RxDBKeyCompressionPlugin=c},{"jsonschema-key-compression":612}],25:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getForDatabase=a,r.isLeader=s,r.waitForLeadership=u,r.onDestroy=c,r.RxDBLeaderElectionPlugin=r.prototypes=r.rxdb=r.LeaderElector=void 0;var n=e("broadcast-channel"),i=new WeakMap,o=function(){function e(e){this.destroyed=!1,this.isLeader=!1,this.isDead=!1,this.database=e,this.elector=(0,n.createLeaderElection)(e.broadcastChannel)}var t=e.prototype;return t.die=function(){return this.elector.die()},t.waitForLeadership=function(){var e=this;return this.elector.awaitLeadership().then((function(){return e.isLeader=!0,!0}))},t.destroy=function(){if(!this.destroyed)return this.destroyed=!0,this.isDead=!0,this.die()},e}();function a(){return i.has(this)||i.set(this,new o(this)),i.get(this)}function s(){return!this.multiInstance||this.leaderElector().isLeader}function u(){return this.multiInstance?this.leaderElector().waitForLeadership():Promise.resolve(!0)}function c(e){var t=i.get(e);t&&t.destroy()}r.LeaderElector=o;r.rxdb=true;var f={RxDatabase:function(e){e.leaderElector=a,e.isLeader=s,e.waitForLeadership=u}};r.prototypes=f;var l={name:"leader-election",rxdb:true,prototypes:f,hooks:{preDestroyRxDatabase:c}};r.RxDBLeaderElectionPlugin=l},{"broadcast-channel":113}],26:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxDBLocalDocumentsPlugin=r.RxLocalDocument=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("@babel/runtime/helpers/inheritsLoose")),s=n(e("object-path")),u=e("../rx-document"),c=e("../doc-cache"),f=e("../rx-error"),l=e("../util"),d=e("../rx-database"),h=e("../rx-collection"),p=e("rxjs/operators"),b=e("../rx-storage-helper"),v=e("../overwritable"),m=new WeakMap,y=function(e){return m.has(e)||m.set(e,(0,c.createDocCache)()),m.get(e)},g=new WeakMap,_=function(e){function t(t,r,n){var i;return(i=e.call(this,null,r)||this).id=t,i.parent=n,i}return(0,a.default)(t,e),t}((0,u.createRxDocumentConstructor)());function w(e){return(0,d.isRxDatabase)(e),e.localDocumentsStore}r.RxLocalDocument=_;var S={get isLocal(){return!0},_handleChangeEvent:function(e){if(e.documentId===this.primary)switch(e.operation){case"UPDATE":var t=e.documentData;this._dataSync$.next(t);break;case"DELETE":y(this.parent).delete(this.primary),this._isDeleted$.next(!0)}},get allAttachments$(){throw(0,f.newRxError)("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){return this._dataSync$.asObservable()},$emit:function(e){return this.parent.$emit(e)},get:function(e){if(this._data){if("string"!=typeof e)throw(0,f.newRxTypeError)("LD2",{objPath:e});var t=s.default.get(this._data,e);return t=v.overwritable.deepFreezeWhenDevMode(t)}},get$:function(e){if(e.includes(".item."))throw(0,f.newRxError)("LD3",{path:e});if(e===this.primaryPath)throw(0,f.newRxError)("LD4");return this._dataSync$.pipe((0,p.map)((function(t){return s.default.get(t,e)})),(0,p.distinctUntilChanged)())},set:function(e,t){if(!t){var r=(0,l.flatClone)(e);return r._rev=this._data._rev,this._data=r,this}if("_id"===e)throw(0,f.newRxError)("LD5",{objPath:e,value:t});if(!Object.is(this.get(e),t))return s.default.set(this._data,e,t),this},_saveData:function(e){var t=this._dataSync$.getValue(),r=w(this.parent);return e._id=this.id,r.bulkWrite([{previous:t,document:e}]).then((function(t){var r=t.success.get(e._id);if(!r)throw(0,l.getFromMapOrThrow)(t.error,e._id);e._rev=r._rev}))},remove:function(){var e=this,t=w(this.parent),r={_id:this.id,_deleted:!0,_attachments:{}};return(0,b.writeSingleLocal)(t,{previous:this._data,document:r}).then((function(){y(e.parent).delete(e.id)}))}},x=!1,O=function(){if(!x){x=!0;var e=u.basePrototype;Object.getOwnPropertyNames(e).forEach((function(t){if(!Object.getOwnPropertyDescriptor(S,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(S,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((function(e){return S[e]=function(e){return function(){throw(0,f.newRxError)("LD6",{functionName:e})}}(e)}))}};function j(e,t){var r=this;return(0,h.isRxCollection)(this)&&this._isInMemory?this.parentCollection.insertLocal(e,t):this.getLocal(e).then((function(n){if(n)throw(0,f.newRxError)("LD7",{id:e,data:t});return(t=(0,l.flatClone)(t))._id=e,(0,b.writeSingleLocal)(w(r),{document:t}).then((function(n){return t._rev=n._rev,_.create(e,t,r)}))}))}function E(e,t){var r=this;return(0,h.isRxCollection)(this)&&this._isInMemory?this._parentCollection.upsertLocal(e,t):this.getLocal(e).then((function(n){return n?(t._rev=n._data._rev,n.atomicUpdate((function(){return t})).then((function(){return n}))):r.insertLocal(e,t)}))}function M(e){var t=this;if((0,h.isRxCollection)(this)&&this._isInMemory)return this.parentCollection.getLocal(e);var r=w(this),n=y(this).get(e);return n?Promise.resolve(n):(0,b.findLocalDocument)(r,e).then((function(r){return r?_.create(e,r,t):null})).catch((function(){return null}))}function k(e){var t=this;return this.$.pipe((0,p.startWith)(null),(0,p.mergeMap)(function(){var r=(0,o.default)(i.default.mark((function r(n){var o;return i.default.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!n){r.next=4;break}return r.abrupt("return",{changeEvent:n});case 4:return r.next=6,t.getLocal(e);case 6:return o=r.sent,r.abrupt("return",{doc:o});case 8:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}()),(0,p.mergeMap)(function(){var r=(0,o.default)(i.default.mark((function r(n){var o,a;return i.default.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!n.changeEvent){r.next=12;break}if((o=n.changeEvent).isLocal&&o.documentId===e){r.next=6;break}return r.abrupt("return",{use:!1});case 6:return r.next=8,t.getLocal(e);case 8:return a=r.sent,r.abrupt("return",{use:!0,doc:a});case 10:r.next=13;break;case 12:return r.abrupt("return",{use:!0,doc:n.doc});case 13:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}()),(0,p.filter)((function(e){return e.use})),(0,p.map)((function(e){return e.doc})))}_.create=function(e,t,r){O(),function(e){if(!g.has(e)){var t=e.$.pipe((0,p.filter)((function(e){return e.isLocal}))).subscribe((function(t){var r=y(e).get(t.documentId);r&&r._handleChangeEvent(t)}));e._subs.push(t),g.set(e,t)}g.get(e)}(r);var n=new _(e,t,r);return n.__proto__=S,y(r).set(e,n),n};var A={name:"local-documents",rxdb:!0,prototypes:{RxCollection:function(e){e.insertLocal=j,e.upsertLocal=E,e.getLocal=M,e.getLocal$=k},RxDatabase:function(e){e.insertLocal=j,e.upsertLocal=E,e.getLocal=M,e.getLocal$=k}},overwritable:{}};r.RxDBLocalDocumentsPlugin=A},{"../doc-cache":5,"../overwritable":9,"../rx-collection":44,"../rx-database":45,"../rx-document":47,"../rx-error":48,"../rx-storage-helper":52,"../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/inheritsLoose":66,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"object-path":629,"rxjs/operators":908}],27:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.createOldCollection=y,r._getOldCollections=_,r.mustMigrate=S,r.createDataMigrator=function(e,t){return new m(e,t)},r.runStrategyIfNotNull=x,r.getBatchOfOldCollection=O,r.migrateDocumentData=j,r.isDocumentDataWithoutRevisionEqual=E,r._migrateDocument=M,r.deleteOldCollection=k,r.migrateOldCollection=A,r.migratePromise=function(e,t){e._migratePromise||(e._migratePromise=new Promise((function(r,n){A(e,t).subscribe(null,n,r)})));return e._migratePromise},r.DataMigrator=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=e("rxjs"),s=n(e("deep-equal")),u=e("../../util"),c=e("../../rx-schema"),f=e("../../rx-error"),l=e("../../hooks"),d=e("../../crypter"),h=e("./migration-state"),p=e("rxjs/operators"),b=e("../../rx-storage-helper"),v=e("../../rx-collection-helper"),m=function(){function e(e,t){this._migrated=!1,this.newestCollection=e,this.migrationStrategies=t,this.currentSchema=e.schema,this.database=e.database,this.name=e.name}var t=e.prototype;return t.migrate=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;if(this._migrated)throw(0,f.newRxError)("DM1");this._migrated=!0;var r,n={done:!1,total:0,handled:0,success:0,deleted:0,percent:0},i=new a.Subject,o=(0,h.getMigrationStateByDatabase)(this.newestCollection.database),s=o.getValue().slice(0);return s.push(i.asObservable()),o.next(s),_(e).then((function(e){return r=e,Promise.all(r.map((function(e){return(0,b.countAllUndeleted)(e.storageInstance)})))})).then((function(o){var a=o.reduce((function(e,t){return e+t}),0);n.total=a,i.next({collection:e.newestCollection,state:(0,u.flatClone)(n)});for(var s=r.shift(),c=Promise.resolve(),f=function(){var o=A(s,t);c=c.then((function(){return new Promise((function(t){var r=o.subscribe((function(t){n.handled++,n[t.type]=n[t.type]+1,n.percent=Math.round(n.handled/n.total*100),i.next({collection:e.newestCollection,state:(0,u.flatClone)(n)})}),(function(e){r.unsubscribe(),i.error(e)}),(function(){r.unsubscribe(),t()}))}))})),s=r.shift()};s;)f();return c})).then((function(){n.done=!0,n.percent=100,i.next({collection:e.newestCollection,state:(0,u.flatClone)(n)}),i.complete()})),i.pipe((0,p.map)((function(e){return e.state})))},t.migratePromise=function(e){var t=this;return this._migratePromise||(this._migratePromise=S(this).then((function(r){return r?new Promise((function(r,n){t.migrate(e).subscribe(null,n,r)})):Promise.resolve(!1)}))),this._migratePromise},e}();function y(e,t,r){return g.apply(this,arguments)}function g(){return(g=(0,o.default)(i.default.mark((function e(t,r,n){var o,a,s,u,f;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=n.newestCollection.database,a=(0,c.createRxSchema)(r,!1),s={databaseName:o.name,collectionName:n.newestCollection.name,schema:r,options:n.newestCollection.instanceCreationOptions},e.next=5,o.storage.createStorageInstance(s);case 5:return u=e.sent,f={version:t,dataMigrator:n,newestCollection:n.newestCollection,database:o,schema:(0,c.createRxSchema)(r,!1),storageInstance:u,_crypter:(0,d.createCrypter)(o.password,a)},e.abrupt("return",f);case 8:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function _(e){return w.apply(this,arguments)}function w(){return(w=(0,o.default)(i.default.mark((function e(t){var r;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Promise.all((0,c.getPreviousVersions)(t.currentSchema.jsonSchema).map((function(e){return(0,b.getSingleDocument)(t.database.internalStore,t.name+"-"+e)})).map((function(e){return e.catch((function(){return null}))})));case 2:return r=e.sent,e.abrupt("return",Promise.all(r.map((function(e){return e?y(e.schema.version,e.schema,t):null})).filter((function(e){return null!==e}))));case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function S(e){return 0===e.currentSchema.version?Promise.resolve(!1):_(e).then((function(e){return 0!==e.length}))}function x(e,t,r){if(null===r)return Promise.resolve(null);var n=e.dataMigrator.migrationStrategies[t](r,e);return(0,u.toPromise)(n)}function O(e,t){return(0,b.getBatch)(e.storageInstance,t).then((function(t){return t.map((function(t){return t=(0,u.flatClone)(t),t=(0,v._handleFromStorageInstance)(e,t)}))}))}function j(e,t){var r=(0,u.flatClone)(t._attachments),n=(0,u.clone)(t);n._attachments=r;for(var i=e.version+1,o=Promise.resolve(n),a=function(){var t=i;o=o.then((function(r){return x(e,t,r)})),i++};i<=e.newestCollection.schema.version;)a();return o.then((function(r){if(null===r)return Promise.resolve(null);try{e.newestCollection.schema.validate(r)}catch(i){var n=i;throw(0,f.newRxError)("DM2",{fromVersion:e.version,toVersion:e.newestCollection.schema.version,originalDoc:t,finalDoc:r,errors:n.parameters.errors,schema:n.parameters.schema})}return r}))}function E(e,t){var r=Object.assign({},e,{_attachments:void 0,_rev:void 0}),n=Object.assign({},t,{_attachments:void 0,_rev:void 0});return(0,s.default)(r,n)}function M(e,t){var r={res:null,type:"",migrated:null,doc:t,oldCollection:e,newestCollection:e.newestCollection};return(0,l.runAsyncPluginHooks)("preMigrateDocument",{docData:t,oldCollection:e}).then((function(){return j(e,t)})).then((function(n){if(E(t,n))n._rev=t._rev;else if(null!==n){var i=(0,u.getHeightOfRevision)(t._rev)+1+"-"+(0,u.createRevision)(n,!0);n._rev=i}if(r.migrated=n,n){var o=n._attachments,a=(0,v._handleToStorageInstance)(e.newestCollection,n);return a._attachments=o,e.newestCollection.storageInstance.bulkAddRevisions([a]).then((function(){return r.res=a,r.type="success",(0,l.runAsyncPluginHooks)("postMigrateDocument",r)}))}r.type="deleted"})).then((function(){var r=(0,u.flatClone)(t);return r._deleted=!0,e.storageInstance.bulkWrite([{previous:(0,v._handleToStorageInstance)(e,t),document:(0,v._handleToStorageInstance)(e,r)}])})).then((function(){return r}))}function k(e){return e.storageInstance.remove().then((function(){return e.database.removeCollectionDoc(e.dataMigrator.name,e.schema)}))}function A(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;if(e._migrate)throw(0,f.newRxError)("DM3");e._migrate=!0;var r,n=new a.Subject;return function i(){return O(e,t).then((function(t){return 0===t.length?(k(e).then((function(){return n.complete()})),!1):Promise.all(t.map((function(t){return M(e,t).then((function(e){return n.next(e)}))}))).catch((function(e){return r=e})).then((function(){return!0}))})).then((function(e){e&&(r?n.error(r):i())}))}(),n.asObservable()}r.DataMigrator=m},{"../../crypter":4,"../../hooks":7,"../../rx-collection-helper":43,"../../rx-error":48,"../../rx-schema":51,"../../rx-storage-helper":52,"../../util":58,"./migration-state":29,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"deep-equal":497,rxjs:684,"rxjs/operators":908}],28:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"_getOldCollections",{enumerable:!0,get:function(){return o._getOldCollections}}),Object.defineProperty(r,"getBatchOfOldCollection",{enumerable:!0,get:function(){return o.getBatchOfOldCollection}}),Object.defineProperty(r,"migrateDocumentData",{enumerable:!0,get:function(){return o.migrateDocumentData}}),Object.defineProperty(r,"_migrateDocument",{enumerable:!0,get:function(){return o._migrateDocument}}),Object.defineProperty(r,"deleteOldCollection",{enumerable:!0,get:function(){return o.deleteOldCollection}}),Object.defineProperty(r,"migrateOldCollection",{enumerable:!0,get:function(){return o.migrateOldCollection}}),Object.defineProperty(r,"migratePromise",{enumerable:!0,get:function(){return o.migratePromise}}),Object.defineProperty(r,"DataMigrator",{enumerable:!0,get:function(){return o.DataMigrator}}),r.RxDBMigrationPlugin=r.DATA_MIGRATOR_BY_COLLECTION=void 0;var n=e("rxjs"),i=e("rxjs/operators"),o=e("./data-migrator"),a=e("./migration-state"),s=new WeakMap;r.DATA_MIGRATOR_BY_COLLECTION=s;var u={name:"migration",rxdb:!0,hooks:{preDestroyRxDatabase:a.onDatabaseDestroy},prototypes:{RxDatabase:function(e){e.migrationStates=function(){return(0,a.getMigrationStateByDatabase)(this).pipe((0,i.switchMap)((function(e){return(0,n.combineLatest)(e)})),(0,i.shareReplay)({bufferSize:1,refCount:!0}))}},RxCollection:function(e){e.getDataMigrator=function(){return s.has(this)||s.set(this,(0,o.createDataMigrator)(this.asRxCollection,this.migrationStrategies)),s.get(this)},e.migrationNeeded=function(){return(0,o.mustMigrate)(this.getDataMigrator())}}}};r.RxDBMigrationPlugin=u},{"./data-migrator":27,"./migration-state":29,rxjs:684,"rxjs/operators":908}],29:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getMigrationStateByDatabase=function(e){o.has(e)||o.set(e,new n.BehaviorSubject([]));var t=o.get(e);return(0,i.ensureNotFalsy)(t)},r.onDatabaseDestroy=function(e){var t=o.get(e);t&&t.complete()},r.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE=void 0;var n=e("rxjs"),i=e("../../util"),o=new WeakMap;r.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE=o},{"../../util":58,rxjs:684}],30:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.checkAdapter=function(e){var t,r,a=o+"-"+(0,i.randomCouchString)(12);try{t=new n.PouchDB(o,(0,i.adapterObject)(e),{auto_compaction:!0,revs_limit:1})}catch(e){return Promise.resolve(!1)}return t.info().then((function(){return t.put({_id:a,value:{ok:!0,time:(new Date).getTime()}})})).then((function(){return t.get(a)})).then((function(e){return r=e})).then((function(){return t.remove(r)})).then((function(){return!0})).then((function(){return!!(r&&r.value&&r.value.ok)})).catch((function(){return!1}))},r.POUCHDB_LOCATION=void 0;var n=e("./pouch-db"),i=e("../../util"),o="rxdb-adapter-check";r.POUCHDB_LOCATION=o},{"../../util":58,"./pouch-db":33}],31:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.getCustomEventEmitterByPouch=h,r.addCustomEventsPluginToPouch=function(){if(l)return;l=!0;var e=a.default.prototype.bulkDocs,t=function(){var t=(0,o.default)(i.default.mark((function t(r,n,a){var s,f,l,d,b,v,m,y=this;return i.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(s=(0,u.now)(),f=p++,"function"==typeof n&&(a=n,n={}),n||(n={}),Array.isArray(r)?l=r:void 0===r?l=[]:(l=r.docs,r.hasOwnProperty("new_edits")&&(n.new_edits=r.new_edits)),0!==l.length){t.next=7;break}throw(0,c.newRxError)("SNH",{args:{body:r,options:n}});case 7:if(d=new Map,!n.hasOwnProperty("new_edits")||!1!==n.new_edits){t.next=18;break}return b=l.map((function(e){return e._id})),t.next=12,this.changes({live:!1,since:0,doc_ids:b,style:"all_docs"});case 12:return v=t.sent,t.next=15,Promise.all(v.results.map(function(){var e=(0,o.default)(i.default.mark((function e(t){var r;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,y.get(t.id,{rev:t.changes[0].rev,deleted:"ok",revs:!!n.set_new_edit_as_latest_revision,style:"all_docs"});case 2:return r=e.sent,e.abrupt("return",r);case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 15:t.sent.forEach((function(e){return d.set(e._id,e)})),n.set_new_edit_as_latest_revision&&l.forEach((function(e){var t=e._id,r=d.get(t);if(r){var n=e._rev.split("-"),i=parseInt(n[0],10),o=n[1];e._revisions={start:i,ids:r._revisions.ids},e._revisions.ids.unshift(o),delete r._revisions}}));case 18:return(m=(0,u.flatClone)(n)).isDeeper=!0,t.abrupt("return",e.call(this,l,m,(function(e,t){if(e){if(!a)throw e;a(e)}else{if(!n.isDeeper){var r=(0,u.now)(),i={emitId:f,writeDocs:l,writeOptions:n,writeResult:t,previousDocs:d,startTime:s,endTime:r};h(y).subject.next(i)}if(!a)return t;a(null,t)}})));case 21:case"end":return t.stop()}}),t,this)})));return function(e,r,n){return t.apply(this,arguments)}}();a.default.plugin({bulkDocs:t})},r.EVENT_EMITTER_BY_POUCH_INSTANCE=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("pouchdb-core")),s=e("rxjs"),u=e("../../util"),c=e("../../rx-error"),f=e("oblivious-set"),l=!1,d=new Map;function h(e){var t=[e.name,e.adapter].join("|"),r=d.get(t);return r||(r={subject:new s.Subject,obliviousSet:new f.ObliviousSet(6e4)},d.set(t,r)),r}r.EVENT_EMITTER_BY_POUCH_INSTANCE=d;var p=0},{"../../rx-error":48,"../../util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"oblivious-set":634,"pouchdb-core":655,rxjs:684}],32:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./pouch-db");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===n[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return n[e]}}))}));var i=e("./rx-storage-pouchdb");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===i[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return i[e]}}))}));var o=e("./adapter-check");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===o[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return o[e]}}))}));var a=e("./custom-events-plugin");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===a[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return a[e]}}))}))},{"./adapter-check":30,"./custom-events-plugin":31,"./pouch-db":33,"./rx-storage-pouchdb":34}],33:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.isLevelDown=function(e){if(!e||"function"!=typeof e.super_)throw(0,a.newRxError)("UT4",{adapter:e})},r.pouchReplicationFunction=function(e,t){var r=t.pull,n=void 0===r||r,i=t.push,o=void 0===i||i;if(n&&o)return e.sync.bind(e);if(!n&&o)return e.replicate.to.bind(e);if(n&&!o)return e.replicate.from.bind(e);if(!n&&!o)throw(0,a.newRxError)("UT3",{pull:n,push:o})},r.isInstanceOf=function(e){return e instanceof i.default},r.addPouchPlugin=u,r.PouchDB=void 0;var i=n(e("pouchdb-core")),o=n(e("pouchdb-find")),a=e("../../rx-error"),s=e("./custom-events-plugin");function u(e){if(e.rxdb)throw(0,a.newRxTypeError)("PL2",{plugin:e});"object"==typeof e&&e.default&&(e=e.default),i.default.plugin(e)}u(o.default),(0,s.addCustomEventsPluginToPouch)();var c=i.default;r.PouchDB=c},{"../../rx-error":48,"./custom-events-plugin":31,"@babel/runtime/helpers/interopRequireDefault":67,"pouchdb-core":655,"pouchdb-find":658}],34:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.writeAttachmentsToAttachments=_,r.checkPouchAdapter=S,r.pouchHash=x,r.pouchSwapIdToPrimary=O,r.pouchDocumentDataToRxDocumentData=j,r.rxDocumentDataToPouchDocumentData=E,r.pouchSwapPrimaryToId=M,r.pouchStripLocalFlagFromPrimary=k,r.getEventKey=A,r.pouchChangeRowToChangeEvent=P,r.pouchChangeRowToChangeStreamEvent=function(e,t){var r=t.doc;if(!r)throw(0,f.newRxError)("SNH",{args:{pouchRow:t}});var n=(0,u.getHeightOfRevision)(r._rev);if(t.deleted){var i=(0,u.flatClone)(j(e,t.doc));return delete i._deleted,{sequence:t.seq,id:t.id,operation:"DELETE",doc:null,previous:i}}return 1===n?{sequence:t.seq,id:t.id,operation:"INSERT",doc:j(e,t.doc),previous:null}:{sequence:t.seq,id:t.id,operation:"UPDATE",doc:j(e,t.doc),previous:"UNKNOWN"}},r.primarySwapPouchDbQuerySelector=R,r.createIndexesOnPouch=C,r.getPouchLocation=D,r.getRxStoragePouch=function(e,t){if(!e)throw new Error("adapter missing");return new g(e,t)},r.RxStoragePouch=r.RxStorageInstancePouch=r.RxStorageKeyObjectInstancePouch=r.OPEN_POUCHDB_STORAGE_INSTANCES=r.POUCHDB_DESIGN_PREFIX=r.POUCHDB_LOCAL_PREFIX=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=e("pouchdb-selector-core"),s=e("pouchdb-md5"),u=e("../../util"),c=e("./pouch-db"),f=e("../../rx-error"),l=e("rxjs"),d=e("../../rx-schema-helper"),h=e("./custom-events-plugin"),p="_local/";r.POUCHDB_LOCAL_PREFIX=p;var b="_design/";r.POUCHDB_DESIGN_PREFIX=b;var v=new Set;r.OPEN_POUCHDB_STORAGE_INSTANCES=v;var m=function(){function e(e,t,r,n){this.changes$=new l.Subject,this.databaseName=e,this.collectionName=t,this.internals=r,this.options=n,v.add(this)}var t=e.prototype;return t.close=function(){return v.delete(this),Promise.resolve()},t.remove=function(){var e=(0,o.default)(i.default.mark((function e(){return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.internals.pouch.destroy();case 2:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}(),t.bulkWrite=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a,s,c,f=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Map,n=t.map((function(e){r.set(e.document._id,e);var t=(0,u.flatClone)(e.document);return t._id=p+t._id,e.previous&&(t._rev=e.previous._rev),t})),o=(0,u.now)(),e.next=5,this.internals.pouch.bulkDocs(n);case 5:return a=e.sent,s=(0,u.now)(),c={success:new Map,error:new Map},a.forEach((function(e){e.id=k(e.id);var t=(0,u.getFromMapOrThrow)(r,e.id);if(e.error){var n={isError:!0,status:409,documentId:e.id,writeRow:t};c.error.set(e.id,n)}else{var i,a=(0,u.flatClone)(t.document);if(a._rev=e.rev,a._attachments={},c.success.set(e.id,a),t.previous)if(t.document._deleted){var l=(0,u.flatClone)(t.previous);l._rev=e.rev,i={operation:"DELETE",doc:null,id:e.id,previous:l}}else i={operation:"UPDATE",doc:a,id:e.id,previous:t.previous};else i={operation:"INSERT",doc:a,id:e.id,previous:null};if(!t.document._deleted||t.previous&&!t.previous._deleted){var d="DELETE"===i.operation?i.previous:i.doc,h={eventId:A(!0,d._id,d._rev?d._rev:""),documentId:e.id,change:i,startTime:o,endTime:s};f.changes$.next(h)}else;}})),e.abrupt("return",c);case 10:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.findLocalDocumentsById=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Map,e.next=3,Promise.all(t.map(function(){var e=(0,o.default)(i.default.mark((function e(t){var o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=p+t,e.prev=1,e.next=4,n.internals.pouch.get(o);case 4:(a=e.sent)._id=t,r.set(t,a),e.next=11;break;case 9:e.prev=9,e.t0=e.catch(1);case 11:case"end":return e.stop()}}),e,null,[[1,9]])})));return function(t){return e.apply(this,arguments)}}()));case 3:return e.abrupt("return",r);case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),t.changeStream=function(){return this.changes$.asObservable()},e}();r.RxStorageKeyObjectInstancePouch=m;var y=function(){function e(e,t,r,n,a){var s=this;this.changes$=new l.Subject,this.subs=[],this.databaseName=e,this.collectionName=t,this.schema=r,this.internals=n,this.options=a,v.add(this);var c=(0,h.getCustomEventEmitterByPouch)(this.internals.pouch);this.emittedEventIds=c.obliviousSet;var d=c.subject.subscribe(function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.writeOptions.hasOwnProperty("new_edits")||t.writeOptions.new_edits){e.next=4;break}return e.next=3,Promise.all(t.writeDocs.map(function(){var e=(0,o.default)(i.default.mark((function e(r){var n,o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r._id,r=j(s.schema.primaryKey,r),e.next=4,_(r._attachments);case 4:if(r._attachments=e.sent,(o=t.previousDocs.get(n))&&(o=j(s.schema.primaryKey,o)),!(o&&(0,u.getHeightOfRevision)(o._rev)>(0,u.getHeightOfRevision)(r._rev))){e.next=9;break}return e.abrupt("return");case 9:if(o||!r._deleted){e.next=11;break}return e.abrupt("return");case 11:if(!(o&&o._deleted&&r._deleted)){e.next=13;break}return e.abrupt("return");case 13:if(o||r._deleted){e.next=17;break}a={operation:"INSERT",doc:r,id:n,previous:null},e.next=27;break;case 17:if(!r._deleted||!o||o._deleted){e.next=22;break}o._rev=r._rev,a={operation:"DELETE",doc:null,id:n,previous:o},e.next=27;break;case 22:if(!o){e.next=26;break}a={operation:"UPDATE",doc:r,id:n,previous:o},e.next=27;break;case 26:throw(0,f.newRxError)("SNH",{args:{writeDoc:r}});case 27:s.addEventToChangeStream(a,t.startTime,t.endTime);case 28:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 3:return e.abrupt("return");case 4:if(t.writeOptions.custom){e.next=10;break}return r=new Map,t.writeDocs.forEach((function(e){return r.set(e._id,e)})),e.next=9,Promise.all(t.writeResult.map(function(){var e=(0,o.default)(i.default.mark((function e(t){var n,o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(n=t.id).startsWith(b)&&!n.startsWith(p)){e.next=3;break}return e.abrupt("return");case 3:return o=(0,u.getFromMapOrThrow)(r,t.id),e.next=6,_(o._attachments);case 6:o._attachments=e.sent,a=P(s.schema.primaryKey,o),s.addEventToChangeStream(a);case 9:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 9:return e.abrupt("return");case 10:return n=t.writeOptions.custom.writeRowById,e.next=13,Promise.all(t.writeResult.map(function(){var e=(0,o.default)(i.default.mark((function e(r){var o,a,c,f,l;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.error){e.next=2;break}return e.abrupt("return");case 2:return o=r.id,a=(0,u.getFromMapOrThrow)(n,o),c=j(s.schema.primaryKey,a.document),e.next=7,_(c._attachments);case 7:if(c._attachments=e.sent,c._rev=r.rev,a.previous){e.next=13;break}f={operation:"INSERT",doc:c,id:o,previous:null},e.next=23;break;case 13:if(!a.document._deleted){e.next=22;break}return l=j(s.schema.primaryKey,a.previous),e.next=17,_(l._attachments);case 17:l._attachments=e.sent,l._rev=r.rev,f={operation:"DELETE",doc:null,id:r.id,previous:l},e.next=23;break;case 22:f={operation:"UPDATE",doc:c,id:r.id,previous:a.previous};case 23:(!a.document._deleted||a.previous&&!a.previous._deleted)&&s.addEventToChangeStream(f,t.startTime,t.endTime);case 24:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 13:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}());this.subs.push(d)}var t=e.prototype;return t.addEventToChangeStream=function(e,t,r){var n="DELETE"===e.operation?e.previous:e.doc,i=n[this.schema.primaryKey],o=A(!1,i,n._rev);if(!this.emittedEventIds.has(o)){this.emittedEventIds.add(o);var a={eventId:o,documentId:i,change:e,startTime:t,endTime:r};this.changes$.next(a)}},t.close=function(){return this.subs.forEach((function(e){return e.unsubscribe()})),v.delete(this),Promise.resolve()},t.remove=function(){var e=(0,o.default)(i.default.mark((function e(){return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.internals.pouch.destroy();case 2:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}(),t.getSortComparator=function(e){var t,r=this.schema.primaryKey,n=e.sort?e.sort:[(t={},t[r]="asc",t)],i=(0,a.massageSelector)(e.selector),o=Object.keys(e.selector);return function(e,t){var s=[e,t].map((function(e){var t=(0,u.flatClone)(e),n=t[r];return delete t[r],t._id=n,{doc:t}}));return(0,a.filterInMemoryFields)(s,{selector:i,sort:n},o)[0].doc._id===s[0].doc._id?-1:1}},t.getQueryMatcher=function(e){var t=this.schema.primaryKey,r=(0,a.massageSelector)(e.selector);return function(n){var i={doc:M(t,n)},o=(0,a.filterInMemoryFields)([i],{selector:r},Object.keys(e.selector));return o&&1===o.length}},t.prepareQuery=function(e){var t=this,r=this.schema.primaryKey,n=e;if(n.sort&&n.sort.forEach((function(e){var r=Object.keys(e)[0],i=["$gt","$gte","$lt","$lte"];if(!(n.selector[r]&&Object.keys(n.selector[r]).some((function(e){return i.includes(e)}))||!1)){var o=(0,d.getSchemaByObjectPath)(t.schema,r);if(!o)throw(0,f.newRxError)("QU5",{key:r});switch(n.selector[r]||(n.selector[r]={}),o.type){case"number":case"integer":n.selector[r].$gt=-1e28;break;case"string":"string"!=typeof n.selector[r]&&(n.selector[r].$gt="");break;default:n.selector[r].$gt=null}}})),n.selector[r]&&n.selector[r].$regex)throw(0,f.newRxError)("QU4",{path:r,query:e});if(n.sort){var i=n.sort.map((function(e){var t,n=Object.keys(e)[0],i=Object.values(e)[0];return(t={})[n===r?"_id":n]=i,t}));n.sort=i}return Object.entries(n.selector).forEach((function(e){var t=e[0],r=e[1];"object"!=typeof r||null===r||Array.isArray(r)||0!==Object.keys(r).length||delete n.selector[t]})),n.selector=R(n.selector,r),n},t.bulkAddRevisions=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.map((function(e){return M(n.schema.primaryKey,e)})),e.next=3,this.internals.pouch.bulkDocs(r,{new_edits:!1,set_new_edit_as_latest_revision:!0});case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.bulkWrite=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,a,s,c;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.schema.primaryKey,n=new Map,a=t.map((function(e){var t=e.document[r];n.set(t,e);var i=E(r,e.document);return e.previous&&(i._rev=e.previous._rev),i})),e.next=5,this.internals.pouch.bulkDocs(a,{custom:{writeRowById:n}});case 5:return s=e.sent,c={success:new Map,error:new Map},e.next=9,Promise.all(s.map(function(){var e=(0,o.default)(i.default.mark((function e(t){var o,a,s;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=(0,u.getFromMapOrThrow)(n,t.id),!t.error){e.next=6;break}a={isError:!0,status:409,documentId:t.id,writeRow:o},c.error.set(t.id,a),e.next=18;break;case 6:if(s=(0,u.flatClone)(o.document),(s=O(r,s))._rev=t.rev,s._attachments={},o.document._attachments){e.next=14;break}o.document._attachments={},e.next=17;break;case 14:return e.next=16,_(o.document._attachments);case 16:s._attachments=e.sent;case 17:c.success.set(t.id,s);case 18:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 9:return e.next=11,(0,u.promiseWait)(0).then((function(){return(0,u.promiseWait)(0)}));case 11:return e.abrupt("return",c);case 12:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.query=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.schema.primaryKey,e.next=3,this.internals.pouch.find(t);case 3:return n=e.sent,o={documents:n.docs.map((function(e){return j(r,e)}))},e.abrupt("return",o);case 6:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.getAttachmentData=function(){var e=(0,o.default)(i.default.mark((function e(t,r){var n;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.internals.pouch.getAttachment(t,r);case 2:return n=e.sent,e.abrupt("return",n);case 4:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.findDocumentsById=function(){var e=(0,o.default)(i.default.mark((function e(t,r){var n,a,s,u,c,f=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.schema.primaryKey,!r){e.next=9;break}return e.next=4,this.internals.pouch.changes({live:!1,since:0,doc_ids:t,style:"all_docs"});case 4:return a=e.sent,s=new Map,e.next=8,Promise.all(a.results.map(function(){var e=(0,o.default)(i.default.mark((function e(t){var r,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,f.internals.pouch.get(t.id,{rev:t.changes[0].rev,deleted:"ok",style:"all_docs"});case 2:r=e.sent,o=j(n,r),s.set(t.id,o);case 5:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 8:return e.abrupt("return",s);case 9:return e.next=11,this.internals.pouch.allDocs({include_docs:!0,keys:t});case 11:return u=e.sent,c=new Map,u.rows.filter((function(e){return!!e.doc})).forEach((function(e){var t=e.doc;t=j(n,t),c.set(e.id,t)})),e.abrupt("return",c);case 15:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.changeStream=function(){return this.changes$.asObservable()},t.getChangedDocuments=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={live:!1,limit:t.limit,include_docs:!1,since:t.startSequence,descending:"desc"===t.order},e.next=3,this.internals.pouch.changes(r);case 3:return n=e.sent,o=n.results.filter((function(e){return!e.id.startsWith(b)})).map((function(e){return{id:e.id,sequence:e.seq}})),a=n.last_seq,e.abrupt("return",{changedDocuments:o,lastSequence:a});case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e}();r.RxStorageInstancePouch=y;var g=function(){function e(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.name="pouchdb",this.adapter=e,this.pouchSettings=t,S(e)}var t=e.prototype;return t.hash=function(e){return x(e)},t.createPouch=function(){var e=(0,o.default)(i.default.mark((function e(t,r){var n,o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={location:t,adapter:(0,u.adapterObject)(this.adapter),settings:r},o=Object.assign({},n.adapter,this.pouchSettings,n.settings),a=new c.PouchDB(n.location,o),e.abrupt("return",a);case 4:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.createStorageInstance=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=D(t.databaseName,t.collectionName,t.schema.version),e.next=3,this.createPouch(r,t.options);case 3:return n=e.sent,e.next=6,C(n,t.schema);case 6:return e.abrupt("return",new y(t.databaseName,t.collectionName,t.schema,{pouch:n},t.options));case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.createKeyObjectStorageInstance=function(){var e=(0,o.default)(i.default.mark((function e(t,r,n){var o,a,s;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(o=(0,u.flatClone)(n)).auto_compaction=!1,o.revs_limit=1,a=D(t,r,0),e.next=6,this.createPouch(a,n);case 6:return s=e.sent,e.abrupt("return",new m(t,r,{pouch:s},n));case 8:case"end":return e.stop()}}),e,this)})));return function(t,r,n){return e.apply(this,arguments)}}(),e}();function _(e){return w.apply(this,arguments)}function w(){return(w=(0,o.default)(i.default.mark((function e(t){var r;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}return e.abrupt("return",{});case 2:return r={},e.next=5,Promise.all(Object.entries(t).map(function(){var e=(0,o.default)(i.default.mark((function e(t){var n,o,a,s,c,l;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t[0],(o=t[1]).type){e.next=3;break}throw(0,f.newRxError)("SNH",{args:o});case 3:if(!o.data){e.next=15;break}return a=o,e.next=7,x(a.data);case 7:return s=e.sent,e.next=10,u.blobBufferUtil.toString(a.data);case 10:c=e.sent,l=c.length,r[n]={digest:s,length:l,type:a.type},e.next=16;break;case 15:r[n]=o;case 16:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 5:return e.abrupt("return",r);case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function S(e){if("string"==typeof e){if(!c.PouchDB.adapters||!c.PouchDB.adapters[e])throw(0,f.newRxError)("DB9",{adapter:e})}else if((0,c.isLevelDown)(e),!c.PouchDB.adapters||!c.PouchDB.adapters.leveldb)throw(0,f.newRxError)("DB10",{adapter:e})}function x(e){return new Promise((function(t){(0,s.binaryMd5)(e,(function(e){t("md5-"+e)}))}))}function O(e,t){return"_id"===e||t[e]||((t=(0,u.flatClone)(t))[e]=t._id,delete t._id),t}function j(e,t){var r=O(e,t);return delete(r=(0,u.flatClone)(r))._revisions,r._attachments={},t._attachments&&Object.entries(t._attachments).forEach((function(e){var t=e[0],n=e[1];n.data?r._attachments[t]={data:n.data,type:n.type}:r._attachments[t]={digest:n.digest,type:n.type?n.type:n.content_type,length:n.length}})),r}function E(e,t){var r=M(e,t);return(r=(0,u.flatClone)(r))._attachments={},t._attachments&&Object.entries(t._attachments).forEach((function(e){var t=e[0],n=e[1];n.data?r._attachments[t]={data:n.data,content_type:n.type}:r._attachments[t]={digest:n.digest,content_type:n.type,length:n.length,stub:!0}})),r}function M(e,t){if("_id"===e)return t;var r={};return Object.entries(t).forEach((function(t){var n=t[0]===e?"_id":t[0];r[n]=t[1]})),r}function k(e){return e.substring(p.length)}function A(e,t,r){if(!t)throw new Error("primary missing !!");return(e?"local":"non-local")+"|"+t+"|"+r}function P(e,t){if(!t)throw(0,f.newRxError)("SNH",{args:{pouchDoc:t}});var r=t._id,n=j(e,t),i=(0,u.getHeightOfRevision)(n._rev);return t._deleted?{operation:"DELETE",id:r,doc:null,previous:n}:1===i?{operation:"INSERT",id:r,doc:n,previous:null}:{operation:"UPDATE",id:r,doc:n,previous:"UNKNOWN"}}function R(e,t){if("_id"===t)return e;if(Array.isArray(e))return e.map((function(e){return R(e,t)}));if("object"==typeof e){var r={};return Object.entries(e).forEach((function(e){var n=e[0],i=e[1];n===t?r._id=i:n.startsWith("$")?r[n]=R(i,t):r[n]=i})),r}return e}function C(e,t){return I.apply(this,arguments)}function I(){return(I=(0,o.default)(i.default.mark((function e(t,r){var n,a,s;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r.indexes){e.next=2;break}return e.abrupt("return");case 2:return n=r.primaryKey,e.next=5,t.getIndexes();case 5:return a=e.sent,s=new Set(a.indexes.map((function(e){return e.name}))),e.next=9,Promise.all(r.indexes.map(function(){var e=(0,o.default)(i.default.mark((function e(r){var o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=(o=Array.isArray(r)?r:[r]).map((function(e){return e===n?"_id":e})),a="idx-rxdb-index-"+o.join(","),!s.has(a)){e.next=5;break}return e.abrupt("return");case 5:return e.abrupt("return",t.createIndex({name:a,ddoc:a,index:{fields:o}}));case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function D(e,t,r){var n=e+"-rxdb-"+r+"-";if(t.includes("/")){var i=t.split("/"),o=i.pop(),a=i.join("/");return a+="/"+n+o}return n+t}r.RxStoragePouch=g},{"../../rx-error":48,"../../rx-schema-helper":50,"../../util":58,"./custom-events-plugin":31,"./pouch-db":33,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"pouchdb-md5":662,"pouchdb-selector-core":665,rxjs:684}],35:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={runBuildingStep:!0,applyBuildingStep:!0,RxDBQueryBuilderPlugin:!0};r.runBuildingStep=s,r.applyBuildingStep=u,r.RxDBQueryBuilderPlugin=void 0;var i=e("./mquery/nosql-query-builder");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===i[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return i[e]}}))}));var o=e("../../rx-query"),a=e("../../util");function s(e,t,r){var n=(0,i.createQueryBuilder)((0,a.clone)(e.mangoQuery));e.other.queryBuilderPath&&(n._path=e.other.queryBuilderPath),n[t](r);var s=n.toJSON(),u=new o.RxQueryBase(e.op,s.query,e.collection);return s.path&&(u.other.queryBuilderPath=s.path),(0,o.tunnelQueryCache)(u)}function u(e,t){e[t]=function(e){return s(this,t,e)}}var c={name:"query-builder",rxdb:!0,prototypes:{RxQuery:function(e){["where","equals","eq","or","nor","and","mod","exists","elemMatch","sort"].forEach((function(t){u(e,t)})),i.OTHER_MANGO_ATTRIBUTES.forEach((function(t){u(e,t)})),i.OTHER_MANGO_OPERATORS.forEach((function(t){u(e,t)}))}}};r.RxDBQueryBuilderPlugin=c},{"../../rx-query":49,"../../util":58,"./mquery/nosql-query-builder":37}],36:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.merge=function e(t,r){Object.keys(r).forEach((function(o){n.includes(o)||(void 0===t[o]?t[o]=r[o]:i(r[o])?e(t[o],r[o]):t[o]=r[o])}))},r.isObject=i;var n=["__proto__","constructor","prototype"];function i(e){return"[object Object]"===e.toString()}},{}],37:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.mQuerySortToRxDBSort=a,r.canMerge=l,r.createQueryBuilder=function(e){return new o(e)},r.OTHER_MANGO_OPERATORS=r.OTHER_MANGO_ATTRIBUTES=r.NoSqlQueryBuilderClass=void 0;var n=e("./mquery-utils"),i=e("../../../rx-error"),o=function(){function e(e){if(this.options={},this._conditions={},this._fields={},e){var t=this;e.selector&&t.find(e.selector),e.limit&&t.limit(e.limit),e.skip&&t.skip(e.skip),e.sort&&e.sort.forEach((function(e){return t.sort(e)}))}}var t=e.prototype;return t.where=function(e,t){if(!arguments.length)return this;var r=typeof arguments[0];if("string"===r)return this._path=arguments[0],2===arguments.length&&(this._conditions[this._path]=arguments[1]),this;if("object"===r&&!Array.isArray(arguments[0]))return this.merge(arguments[0]);throw(0,i.newRxTypeError)("MQ1",{path:arguments[0]})},t.equals=function(e){this._ensurePath("equals");var t=this._path;return this._conditions[t]=e,this},t.eq=function(e){this._ensurePath("eq");var t=this._path;return this._conditions[t]=e,this},t.or=function(e){var t=this._conditions.$or||(this._conditions.$or=[]);return Array.isArray(e)||(e=[e]),t.push.apply(t,e),this},t.nor=function(e){var t=this._conditions.$nor||(this._conditions.$nor=[]);return Array.isArray(e)||(e=[e]),t.push.apply(t,e),this},t.and=function(e){var t=this._conditions.$and||(this._conditions.$and=[]);return Array.isArray(e)||(e=[e]),t.push.apply(t,e),this},t.mod=function(e,t){var r,n;1===arguments.length?(this._ensurePath("mod"),r=arguments[0],n=this._path):2!==arguments.length||Array.isArray(arguments[1])?3===arguments.length?(r=arguments.slice(1),n=arguments[0]):(r=arguments[1],n=arguments[0]):(this._ensurePath("mod"),r=arguments.slice(),n=this._path);var i=this._conditions[n]||(this._conditions[n]={});return i.$mod=r,this},t.exists=function(e,t){var r,n;0===arguments.length?(this._ensurePath("exists"),r=this._path,n=!0):1===arguments.length?"boolean"==typeof arguments[0]?(this._ensurePath("exists"),r=this._path,n=arguments[0]):(r=arguments[0],n=!0):2===arguments.length&&(r=arguments[0],n=arguments[1]);var i=this._conditions[r]||(this._conditions[r]={});return i.$exists=n,this},t.elemMatch=function(t,r){if(null===arguments[0])throw(0,i.newRxTypeError)("MQ2");var o,a,s;if("function"==typeof arguments[0])this._ensurePath("elemMatch"),a=this._path,o=arguments[0];else if((0,n.isObject)(arguments[0]))this._ensurePath("elemMatch"),a=this._path,s=arguments[0];else if("function"==typeof arguments[1])a=arguments[0],o=arguments[1];else{if(!arguments[1]||!(0,n.isObject)(arguments[1]))throw(0,i.newRxTypeError)("MQ2");a=arguments[0],s=arguments[1]}o&&(o(s=new e),s=s._conditions);var u=this._conditions[a]||(this._conditions[a]={});return u.$elemMatch=s,this},t.sort=function(e){var t,r=this;if(!e)return this;var o=typeof e;if(Array.isArray(e)){t=e.length;for(var a=0;a0||(0===l._lastEnsureEqual&&l._creationTime2&&void 0!==h[2]&&h[2],o={previous:r.previous?l(t,(0,a.flatClone)(r.previous)):void 0,document:l(t,(0,a.flatClone)(r.document))};case 2:return e.prev=3,e.next=6,t.database.lockedRun((function(){return(0,c.writeSingle)(t.storageInstance,o)}));case 6:return u=e.sent,f=d(t,u),e.abrupt("return",f);case 11:return e.prev=11,e.t0=e.catch(3),e.delegateYield(i.default.mark((function a(){var u,f,l;return i.default.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:if(u=e.t0,f=u.documentId,!n||409!==u.status){i.next=11;break}return i.next=5,t.database.lockedRun((function(){return(0,c.getSingleDocument)(t.storageInstance,f)}));case 5:if(l=i.sent){i.next=8;break}throw(0,s.newRxError)("SNH");case 8:o.previous=l,i.next=16;break;case 11:if(409!==u.status){i.next=15;break}throw(0,s.newRxError)("COL19",{id:f,pouchDbError:u,data:r});case 15:throw u;case 16:case"end":return i.stop()}}),a)}))(),"t1",14);case 14:e.next=2;break;case 16:case"end":return e.stop()}}),e,null,[[3,11]])})))).apply(this,arguments)}function l(e,t){t=e._crypter.encrypt(t);var r={collection:e,doc:t};return(0,u.runPluginHooks)("preWriteToStorageInstance",r),r.doc}function d(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n={collection:e,doc:t};return(0,u.runPluginHooks)("postReadFromInstance",n),r?n.doc:e._crypter.decrypt(n.doc)}},{"./hooks":7,"./rx-error":48,"./rx-storage-helper":52,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72}],44:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.createRxCollection=function(e,t){var r=e.database,n=e.name,i=e.schema,o=e.instanceCreationOptions,a=void 0===o?{}:o,s=e.migrationStrategies,u=void 0===s?{}:s,c=e.autoMigrate,f=void 0===c||c,h=e.statics,p=void 0===h?{}:h,v=e.methods,y=void 0===v?{}:v,g=e.attachments,_=void 0===g?{}:g,S=e.options,x=void 0===S?{}:S,O=e.cacheReplacementPolicy,E=void 0===O?b.defaultCacheReplacementPolicy:O;(0,w.validateDatabaseName)(n),(0,l.isInstanceOf)(i)||(i=(0,l.createRxSchema)(i));Object.keys(y).filter((function(e){return i.topLevelFields.includes(e)})).forEach((function(e){throw(0,d.newRxError)("COL18",{funName:e})}));var M=new j(r,n,i,a,u,y,_,x,E,p);return M.prepare(t).then((function(){Object.entries(p).forEach((function(e){var t=e[0],r=e[1];Object.defineProperty(M,t,{get:function(){return r.bind(M)}})}));var e=Promise.resolve();return f&&0!==M.schema.version&&(e=M.migratePromise()),e})).then((function(){return(0,m.runPluginHooks)("createRxCollection",M),M}))},r.isRxCollection=function(e){return e instanceof j},r.RxCollectionBase=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("@babel/runtime/helpers/createClass")),s=e("rxjs/operators"),u=e("./util"),c=e("./rx-collection-helper"),f=e("./rx-query"),l=e("./rx-schema"),d=e("./rx-error"),h=e("./crypter"),p=e("./doc-cache"),b=e("./query-cache"),v=e("./change-event-buffer"),m=e("./hooks"),y=e("./rx-document"),g=e("./rx-document-prototype-merge"),_=e("./rx-storage-helper"),w=e("./plugins/dev-mode/check-names"),S=["pre","post"],x=["insert","save","remove","create"],O=!1,j=function(){function e(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:{},s=arguments.length>7&&void 0!==arguments[7]?arguments[7]:{},u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:b.defaultCacheReplacementPolicy,c=arguments.length>9&&void 0!==arguments[9]?arguments[9]:{};this._isInMemory=!1,this.destroyed=!1,this._atomicUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._repStates=new Set,this.storageInstance={},this.localDocumentsStore={},this._docCache=(0,p.createDocCache)(),this._queryCache=(0,b.createQueryCache)(),this._crypter={},this._observable$={},this._changeEventBuffer={},this.database=e,this.name=t,this.schema=r,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=o,this.attachments=a,this.options=s,this.cacheReplacementPolicy=u,this.statics=c,E(this.asRxCollection)}var t=e.prototype;return t.prepare=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a,u,c,f=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={databaseName:this.database.name,collectionName:this.name,schema:this.schema.jsonSchema,options:this.instanceCreationOptions},(0,m.runPluginHooks)("preCreateRxStorageInstance",r),e.next=4,Promise.all([this.database.storage.createStorageInstance(r),this.database.storage.createKeyObjectStorageInstance(this.database.name,this.name+"-local",this.instanceCreationOptions)]);case 4:n=e.sent,o=n[0],a=n[1],this.storageInstance=o,this.localDocumentsStore=a,this._crypter=(0,h.createCrypter)(this.database.password,this.schema),this._observable$=this.database.$.pipe((0,s.filter)((function(e){return e.collectionName===f.name}))),this._changeEventBuffer=(0,v.createChangeEventBuffer)(this.asRxCollection),u=o.changeStream().pipe((0,s.map)((function(e){return(0,_.storageChangeEventToRxChangeEvent)(!1,e,f.database,f)}))).subscribe((function(e){f.$emit(e)})),this._subs.push(u),c=this.localDocumentsStore.changeStream().pipe((0,s.map)((function(e){return(0,_.storageChangeEventToRxChangeEvent)(!0,e,f.database,f)}))).subscribe((function(e){return f.$emit(e)})),this._subs.push(c),this._subs.push(this._observable$.pipe((0,s.filter)((function(e){return!e.isLocal}))).subscribe((function(e){var t=f._docCache.get(e.documentId);t&&t._handleChangeEvent(e)})));case 17:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.migrationNeeded=function(){if(0===this.schema.version)return Promise.resolve(!1);throw(0,u.pluginMissing)("migration")},t.getDataMigrator=function(){throw(0,u.pluginMissing)("migration")},t.migrate=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this.getDataMigrator().migrate(e)},t.migratePromise=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this.getDataMigrator().migratePromise(e)},t._queryStorageInstance=function(){var e=(0,o.default)(i.default.mark((function e(t,r){var n,o,a,s,u=this,f=arguments;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=f.length>2&&void 0!==f[2]&&f[2],o=t.toJSON(),r&&(o.limit=r),e.next=5,this.database.lockedRun((function(){return u.storageInstance.query(o)}));case 5:return a=e.sent,s=a.documents.map((function(e){return(0,c._handleFromStorageInstance)(u,e,n)})),e.abrupt("return",s);case 8:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.$emit=function(e){return this.database.$emit(e)},t.insert=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=null,!(0,y.isRxDocument)(t)){e.next=6;break}if((r=t)._isTemporary){e.next=5;break}throw(0,d.newRxError)("COL1",{data:t});case 5:t=r.toJSON();case 6:return n=(0,c.fillObjectDataBeforeInsert)(this,t),o=r,e.next=10,this._runHooks("pre","insert",n);case 10:return this.schema.validate(n),e.next=13,(0,c.writeToStorageInstance)(this,{document:n});case 13:return a=e.sent,r?r._dataSync$.next(a):o=(0,g.createRxDocument)(this,a),e.next=17,this._runHooks("post","insert",n,o);case 17:return e.abrupt("return",o);case 18:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.bulkInsert=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a,s,f,l,d=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.map((function(e){return(0,c.fillObjectDataBeforeInsert)(d,e)})),e.next=3,Promise.all(r.map((function(e){return d._runHooks("pre","insert",e).then((function(){return d.schema.validate(e),e}))})));case 3:return n=e.sent,o=n.map((function(e){return{document:(0,c._handleToStorageInstance)(d,e)}})),a=new Map,n.forEach((function(e){a.set(e[d.schema.primaryPath],e)})),e.next=9,this.database.lockedRun((function(){return d.storageInstance.bulkWrite(o)}));case 9:return s=e.sent,f=Array.from(s.success.entries()),l=f.map((function(e){var t=e[0],r=e[1],n=(0,u.getFromMapOrThrow)(a,t);return n._rev=r._rev,(0,g.createRxDocument)(d,n)})),e.next=14,Promise.all(l.map((function(e){return d._runHooks("post","insert",a.get(e.primary),e)})));case 14:return e.abrupt("return",{success:l,error:Array.from(s.error.values())});case 15:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.bulkRemove=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a,s,f,l,d=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.findByIds(t);case 2:return r=e.sent,n=[],o=new Map,Array.from(r.values()).forEach((function(e){var t=(0,u.clone)(e.toJSON(!0));n.push(t),o.set(e.primary,t)})),e.next=8,Promise.all(n.map((function(e){var t=e[d.schema.primaryPath];return d._runHooks("pre","remove",e,r.get(t))})));case 8:return a=n.map((function(e){var t=(0,u.flatClone)(e);return t._deleted=!0,{previous:(0,c._handleToStorageInstance)(d,e),document:(0,c._handleToStorageInstance)(d,t)}})),e.next=11,this.database.lockedRun((function(){return d.storageInstance.bulkWrite(a)}));case 11:return s=e.sent,f=Array.from(s.success.keys()),e.next=15,Promise.all(f.map((function(e){return d._runHooks("post","remove",o.get(e),r.get(e))})));case 15:return l=f.map((function(e){return r.get(e)})),e.abrupt("return",{success:l,error:Array.from(s.error.values())});case 17:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.upsert=function(e){var t=this,r=(0,u.flatClone)(e),n=r[this.schema.primaryPath];if(!n)throw(0,d.newRxError)("COL3",{primaryPath:this.schema.primaryPath,data:r});return this.findOne(n).exec().then((function(n){return n?(r._rev=n._rev,n.atomicUpdate((function(){return r})).then((function(){return n}))):t.insert(e)}))},t.atomicUpsert=function(e){var t,r=this,n=e[this.schema.primaryPath];if(!n)throw(0,d.newRxError)("COL4",{data:e});return t=(t=this._atomicUpsertQueues.has(n)?this._atomicUpsertQueues.get(n):Promise.resolve()).then((function(){return function(e,t,r){var n=e._docCache.get(t);if(n)return Promise.resolve({doc:n,inserted:!1});return e.findOne(t).exec().then((function(t){return t?{doc:t,inserted:!1}:e.insert(r).then((function(e){return{doc:e,inserted:!0}}))}))}(r,n,e)})).then((function(t){return t.inserted?t.doc:function(e,t){return e.atomicUpdate((function(e){return t._rev=e._rev,e._data=t,e._data})).then((function(){return e}))}(t.doc,e).then((function(){return(0,u.nextTick)()})).then((function(){return(0,u.nextTick)()})).then((function(){return(0,u.nextTick)()})).then((function(){return t.doc}))})),this._atomicUpsertQueues.set(n,t),t},t.find=function(e){if("string"==typeof e)throw(0,d.newRxError)("COL5",{queryObj:e});return e||(e=(0,f._getDefaultQuery)(this)),(0,f.createRxQuery)("find",e,this)},t.findOne=function(e){var t;if("string"==typeof e){var r;t=(0,f.createRxQuery)("findOne",{selector:(r={},r[this.schema.primaryPath]=e,r)},this)}else{if(e||(e=(0,f._getDefaultQuery)(this)),e.limit)throw(0,d.newRxError)("QU6");t=(0,f.createRxQuery)("findOne",e,this)}if("number"==typeof e||Array.isArray(e))throw(0,d.newRxTypeError)("COL6",{queryObj:e});return t},t.findByIds=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=new Map,n=[],t.forEach((function(e){var t=a._docCache.get(e);t?r.set(e,t):n.push(e)})),!(n.length>0)){e.next=8;break}return e.next=6,this.storageInstance.findDocumentsById(n,!1);case 6:o=e.sent,Array.from(o.values()).forEach((function(e){e=(0,c._handleFromStorageInstance)(a,e);var t=(0,g.createRxDocument)(a,e);r.set(t.primary,t)}));case 8:return e.abrupt("return",r);case 9:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.findByIds$=function(e){var t=this,r=null,n=-1,a=this.findByIds(e).then((function(e){n=t._changeEventBuffer.counter,r=e}));return this.$.pipe((0,s.startWith)(null),(0,s.mergeMap)((function(e){return a.then((function(){return e}))})),(0,s.mergeMap)(function(){var a=(0,o.default)(i.default.mark((function o(a){var s,c,f;return i.default.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:if(s=(0,u.ensureNotFalsy)(r),null!==(c=t._changeEventBuffer.getFrom(n+1))){i.next=10;break}return i.next=5,t.findByIds(e);case 5:f=i.sent,n=t._changeEventBuffer.counter,Array.from(f.entries()).forEach((function(e){var t=e[0],r=e[1];return s.set(t,r)})),i.next=11;break;case 10:c.filter((function(t){return e.includes(t.documentId)})).forEach((function(e){var r=e.operation;"INSERT"===r||"UPDATE"===r?s.set(e.documentId,t._docCache.get(e.documentId)):s.delete(e.documentId)}));case 11:return i.abrupt("return",s);case 12:case"end":return i.stop()}}),o)})));return function(e){return a.apply(this,arguments)}}()),(0,s.filter)((function(e){return!!e})),(0,s.shareReplay)({bufferSize:1,refCount:!0}))},t.exportJSON=function(){throw(0,u.pluginMissing)("json-dump")},t.importJSON=function(e){throw(0,u.pluginMissing)("json-dump")},t.syncCouchDB=function(e){throw(0,u.pluginMissing)("replication")},t.syncGraphQL=function(e){throw(0,u.pluginMissing)("replication-graphql")},t.inMemory=function(){throw(0,u.pluginMissing)("in-memory")},t.addHook=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if("function"!=typeof r)throw(0,d.newRxTypeError)("COL7",{key:t,when:e});if(!S.includes(e))throw(0,d.newRxTypeError)("COL8",{key:t,when:e});if(!x.includes(t))throw(0,d.newRxError)("COL9",{key:t});if("post"===e&&"create"===t&&!0===n)throw(0,d.newRxError)("COL10",{when:e,key:t,parallel:n});var i=r.bind(this),o=n?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][o].push(i)},t.getHooks=function(e,t){try{return this.hooks[t][e]}catch(e){return{series:[],parallel:[]}}},t._runHooks=function(e,t,r,n){var i=this.getHooks(e,t);if(!i)return Promise.resolve();var o=i.series.map((function(e){return function(){return e(r,n)}}));return(0,u.promiseSeries)(o).then((function(){return Promise.all(i.parallel.map((function(e){return e(r,n)})))}))},t._runHooksSync=function(e,t,r,n){var i=this.getHooks(e,t);i&&i.series.forEach((function(e){return e(r,n)}))},t.newDocument=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e=this.schema.fillObjectWithDefaults(e);var t=(0,y.createWithConstructor)((0,g.getRxDocumentConstructor)(this),this,e);return t._isTemporary=!0,this._runHooksSync("post","create",e,t),t},t.destroy=function(){var e=this;return this.destroyed?Promise.resolve(!1):(this._onDestroyCall&&this._onDestroyCall(),this._subs.forEach((function(e){return e.unsubscribe()})),this._changeEventBuffer&&this._changeEventBuffer.destroy(),Array.from(this._repStates).forEach((function(e){return e.cancel()})),this.storageInstance.close().then((function(){return delete e.database.collections[e.name],e.destroyed=!0,(0,m.runAsyncPluginHooks)("postDestroyRxCollection",e).then((function(){return!0}))})))},t.remove=function(){return this.database.removeCollection(this.name)},(0,a.default)(e,[{key:"$",get:function(){return this._observable$}},{key:"insert$",get:function(){return this.$.pipe((0,s.filter)((function(e){return"INSERT"===e.operation})))}},{key:"update$",get:function(){return this.$.pipe((0,s.filter)((function(e){return"UPDATE"===e.operation})))}},{key:"remove$",get:function(){return this.$.pipe((0,s.filter)((function(e){return"DELETE"===e.operation})))}},{key:"onDestroy",get:function(){var e=this;return this._onDestroy||(this._onDestroy=new Promise((function(t){return e._onDestroyCall=t}))),this._onDestroy}},{key:"asRxCollection",get:function(){return this}}]),e}();function E(e){if(!O){O=!0;var t=Object.getPrototypeOf(e);x.forEach((function(e){S.map((function(r){var n=r+(0,u.ucfirst)(e);t[n]=function(t,n){return this.addHook(r,e,t,n)}}))}))}}r.RxCollectionBase=j},{"./change-event-buffer":2,"./crypter":4,"./doc-cache":5,"./hooks":7,"./plugins/dev-mode/check-names":13,"./query-cache":41,"./rx-collection-helper":43,"./rx-document":47,"./rx-document-prototype-merge":46,"./rx-error":48,"./rx-query":49,"./rx-schema":51,"./rx-storage-helper":52,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"rxjs/operators":908}],45:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r._ensureStorageTokenExists=x,r.writeToSocket=j,r._collectionNamePrimary=E,r._removeAllOfCollection=M,r.createRxDatabase=function(e){var t=e.storage,r=e.instanceCreationOptions,n=e.name,i=e.password,o=e.multiInstance,a=void 0===o||o,s=e.eventReduce,u=void 0!==s&&s,c=e.ignoreDuplicate,f=void 0!==c&&c,d=e.options,h=void 0===d?{}:d;(0,b.runPluginHooks)("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:n,password:i,multiInstance:a,eventReduce:u,ignoreDuplicate:f,options:h}),i&&p.overwritable.validatePassword(i);f||function(e){if(_.has(e))throw(0,l.newRxError)("DB8",{name:e,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(n);_.add(n);var v=new S(n,t,r,i,a,u,h);return function(e){return C.apply(this,arguments)}(v).then((function(){return(0,b.runAsyncPluginHooks)("createRxDatabase",v)})).then((function(){return v}))},r.removeRxDatabase=I,r.isRxDatabase=function(e){return e instanceof S},r.dbCount=function(){return w},r.RxDatabaseBase=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=n(e("@babel/runtime/helpers/createClass")),s=n(e("random-token")),u=e("custom-idle-queue"),c=e("broadcast-channel"),f=e("./util"),l=e("./rx-error"),d=e("./rx-schema"),h=e("./rx-change-event"),p=e("./overwritable"),b=e("./hooks"),v=e("rxjs"),m=e("./rx-collection"),y=e("./rx-storage-helper"),g=e("./rx-schema-helper"),_=new Set,w=0,S=function(){function e(e,t,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5],a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:{};this.internalStore={},this.localDocumentsStore={},this.idleQueue=new u.IdleQueue,this.token=(0,s.default)(10),this._subs=[],this.destroyed=!1,this.subject=new v.Subject,this.observable$=this.subject.asObservable(),this.name=e,this.storage=t,this.instanceCreationOptions=r,this.password=n,this.multiInstance=i,this.eventReduce=o,this.options=a,this.collections={},w++}var t=e.prototype;return t.dangerousRemoveCollectionInfo=function(){var e=(0,o.default)(i.default.mark((function e(){var t,r;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,y.getAllDocuments)(this.internalStore);case 2:return t=e.sent,r=t.map((function(e){var t=(0,f.flatClone)(e);return t._deleted=!0,{previous:e,document:t}})),e.next=6,this.internalStore.bulkWrite(r);case 6:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}(),t.$emit=function(e){this.subject.next(e),e.databaseToken===this.token&&j(this,e)},t.removeCollectionDoc=function(){var e=(0,o.default)(i.default.mark((function e(t,r){var n,o,a,s=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=E(t,r),e.next=3,(0,y.getSingleDocument)(this.internalStore,n);case 3:if(o=e.sent){e.next=6;break}throw(0,l.newRxError)("SNH");case 6:return(a=(0,f.flatClone)(o))._deleted=!0,e.next=10,this.lockedRun((function(){return s.internalStore.bulkWrite([{document:a,previous:o}])}));case 10:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.addCollections=function(){var e=(0,o.default)(i.default.mark((function e(t){var r,n,o,a,s,u,c=this;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.internalStore.findDocumentsById(Object.keys(t).map((function(e){return E(e,t[e].schema)})),!1);case 2:return r=e.sent,n={},Array.from(r.entries()).forEach((function(e){var t=e[0],r=e[1];n[t]=r})),o={},e.next=8,Promise.all(Object.entries(t).map((function(e){var r=e[0],i=e[1],a=r,s=n[E(r,t[a].schema)],u=(0,f.flatClone)(i);u.name=a;var h=(0,d.createRxSchema)(i.schema);if(o[a]=h.hash,u.schema=h,u.database=c,c.collections[r])throw(0,l.newRxError)("DB3",{name:r});if(s&&s.schemaHash!==o[a])throw(0,l.newRxError)("DB6",{name:r,previousSchemaHash:s.schemaHash,schemaHash:o[a]});var p=(0,f.flatClone)(i);return p.database=c,p.name=r,(0,b.runPluginHooks)("preCreateRxCollection",p),(0,m.createRxCollection)(u,!!s)})));case 8:if(a=e.sent,s=[],u={},a.forEach((function(e){var r=e.name;if(u[r]=e,e.schema.crypt&&!c.password)throw(0,l.newRxError)("DB7",{name:r});n[r]||s.push({document:{collectionName:E(r,t[r].schema),schemaHash:o[r],schema:e.schema.normalized,version:e.schema.version,_attachments:{}}}),c.collections[r]=e,c[r]||Object.defineProperty(c,r,{get:function(){return c.collections[r]}})})),!(s.length>0)){e.next=15;break}return e.next=15,this.internalStore.bulkWrite(s);case 15:return e.abrupt("return",u);case 16:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.removeCollection=function(e){var t=this;return this.collections[e]&&this.collections[e].destroy(),M(this,e).then((function(r){return Promise.all(r.map((function(r){return t.storage.createStorageInstance({databaseName:t.name,collectionName:e,schema:(0,g.getPseudoSchemaForVersion)(r,"collectionName"),options:t.instanceCreationOptions})})))})).then((function(e){return Promise.all(e.map((function(e){return t.lockedRun((function(){return e.remove()}))})))})).then((function(){}))},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(){throw(0,f.pluginMissing)("json-dump")},t.importJSON=function(e){throw(0,f.pluginMissing)("json-dump")},t.server=function(e){throw(0,f.pluginMissing)("server")},t.backup=function(e){throw(0,f.pluginMissing)("backup")},t.leaderElector=function(){throw(0,f.pluginMissing)("leader-election")},t.isLeader=function(){throw(0,f.pluginMissing)("leader-election")},t.waitForLeadership=function(){throw(0,f.pluginMissing)("leader-election")},t.migrationStates=function(){throw(0,f.pluginMissing)("migration")},t.destroy=function(){var e=this;return this.destroyed?Promise.resolve(!1):((0,b.runPluginHooks)("preDestroyRxDatabase",this),w--,this.destroyed=!0,this._subs.map((function(e){return e.unsubscribe()})),this.requestIdlePromise().then((function(){return Promise.all(Object.keys(e.collections).map((function(t){return e.collections[t]})).map((function(e){return e.destroy()})))})).then((function(){return e.internalStore.close?e.internalStore.close():null})).then((function(){return e.broadcastChannel?e.broadcastChannel.close():Promise.resolve()})).then((function(){return _.delete(e.name)})).then((function(){return!0})))},t.remove=function(){var e=this;return this.destroy().then((function(){return I(e.name,e.storage)}))},(0,a.default)(e,[{key:"$",get:function(){return this.observable$}}]),e}();function x(e){return O.apply(this,arguments)}function O(){return(O=(0,o.default)(i.default.mark((function e(t){var r,n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r="storageToken",e.next=3,(0,y.findLocalDocument)(t.localDocumentsStore,r);case 3:if(n=e.sent){e.next=11;break}return o=(0,s.default)(10),e.next=8,t.localDocumentsStore.bulkWrite([{document:{_id:r,value:o,_attachments:{}}}]);case 8:return e.abrupt("return",o);case 11:return e.abrupt("return",n.value);case 12:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function j(e,t){if(e.destroyed)return Promise.resolve(!1);if(e.multiInstance&&!(0,h.isRxChangeEventIntern)(t)&&e.broadcastChannel){var r={cE:t,storageToken:e.storageToken};return e.broadcastChannel.postMessage(r).then((function(){return!0}))}return Promise.resolve(!1)}function E(e,t){return e+"-"+t.version}function M(e,t){return k.apply(this,arguments)}function k(){return(k=(0,o.default)(i.default.mark((function e(t,r){var n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.lockedRun((function(){return(0,y.getAllDocuments)(t.internalStore)}));case 2:return n=e.sent,o=n.filter((function(e){return e.collectionName.split("-")[0]===r})),e.abrupt("return",Promise.all(o.map((function(e){var r=(0,f.flatClone)(e);return r._deleted=!0,t.lockedRun((function(){return(0,y.writeSingle)(t.internalStore,{previous:e,document:r})}))}))).then((function(){return o.map((function(e){return e.version}))})));case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function A(e){e.broadcastChannel=new c.BroadcastChannel("RxDB:"+e.name+":socket"),e.broadcastChannel$=new v.Subject,e.broadcastChannel.onmessage=function(t){if(t.storageToken===e.storageToken&&t.cE.databaseToken!==e.token){var r=t.cE;e.broadcastChannel$.next(r)}},e._subs.push(e.broadcastChannel$.subscribe((function(t){e.$emit(t)})))}function P(e,t,r){return R.apply(this,arguments)}function R(){return(R=(0,o.default)(i.default.mark((function e(t,r,n){var o,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.createStorageInstance({databaseName:r,collectionName:y.INTERNAL_STORAGE_NAME,schema:(0,g.getPseudoSchemaForVersion)(0,"collectionName"),options:n});case 2:return o=e.sent,e.next=5,t.createKeyObjectStorageInstance(r,"",n);case 5:return a=e.sent,e.abrupt("return",{internalStore:o,localDocumentsStore:a});case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function C(){return(C=(0,o.default)(i.default.mark((function e(t){var r,n;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,P(t.storage,t.name,t.instanceCreationOptions);case 2:return r=e.sent,t.internalStore=r.internalStore,t.localDocumentsStore=r.localDocumentsStore,n=t.localDocumentsStore.changeStream().subscribe((function(e){t.$emit((0,y.storageChangeEventToRxChangeEvent)(!0,e,t))})),t._subs.push(n),e.next=9,x(t);case 9:t.storageToken=e.sent,t.multiInstance&&A(t);case 11:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function I(e,t){return D.apply(this,arguments)}function D(){return(D=(0,o.default)(i.default.mark((function e(t,r){var n,a;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,P(r,t,{});case 2:return n=e.sent,e.next=5,(0,y.getAllDocuments)(n.internalStore);case 5:return a=e.sent,e.next=8,Promise.all(a.map((function(e){return e.collectionName})).map(function(){var e=(0,o.default)(i.default.mark((function e(n){var o,a,s,u;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=n.split("-"),a=o[0],s=parseInt(o[1],10),e.next=5,r.createStorageInstance({databaseName:t,collectionName:a,schema:(0,g.getPseudoSchemaForVersion)(s,"collectionName"),options:{}});case 5:return u=e.sent,e.abrupt("return",u.remove());case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 8:return e.abrupt("return",Promise.all([n.internalStore.remove(),n.localDocumentsStore.remove()]));case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}r.RxDatabaseBase=S},{"./hooks":7,"./overwritable":9,"./rx-change-event":42,"./rx-collection":44,"./rx-error":48,"./rx-schema":51,"./rx-schema-helper":50,"./rx-storage-helper":52,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"broadcast-channel":113,"custom-idle-queue":495,"random-token":675,rxjs:684}],46:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getDocumentPrototype=s,r.getRxDocumentConstructor=u,r.createRxDocument=c,r.createRxDocuments=function(e,t){return t.map((function(t){return c(e,t)}))},r.getDocumentOrmPrototype=f;var n=e("./rx-document"),i=e("./hooks"),o=new WeakMap,a=new WeakMap;function s(e){if(!o.has(e)){var t=e.schema.getDocumentPrototype(),r=f(e),i=n.basePrototype,a={};[t,r,i].forEach((function(e){Object.getOwnPropertyNames(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t),n=!0;(t.startsWith("_")||t.endsWith("_")||t.startsWith("$")||t.endsWith("$"))&&(n=!1),"function"==typeof r.value?Object.defineProperty(a,t,{get:function(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(a,t,r))}))})),o.set(e,a)}return o.get(e)}function u(e){if(!a.has(e)){var t=(0,n.createRxDocumentConstructor)(s(e));a.set(e,t)}return a.get(e)}function c(e,t){var r=t[e.schema.primaryPath],o=e._docCache.get(r);if(o)return o;var a=(0,n.createWithConstructor)(u(e),e,t);return e._docCache.set(r,a),e._runHooksSync("post","create",t,a),(0,i.runPluginHooks)("postCreateRxDocument",a),a}function f(e){var t={};return Object.entries(e.methods).forEach((function(e){var r=e[0],n=e[1];t[r]=n})),t}},{"./hooks":7,"./rx-document":47}],47:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.createRxDocumentConstructor=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m,t=function(e,t){this.collection=e,this._isTemporary=!1,this._dataSync$=new u.BehaviorSubject(t),this._isDeleted$=new u.BehaviorSubject(!1),this._atomicQueue=Promise.resolve(),this.isInstanceOfRxDocument=!0};return t.prototype=e,t},r.defineGetterSetter=y,r.createWithConstructor=function(e,t,r){if(r[t.schema.primaryPath]&&r[t.schema.primaryPath].startsWith("_design"))return null;var n=new e(t,r);return(0,d.runPluginHooks)("createRxDocument",n),n},r.isRxDocument=function(e){return void 0!==e&&!!e.isInstanceOfRxDocument},r.basePrototype=void 0;var i,o=n(e("@babel/runtime/regenerator")),a=n(e("@babel/runtime/helpers/asyncToGenerator")),s=n(e("object-path")),u=e("rxjs"),c=e("rxjs/operators"),f=e("./util"),l=e("./rx-error"),d=e("./hooks"),h=e("./rx-change-event"),p=e("./rx-collection-helper"),b=e("./overwritable"),v=e("./rx-schema-helper"),m={get _data(){if(this.isInstanceOfRxDocument)return this._dataSync$.getValue()},get primaryPath(){if(this.isInstanceOfRxDocument)return this.collection.schema.primaryPath},get primary(){var e=this;if(e.isInstanceOfRxDocument)return e._data[e.primaryPath]},get revision(){if(this.isInstanceOfRxDocument)return this._data._rev},get deleted$(){if(this.isInstanceOfRxDocument)return this._isDeleted$.asObservable()},get deleted(){if(this.isInstanceOfRxDocument)return this._isDeleted$.getValue()},get $(){return this._dataSync$.asObservable()},_handleChangeEvent:function(e){if(e.documentId===this.primary){var t=(0,h.getDocumentDataOfRxChangeEvent)(e),r=(0,f.getHeightOfRevision)(t._rev);if(!((0,f.getHeightOfRevision)(this._data._rev)>r))switch(e.operation){case"INSERT":break;case"UPDATE":var n=e.documentData;this._dataSync$.next(n);break;case"DELETE":this.collection._docCache.delete(this.primary),this._isDeleted$.next(!0)}}},$emit:function(e){return this.collection.$emit(e)},get$:function(e){if(e.includes(".item."))throw(0,l.newRxError)("DOC1",{path:e});if(e===this.primaryPath)throw(0,l.newRxError)("DOC2");if(this.collection.schema.finalFields.includes(e))throw(0,l.newRxError)("DOC3",{path:e});if(!(0,v.getSchemaByObjectPath)(this.collection.schema.jsonSchema,e))throw(0,l.newRxError)("DOC4",{path:e});return this._dataSync$.pipe((0,c.map)((function(t){return s.default.get(t,e)})),(0,c.distinctUntilChanged)())},populate:function(e){var t=(0,v.getSchemaByObjectPath)(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return Promise.resolve(null);if(!t)throw(0,l.newRxError)("DOC5",{path:e});if(!t.ref)throw(0,l.newRxError)("DOC6",{path:e,schemaObj:t});var n=this.collection.database.collections[t.ref];if(!n)throw(0,l.newRxError)("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?n.findByIds(r).then((function(e){var t=e.values();return Array.from(t)})):n.findOne(r).exec()},get:function(e){if(this._data){var t=s.default.get(this._data,e);return"object"!=typeof t||Array.isArray(t)?b.overwritable.deepFreezeWhenDevMode(t):(t=(0,f.clone)(t),y(this.collection.schema,t,e,this),t)}},toJSON:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(e)return b.overwritable.deepFreezeWhenDevMode(this._data);var t=(0,f.flatClone)(this._data);return delete t._rev,delete t._attachments,b.overwritable.deepFreezeWhenDevMode(t)},set:function(e,t){if(!this._isTemporary)throw(0,l.newRxTypeError)("DOC16",{objPath:e,value:t});if("string"!=typeof e)throw(0,l.newRxTypeError)("DOC15",{objPath:e,value:t});if(!Object.is(this.get(e),t)){var r=e.split(".");r.pop();var n=r.join(".");if(void 0===s.default.get(this._data,n))throw(0,l.newRxError)("DOC10",{childpath:e,rootPath:n});return s.default.set(this._data,e,t),this}},update:function(e){throw(0,f.pluginMissing)("update")},putAttachment:function(){throw(0,f.pluginMissing)("attachments")},getAttachment:function(){throw(0,f.pluginMissing)("attachments")},allAttachments:function(){throw(0,f.pluginMissing)("attachments")},get allAttachments$(){throw(0,f.pluginMissing)("attachments")},atomicUpdate:function(e){var t=this;return new Promise((function(r,n){t._atomicQueue=t._atomicQueue.then((0,a.default)(o.default.mark((function i(){var a,s,u;return o.default.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:a=!1;case 1:if(a){i.next=24;break}return s=t._dataSync$.getValue(),i.prev=3,i.next=6,e((0,f.clone)(t._dataSync$.getValue()),t);case 6:return u=i.sent,t.collection&&(u=t.collection.schema.fillObjectWithDefaults(u)),i.next=10,t._saveData(u,s);case 10:a=!0,i.next=22;break;case 13:if(i.prev=13,i.t0=i.catch(3),!(0,l.isPouchdbConflictError)(i.t0)){i.next=20;break}return i.next=18,(0,f.nextTick)();case 18:i.next=22;break;case 20:return n(i.t0),i.abrupt("return");case 22:i.next=1;break;case 24:r(t);case 25:case"end":return i.stop()}}),i,null,[[3,13]])}))))}))},atomicPatch:function(e){return this.atomicUpdate((function(t){return Object.entries(e).forEach((function(e){var r=e[0],n=e[1];t[r]=n})),t}))},_saveData:(i=(0,a.default)(o.default.mark((function e(t,r){return o.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=t,!this._isDeleted$.getValue()){e.next=3;break}throw(0,l.newRxError)("DOC11",{id:this.primary,document:this});case 3:return this.collection.schema.validateChange(r,t),e.next=6,this.collection._runHooks("pre","save",t,this);case 6:return this.collection.schema.validate(t),e.next=9,(0,p.writeToStorageInstance)(this.collection,{previous:r,document:t});case 9:return e.abrupt("return",this.collection._runHooks("post","save",t,this));case 10:case"end":return e.stop()}}),e,this)}))),function(e,t){return i.apply(this,arguments)}),save:function(){var e=this;if(!this._isTemporary)throw(0,l.newRxError)("DOC17",{id:this.primary,document:this});return this.collection.insert(this).then((function(){return e._isTemporary=!1,e.collection._docCache.set(e.primary,e),e._dataSync$.next(e._data),!0}))},remove:function(){var e=this;if(this.deleted)return Promise.reject((0,l.newRxError)("DOC13",{document:this,id:this.primary}));var t=(0,f.flatClone)(this._data);return this.collection._runHooks("pre","remove",t,this).then((function(){return t._deleted=!0,(0,f.now)(),(0,p.writeToStorageInstance)(e.collection,{previous:e._data,document:t})})).then((function(){return e.collection._runHooks("post","remove",t,e)})).then((function(){return e}))},destroy:function(){throw(0,l.newRxError)("DOC14")}};function y(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(null!==t){var i=(0,v.getSchemaByObjectPath)(e.jsonSchema,r);void 0!==i&&(i.properties&&(i=i.properties),Object.keys(i).forEach((function(e){var i=(0,f.trimDots)(r+"."+e);t.__defineGetter__(e,(function(){var e=n||this;if(e.get&&"function"==typeof e.get)return e.get(i)})),Object.defineProperty(t,e+"$",{get:function(){return(n||this).get$(i)},enumerable:!1,configurable:!1}),Object.defineProperty(t,e+"_",{get:function(){return(n||this).populate(i)},enumerable:!1,configurable:!1}),t.__defineSetter__(e,(function(e){return(n||this).set(i,e)}))})))}}r.basePrototype=m},{"./hooks":7,"./overwritable":9,"./rx-change-event":42,"./rx-collection-helper":43,"./rx-error":48,"./rx-schema-helper":50,"./util":58,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72,"object-path":629,rxjs:684,"rxjs/operators":908}],48:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.newRxError=function(e,t){return new c(e,s.overwritable.tunnelErrorMessage(e),t)},r.newRxTypeError=function(e,t){return new f(e,s.overwritable.tunnelErrorMessage(e),t)},r.isPouchdbConflictError=function(e){return!(!e.parameters||!e.parameters.pouchDbError||409!==e.parameters.pouchDbError.status)},r.RxTypeError=r.RxError=void 0;var i=n(e("@babel/runtime/helpers/createClass")),o=n(e("@babel/runtime/helpers/inheritsLoose")),a=n(e("@babel/runtime/helpers/wrapNativeSuper")),s=e("./overwritable");function u(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((function(t){var r="[object Object]";try{r=JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(e){}return t+":"+r})).join("\n"),t+="}")}(r)}var c=function(e){function t(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=u(r,t,i);return(n=e.call(this,o)||this).code=t,n.message=o,n.parameters=i,n.rxdb=!0,n}return(0,o.default)(t,e),t.prototype.toString=function(){return this.message},(0,i.default)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,a.default)(Error));r.RxError=c;var f=function(e){function t(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=u(r,t,i);return(n=e.call(this,o)||this).code=t,n.message=o,n.parameters=i,n.rxdb=!0,n}return(0,o.default)(t,e),t.prototype.toString=function(){return this.message},(0,i.default)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,a.default)(TypeError));r.RxTypeError=f},{"./overwritable":9,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/inheritsLoose":66,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/helpers/wrapNativeSuper":71}],49:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r._getDefaultQuery=m,r.tunnelQueryCache=y,r.createRxQuery=function(e,t,r){if(t&&"object"!=typeof t)throw(0,c.newRxTypeError)("QU7",{queryObj:t});if(Array.isArray(t))throw(0,c.newRxTypeError)("QU8",{queryObj:t});(0,f.runPluginHooks)("preCreateRxQuery",{op:e,queryObj:t,collection:r});var n=new v(e,t,r);return n=y(n),(0,f.runPluginHooks)("createRxQuery",n),(0,h.triggerCacheReplacement)(r),n},r.isInstanceOf=function(e){return e instanceof v},r.RxQueryBase=void 0;var i=n(e("@babel/runtime/helpers/createClass")),o=n(e("deep-equal")),a=e("rxjs"),s=e("rxjs/operators"),u=e("./util"),c=e("./rx-error"),f=e("./hooks"),l=e("./rx-document-prototype-merge"),d=e("./event-reduce"),h=e("./query-cache"),p=e("./rx-collection-helper"),b=0,v=function(){function e(e,t,r){this.id=++b,this._execOverDatabaseCount=0,this._creationTime=(0,u.now)(),this._lastEnsureEqual=0,this.other={},this.uncached=!1,this.refCount$=new a.BehaviorSubject(null),this._latestChangeEvent=-1,this._resultsData=null,this._resultsDataMap=new Map,this._lastExecStart=0,this._lastExecEnd=0,this._resultsDocs$=new a.BehaviorSubject(null),this._ensureEqualQueue=Promise.resolve(!1),this.op=e,this.mangoQuery=t,this.collection=r,t||(t=m(this.collection))}var t=e.prototype;return t._setResultData=function(e){this._resultsData=e;var t=(0,l.createRxDocuments)(this.collection,this._resultsData);return this._resultsDocs$.next(t),t},t._execOverDatabase=function(){var e,t=this;switch(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,u.now)(),this.op){case"find":e=this.collection._queryStorageInstance(this);break;case"findOne":e=this.collection._queryStorageInstance(this,1);break;default:throw(0,c.newRxError)("QU1",{collection:this.collection.name,op:this.op})}return e.then((function(e){t._lastExecEnd=(0,u.now)(),t._resultsDataMap=new Map;var r=t.collection.schema.primaryPath;return e.forEach((function(e){var n=e[r];t._resultsDataMap.set(n,e)})),e}))},t.exec=function(e){var t=this;if(e&&"findOne"!==this.op)throw(0,c.newRxError)("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return g(this).then((function(){return(0,a.firstValueFrom)(t.$)})).then((function(r){if(!r&&e)throw(0,c.newRxError)("QU10",{collection:t.collection.name,query:t.mangoQuery,op:t.op});return r}))},t.toString=function(){var e=(0,u.sortObject)({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e,u.stringifyFilter);return this.toString=function(){return t},t},t.toJSON=function(){var e={rxQuery:this,mangoQuery:(0,u.clone)(this.mangoQuery)};(0,f.runPluginHooks)("prePrepareQuery",e);var t=this.collection.storageInstance.prepareQuery(e.mangoQuery);return this.toJSON=function(){return t},t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher((0,p._handleToStorageInstance)(this.collection,e))},t.remove=function(){var e;return this.exec().then((function(t){return e=t,Array.isArray(t)?Promise.all(t.map((function(e){return e.remove()}))):t.remove()})).then((function(){return e}))},t.update=function(e){throw(0,u.pluginMissing)("update")},t.where=function(e){throw(0,u.pluginMissing)("query-builder")},t.sort=function(e){throw(0,u.pluginMissing)("query-builder")},t.skip=function(e){throw(0,u.pluginMissing)("query-builder")},t.limit=function(e){throw(0,u.pluginMissing)("query-builder")},(0,i.default)(e,[{key:"$",get:function(){var e=this;if(!this._$){var t=this._resultsDocs$.pipe((0,s.mergeMap)((function(t){return g(e).then((function(e){return!e&&t}))})),(0,s.filter)((function(e){return!!e})),(0,s.map)((function(t){return"findOne"===e.op?0===t.length?null:t[0]:t})),(0,s.map)((function(e){return Array.isArray(e)?e.slice():e}))).asObservable(),r=this.collection.$.pipe((0,s.tap)((function(){return g(e)})),(0,s.filter)((function(){return!1})));this._$=(0,a.merge)(t,r,this.refCount$.pipe((0,s.filter)((function(){return!1}))))}return this._$}},{key:"queryMatcher",get:function(){return(0,u.overwriteGetterForCaching)(this,"queryMatcher",this.collection.storageInstance.getQueryMatcher(this.toJSON()))}},{key:"asRxQuery",get:function(){return this}}]),e}();function m(e){var t;return{selector:(t={},t[e.schema.primaryPath]={},t)}}function y(e){return e.collection._queryCache.getByQuery(e)}function g(e){return e._ensureEqualQueue=e._ensureEqualQueue.then((function(){return(0,u.promiseWait)(0)})).then((function(){return function(e){if(e._lastEnsureEqual=(0,u.now)(),e.collection.database.destroyed)return!1;if(function(e){return e._latestChangeEvent>=e.collection._changeEventBuffer.counter}(e))return!1;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var n=e.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===n)r=!0;else{e._latestChangeEvent=e.collection._changeEventBuffer.counter,n=n.filter((function(t){return!t.startTime||t.startTime>e._lastExecStart}));var i=e.collection._changeEventBuffer.reduceByLastOfDoc(n),a=(0,d.calculateNewResults)(e,i);a.runFullQueryAgain?r=!0:a.changed&&(t=!0,e._setResultData(a.newResults))}}if(r){var s=e.collection._changeEventBuffer.counter;return e._execOverDatabase().then((function(r){return e._latestChangeEvent=s,(0,o.default)(r,e._resultsData)||(t=!0,e._setResultData(r)),t}))}return t}(e)})).then((function(e){return(0,u.promiseWait)(0).then((function(){return e}))})),e._ensureEqualQueue}r.RxQueryBase=v},{"./event-reduce":6,"./hooks":7,"./query-cache":41,"./rx-collection-helper":43,"./rx-document-prototype-merge":46,"./rx-error":48,"./util":58,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"deep-equal":497,rxjs:684,"rxjs/operators":908}],50:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.getPseudoSchemaForVersion=function(e,t){var r;return{version:e,type:"object",primaryKey:t,properties:(r={},r[t]={type:"string"},r)}},r.getSchemaByObjectPath=function(e,t){var r=t;return r="properties."+(r=r.replace(/\./g,".properties.")),r=(0,o.trimDots)(r),i.default.get(e,r)};var i=n(e("object-path")),o=e("./util")},{"./util":58,"@babel/runtime/helpers/interopRequireDefault":67,"object-path":629}],51:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.getIndexes=l,r.getPreviousVersions=function(e){var t=e.version?e.version:0,r=0;return new Array(t).fill(0).map((function(){return r++}))},r.getFinalFields=d,r.normalize=h,r.fillWithDefaultSettings=p,r.createRxSchema=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];t&&(0,u.runPluginHooks)("preCreateRxSchema",e);var r=new f(p(e));return(0,u.runPluginHooks)("createRxSchema",r),r},r.isInstanceOf=function(e){return e instanceof f},r.RxSchema=void 0;var i=n(e("@babel/runtime/helpers/createClass")),o=n(e("deep-equal")),a=e("./util"),s=e("./rx-error"),u=e("./hooks"),c=e("./rx-document"),f=function(){function e(e){this.jsonSchema=e,this.indexes=l(this.jsonSchema),this.primaryPath=this.jsonSchema.primaryKey,this.primaryPath&&this.jsonSchema.required.push(this.primaryPath),this.finalFields=d(this.jsonSchema),this.jsonSchema.required=this.jsonSchema.required.concat(this.finalFields).filter((function(e,t,r){return r.indexOf(e)===t}))}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((function(r){if(!(0,o.default)(e[r],t[r]))throw(0,s.newRxError)("DOC9",{dataBefore:e,dataAfter:t,fieldName:r})}))},t.validate=function(e,t){throw(0,a.pluginMissing)("validate")},t.fillObjectWithDefaults=function(e){return e=(0,a.clone)(e),Object.entries(this.defaultValues).filter((function(t){var r=t[0];return!e.hasOwnProperty(r)||void 0===e[r]})).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.getDocumentPrototype=function(){var e={};return(0,c.defineGetterSetter)(this,e,""),(0,a.overwriteGetterForCaching)(this,"getDocumentPrototype",(function(){return e})),e},(0,i.default)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"normalized",get:function(){return(0,a.overwriteGetterForCaching)(this,"normalized",h(this.jsonSchema))}},{key:"topLevelFields",get:function(){return Object.keys(this.normalized.properties)}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.normalized.properties).filter((function(e){return e[1].hasOwnProperty("default")})).forEach((function(t){var r=t[0],n=t[1];return e[r]=n.default})),(0,a.overwriteGetterForCaching)(this,"defaultValues",e)}},{key:"crypt",get:function(){return!!(this.jsonSchema.encrypted&&this.jsonSchema.encrypted.length>0||this.jsonSchema.attachments&&this.jsonSchema.attachments.encrypted)}},{key:"encryptedPaths",get:function(){return this.jsonSchema.encrypted||[]}},{key:"hash",get:function(){return(0,a.overwriteGetterForCaching)(this,"hash",(0,a.hash)(this.normalized))}}]),e}();function l(e){return(e.indexes||[]).map((function(e){return Array.isArray(e)?e:[e]}))}function d(e){var t=Object.keys(e.properties).filter((function(t){return e.properties[t].final}));return t.push(e.primaryKey),t}function h(e){var t=(0,a.sortObject)((0,a.clone)(e));return e.indexes&&(t.indexes=Array.from(e.indexes)),e.required?e.required.includes(e.primaryKey)||e.required.push(e.primaryKey):e.required=[e.primaryKey],t}function p(e){return(e=(0,a.clone)(e)).additionalProperties=!1,e.hasOwnProperty("keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes||[],e.required=e.required||[],e.encrypted=e.encrypted||[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.version=e.version||0,e}r.RxSchema=f},{"./hooks":7,"./rx-document":47,"./rx-error":48,"./util":58,"@babel/runtime/helpers/createClass":64,"@babel/runtime/helpers/interopRequireDefault":67,"deep-equal":497}],52:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.getAllDocuments=c,r.getSingleDocument=function(e,t){return l.apply(this,arguments)},r.countAllUndeleted=function(e){return d.apply(this,arguments)},r.getBatch=function(e,t){return h.apply(this,arguments)},r.writeSingle=function(e,t){return p.apply(this,arguments)},r.writeSingleLocal=function(e,t){return b.apply(this,arguments)},r.findLocalDocument=function(e,t){return v.apply(this,arguments)},r.getNewestSequence=function(e){return m.apply(this,arguments)},r.storageChangeEventToRxChangeEvent=function(e,t,r,n){var i,o;if("DELETE"!==t.change.operation)if(n){var u={collection:n,doc:t.change.doc};(0,a.runPluginHooks)("postReadFromInstance",u),i=u.doc,i=n._crypter.decrypt(i)}else i=t.change.doc;if("INSERT"!==t.change.operation)if(n){var c={collection:n,doc:t.change.previous};(0,a.runPluginHooks)("postReadFromInstance",c),o=c.doc,o=n._crypter.decrypt(o)}else o=t.change.previous;return{eventId:t.eventId,documentId:t.documentId,databaseToken:r.token,collectionName:n?n.name:void 0,startTime:t.startTime,endTime:t.endTime,isLocal:e,operation:t.change.operation,documentData:s.overwritable.deepFreezeWhenDevMode(i),previousDocumentData:s.overwritable.deepFreezeWhenDevMode(o)}},r.INTERNAL_STORAGE_NAME=void 0;var i=n(e("@babel/runtime/regenerator")),o=n(e("@babel/runtime/helpers/asyncToGenerator")),a=e("./hooks"),s=e("./overwritable"),u=e("./rx-error");function c(e){return f.apply(this,arguments)}function f(){return(f=(0,o.default)(i.default.mark((function e(t){var r,n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.prepareQuery({selector:{}}),e.next=3,t.query(r);case 3:return n=e.sent,o=n.documents,e.abrupt("return",o);case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function l(){return(l=(0,o.default)(i.default.mark((function e(t,r){var n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.findDocumentsById([r],!1);case 2:if(n=e.sent,!(o=n.get(r))){e.next=8;break}return e.abrupt("return",o);case 8:return e.abrupt("return",null);case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function d(){return(d=(0,o.default)(i.default.mark((function e(t){var r;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,c(t);case 2:return r=e.sent,e.abrupt("return",r.length);case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function h(){return(h=(0,o.default)(i.default.mark((function e(t,r){var n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(r<=1)){e.next=2;break}throw(0,u.newRxError)("P1",{limit:r});case 2:return n=t.prepareQuery({selector:{},limit:r}),e.next=5,t.query(n);case 5:return o=e.sent,e.abrupt("return",o.documents);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function p(){return(p=(0,o.default)(i.default.mark((function e(t,r){var n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.bulkWrite([r]);case 2:if(!((n=e.sent).error.size>0)){e.next=8;break}throw n.error.values().next().value;case 8:return o=n.success.values().next().value,e.abrupt("return",o);case 10:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function b(){return(b=(0,o.default)(i.default.mark((function e(t,r){var n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.bulkWrite([r]);case 2:if(!((n=e.sent).error.size>0)){e.next=8;break}throw n.error.values().next().value;case 8:return o=n.success.values().next().value,e.abrupt("return",o);case 10:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function v(){return(v=(0,o.default)(i.default.mark((function e(t,r){var n,o;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.findLocalDocumentsById([r]);case 2:if(n=e.sent,o=n.get(r)){e.next=8;break}return e.abrupt("return",null);case 8:return e.abrupt("return",o);case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function m(){return(m=(0,o.default)(i.default.mark((function e(t){var r;return i.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.getChangedDocuments({order:"desc",limit:1,startSequence:0});case 2:return r=e.sent,e.abrupt("return",r.lastSequence);case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}r.INTERNAL_STORAGE_NAME="_rxdb_internal"},{"./hooks":7,"./overwritable":9,"./rx-error":48,"@babel/runtime/helpers/asyncToGenerator":62,"@babel/runtime/helpers/interopRequireDefault":67,"@babel/runtime/regenerator":72}],53:[function(e,t,r){},{}],54:[function(e,t,r){},{}],55:[function(e,t,r){},{}],56:[function(e,t,r){},{}],57:[function(e,t,r){},{}],58:[function(e,t,r){(function(t){(function(){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.pluginMissing=function(e){var t=e.split("-"),r="RxDB";return t.forEach((function(e){r+=d(e)})),r+="Plugin",new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { "+r+" } from 'rxdb/plugins/"+e+"';\n addRxPlugin("+r+");\n ")},r.fastUnsecureHash=function(e){"string"!=typeof e&&(e=JSON.stringify(e));var t,r,n,i=0;if(0===e.length)return i;for(t=0,n=e.length;t0&&void 0!==arguments[0]?arguments[0]:0;return new Promise((function(t){return setTimeout(t,e)}))},r.toPromise=function(e){return e&&"function"==typeof e.then?e:Promise.resolve(e)},r.requestIdlePromise=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return"object"==typeof window&&window.requestIdleCallback?new Promise((function(t){return window.requestIdleCallback(t,{timeout:e})})):Promise.resolve()},r.promiseSeries=function(e,t){return e.reduce((function(e,t){return e.then(t)}),Promise.resolve(t))},r.requestIdleCallbackIfAvailable=function(e){"object"==typeof window&&window.requestIdleCallback&&window.requestIdleCallback(e)},r.ucfirst=d,r.trimDots=function(e){for(;"."===e.charAt(0);)e=e.substr(1);for(;"."===e.slice(-1);)e=e.slice(0,-1);return e},r.ensureNotFalsy=function(e){if(!e)throw new Error("ensureNotFalsy() is falsy");return e},r.sortObject=function e(t){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!t)return t;if(!r&&Array.isArray(t))return t.sort((function(e,t){return"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1})).map((function(t){return e(t,r)}));if("object"==typeof t&&!Array.isArray(t)){if(t instanceof RegExp)return t;var n={};return Object.keys(t).sort((function(e,t){return e.localeCompare(t)})).forEach((function(i){n[i]=e(t[i],r)})),n}return t},r.stringifyFilter=function(e,t){if(t instanceof RegExp)return t.toString();return t},r.randomCouchString=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10,t="",r="abcdefghijklmnopqrstuvwxyz",n=0;n>1)],t)<=0?a=s+1:o=s-1}r(i[s],t)<=0&&s++;return i.splice(s,0,t),i}},{}],75:[function(e,t,r){"use strict";const n=r;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":76,"./asn1/base":78,"./asn1/constants":82,"./asn1/decoders":84,"./asn1/encoders":87,"bn.js":89}],76:[function(e,t,r){"use strict";const n=e("./encoders"),i=e("./decoders"),o=e("inherits");function a(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new a(e,t)},a.prototype._createNamed=function(e){const t=this.name;function r(e){this._initNamed(e,t)}return o(r,e),r.prototype._initNamed=function(t,r){e.call(this,t,r)},new r(this)},a.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(i[e])),this.decoders[e]},a.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},a.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n[e])),this.encoders[e]},a.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},{"./decoders":84,"./encoders":87,inherits:586}],77:[function(e,t,r){"use strict";const n=e("inherits"),i=e("../base/reporter").Reporter,o=e("safer-buffer").Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map((function(e){return s.isEncoderBuffer(e)||(e=new s(e,t)),this.length+=e.length,e}),this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),r.DecoderBuffer=a,a.isDecoderBuffer=function(e){if(e instanceof a)return!0;return"object"==typeof e&&o.isBuffer(e.base)&&"DecoderBuffer"===e.constructor.name&&"number"==typeof e.offset&&"number"==typeof e.length&&"function"==typeof e.save&&"function"==typeof e.restore&&"function"==typeof e.isEmpty&&"function"==typeof e.readUInt8&&"function"==typeof e.skip&&"function"==typeof e.raw},a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){const t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");const r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=s,s.isEncoderBuffer=function(e){if(e instanceof s)return!0;return"object"==typeof e&&"EncoderBuffer"===e.constructor.name&&"number"==typeof e.length&&"function"==typeof e.join},s.prototype.join=function(e,t){return e||(e=o.alloc(this.length)),t||(t=0),0===this.length||(Array.isArray(this.value)?this.value.forEach((function(r){r.join(e,t),t+=r.length})):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}},{"../base/reporter":80,inherits:586,"safer-buffer":910}],78:[function(e,t,r){"use strict";const n=r;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":77,"./node":79,"./reporter":80}],79:[function(e,t,r){"use strict";const n=e("../base/reporter").Reporter,i=e("../base/buffer").EncoderBuffer,o=e("../base/buffer").DecoderBuffer,a=e("minimalistic-assert"),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function c(e,t,r){const n={};this._baseState=n,n.name=r,n.enc=e,n.parent=t||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}t.exports=c;const f=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){const e=this._baseState,t={};f.forEach((function(r){t[r]=e[r]}));const r=new this.constructor(t.parent);return r._baseState=t,r},c.prototype._wrap=function(){const e=this._baseState;u.forEach((function(t){this[t]=function(){const r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}}),this)},c.prototype._init=function(e){const t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter((function(e){return e._baseState.parent===this}),this),a.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){const t=this._baseState,r=e.filter((function(e){return e instanceof this.constructor}),this);e=e.filter((function(e){return!(e instanceof this.constructor)}),this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach((function(e){e._baseState.parent=this}),this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map((function(e){if("object"!=typeof e||e.constructor!==Object)return e;const t={};return Object.keys(e).forEach((function(r){r==(0|r)&&(r|=0);const n=e[r];t[n]=r})),t})))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach((function(e){c.prototype[e]=function(){const t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}})),s.forEach((function(e){c.prototype[e]=function(){const t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}})),c.prototype.use=function(e){a(e);const t=this._baseState;return a(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){const t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){const t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){const t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){const e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){const t=this._baseState;return a(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){const t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map((function(t){return e[t]}))),this},c.prototype.contains=function(e){const t=this._baseState;return a(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){const r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));let n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){let n=null;if(null!==r.explicit?n=r.explicit:null!==r.implicit?n=r.implicit:null!==r.tag&&(n=r.tag),null!==n||r.any){if(a=this._peekTag(e,n,r.any),e.isError(a))return a}else{const n=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(n)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){const t=this._decodeTag(e,r.explicit);if(e.isError(t))return t;e=t}const n=e.offset;if(null===r.use&&null===r.choice){let t;r.any&&(t=e.save());const n=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(n))return n;r.any?i=e.raw(t):e=n}if(t&&t.track&&null!==r.tag&&t.track(e.path(),n,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),r.any||(i=null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t)),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach((function(r){r._decode(e,t)})),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){const n=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(n,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},c.prototype._decodeGeneric=function(e,t,r){const n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){const r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},c.prototype._decodeChoice=function(e,t){const r=this._baseState;let n=null,i=!1;return Object.keys(r.choice).some((function(o){const a=e.save(),s=r.choice[o];try{const r=s._decode(e,t);if(e.isError(r))return!1;n={type:o,value:r},i=!0}catch(t){return e.restore(a),!1}return!0}),this),i?n:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,r){const n=this._baseState;if(null!==n.default&&n.default===e)return;const i=this._encodeValue(e,t,r);return void 0===i||this._skipDefault(i,t,r)?void 0:i},c.prototype._encodeValue=function(e,t,r){const i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);let o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}let a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map((function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");const n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");const i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i}),this).filter((function(e){return e})),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");const r=this.clone();r._baseState.implicit=null,a=this._createEncoderBuffer(e.map((function(r){const n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)}),r))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){const e=null!==i.implicit?i.implicit:i.tag,r=null===i.implicit?"universal":"context";null===e?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(e,s,r,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){const r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){const r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},{"../base/buffer":77,"../base/reporter":80,"minimalistic-assert":617}],80:[function(e,t,r){"use strict";const n=e("inherits");function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}r.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){const e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){const t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){const t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){const n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){const e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){const t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){let t;const r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map((function(e){return"["+JSON.stringify(e)+"]"})).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){const t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:586}],81:[function(e,t,r){"use strict";function n(e){const t={};return Object.keys(e).forEach((function(r){(0|r)==r&&(r|=0);const n=e[r];t[n]=r})),t}r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=n(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=n(r.tag)},{}],82:[function(e,t,r){"use strict";const n=r;n._reverse=function(e){const t={};return Object.keys(e).forEach((function(r){(0|r)==r&&(r|=0);const n=e[r];t[n]=r})),t},n.der=e("./der")},{"./der":81}],83:[function(e,t,r){"use strict";const n=e("inherits"),i=e("bn.js"),o=e("../base/buffer").DecoderBuffer,a=e("../base/node"),s=e("../constants/der");function u(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){a.call(this,"der",e)}function f(e,t){let r=e.readUInt8(t);if(e.isError(r))return r;const n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){let n=r;for(r=0;128==(128&n);){if(n=e.readUInt8(t),e.isError(n))return n;r<<=7,r|=127&n}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function l(e,t,r){let n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;const i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(let t=0;t=31)return n.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=a.tagClassByName[r||"universal"]<<6,i}(e,t,r,this.reporter);if(n.length<128){const e=i.alloc(2);return e[0]=o,e[1]=n.length,this._createEncoderBuffer([e,n])}let s=1;for(let e=n.length;e>=256;e>>=8)s++;const u=i.alloc(2+s);u[0]=o,u[1]=128|s;for(let e=1+s,t=n.length;t>0;e--,t>>=8)u[e]=255&t;return this._createEncoderBuffer([u,n])},u.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){const t=i.alloc(2*e.length);for(let r=0;r=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let n=0;for(let t=0;t=128;r>>=7)n++}const o=i.alloc(n);let a=o.length-1;for(let t=e.length-1;t>=0;t--){let r=e[t];for(o[a--]=127&r;(r>>=7)>0;)o[a--]=128|127&r}return this._createEncoderBuffer(o)},u.prototype._encodeTime=function(e,t){let r;const n=new Date(e);return"gentime"===t?r=[c(n.getUTCFullYear()),c(n.getUTCMonth()+1),c(n.getUTCDate()),c(n.getUTCHours()),c(n.getUTCMinutes()),c(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[c(n.getUTCFullYear()%100),c(n.getUTCMonth()+1),c(n.getUTCDate()),c(n.getUTCHours()),c(n.getUTCMinutes()),c(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},u.prototype._encodeNull=function(){return this._createEncoderBuffer("")},u.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){const t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=i.from(t)}if(i.isBuffer(e)){let t=e.length;0===e.length&&t++;const r=i.alloc(t);return e.copy(r),0===e.length&&(r[0]=0),this._createEncoderBuffer(r)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let r=1;for(let t=e;t>=256;t>>=8)r++;const n=new Array(r);for(let t=n.length-1;t>=0;t--)n[t]=255&e,e>>=8;return 128&n[0]&&n.unshift(0),this._createEncoderBuffer(i.from(n))},u.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},u.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},u.prototype._skipDefault=function(e,t,r){const n=this._baseState;let i;if(null===n.default)return!1;const o=e.join();if(void 0===n.defaultBuffer&&(n.defaultBuffer=this._encodeValue(n.default,t,r).join()),o.length!==n.defaultBuffer.length)return!1;for(i=0;i=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(e,t,r){var n=s(e,r);return r-1>=t&&(n|=s(e,r-1)<<4),n}function c(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)i=u(e,t,n)<=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,u=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var f=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],l=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],d=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,l=67108863&u,d=Math.min(c,t.length-1),h=Math.max(0,c-e.length+1);h<=d;h++){var p=c-h|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[h])+l)/67108864|0,l=67108863&a}r.words[c]=0|l,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?f[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var c=l[e],h=d[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(h).toString(e);r=(p=p.idivn(h)).isZero()?b+r:f[c-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,h=0|a[1],p=8191&h,b=h>>>13,v=0|a[2],m=8191&v,y=v>>>13,g=0|a[3],_=8191&g,w=g>>>13,S=0|a[4],x=8191&S,O=S>>>13,j=0|a[5],E=8191&j,M=j>>>13,k=0|a[6],A=8191&k,P=k>>>13,R=0|a[7],C=8191&R,I=R>>>13,D=0|a[8],T=8191&D,B=D>>>13,N=0|a[9],L=8191&N,F=N>>>13,q=0|s[0],U=8191&q,z=q>>>13,W=0|s[1],$=8191&W,H=W>>>13,K=0|s[2],V=8191&K,G=K>>>13,Q=0|s[3],J=8191&Q,Y=Q>>>13,X=0|s[4],Z=8191&X,ee=X>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],le=8191&fe,de=fe>>>13,he=0|s[9],pe=8191&he,be=he>>>13;r.negative=e.negative^t.negative,r.length=19;var ve=(c+(n=Math.imul(l,U))|0)+((8191&(i=(i=Math.imul(l,z))+Math.imul(d,U)|0))<<13)|0;c=((o=Math.imul(d,z))+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,U),i=(i=Math.imul(p,z))+Math.imul(b,U)|0,o=Math.imul(b,z);var me=(c+(n=n+Math.imul(l,$)|0)|0)+((8191&(i=(i=i+Math.imul(l,H)|0)+Math.imul(d,$)|0))<<13)|0;c=((o=o+Math.imul(d,H)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,U),i=(i=Math.imul(m,z))+Math.imul(y,U)|0,o=Math.imul(y,z),n=n+Math.imul(p,$)|0,i=(i=i+Math.imul(p,H)|0)+Math.imul(b,$)|0,o=o+Math.imul(b,H)|0;var ye=(c+(n=n+Math.imul(l,V)|0)|0)+((8191&(i=(i=i+Math.imul(l,G)|0)+Math.imul(d,V)|0))<<13)|0;c=((o=o+Math.imul(d,G)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(_,U),i=(i=Math.imul(_,z))+Math.imul(w,U)|0,o=Math.imul(w,z),n=n+Math.imul(m,$)|0,i=(i=i+Math.imul(m,H)|0)+Math.imul(y,$)|0,o=o+Math.imul(y,H)|0,n=n+Math.imul(p,V)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(b,V)|0,o=o+Math.imul(b,G)|0;var ge=(c+(n=n+Math.imul(l,J)|0)|0)+((8191&(i=(i=i+Math.imul(l,Y)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,Y)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(x,U),i=(i=Math.imul(x,z))+Math.imul(O,U)|0,o=Math.imul(O,z),n=n+Math.imul(_,$)|0,i=(i=i+Math.imul(_,H)|0)+Math.imul(w,$)|0,o=o+Math.imul(w,H)|0,n=n+Math.imul(m,V)|0,i=(i=i+Math.imul(m,G)|0)+Math.imul(y,V)|0,o=o+Math.imul(y,G)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,Y)|0;var _e=(c+(n=n+Math.imul(l,Z)|0)|0)+((8191&(i=(i=i+Math.imul(l,ee)|0)+Math.imul(d,Z)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(E,U),i=(i=Math.imul(E,z))+Math.imul(M,U)|0,o=Math.imul(M,z),n=n+Math.imul(x,$)|0,i=(i=i+Math.imul(x,H)|0)+Math.imul(O,$)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(_,V)|0,i=(i=i+Math.imul(_,G)|0)+Math.imul(w,V)|0,o=o+Math.imul(w,G)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(y,J)|0,o=o+Math.imul(y,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,ee)|0;var we=(c+(n=n+Math.imul(l,re)|0)|0)+((8191&(i=(i=i+Math.imul(l,ne)|0)+Math.imul(d,re)|0))<<13)|0;c=((o=o+Math.imul(d,ne)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(A,U),i=(i=Math.imul(A,z))+Math.imul(P,U)|0,o=Math.imul(P,z),n=n+Math.imul(E,$)|0,i=(i=i+Math.imul(E,H)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(x,V)|0,i=(i=i+Math.imul(x,G)|0)+Math.imul(O,V)|0,o=o+Math.imul(O,G)|0,n=n+Math.imul(_,J)|0,i=(i=i+Math.imul(_,Y)|0)+Math.imul(w,J)|0,o=o+Math.imul(w,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Se=(c+(n=n+Math.imul(l,oe)|0)|0)+((8191&(i=(i=i+Math.imul(l,ae)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,ae)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(C,U),i=(i=Math.imul(C,z))+Math.imul(I,U)|0,o=Math.imul(I,z),n=n+Math.imul(A,$)|0,i=(i=i+Math.imul(A,H)|0)+Math.imul(P,$)|0,o=o+Math.imul(P,H)|0,n=n+Math.imul(E,V)|0,i=(i=i+Math.imul(E,G)|0)+Math.imul(M,V)|0,o=o+Math.imul(M,G)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,Y)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Y)|0,n=n+Math.imul(_,Z)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(y,re)|0,o=o+Math.imul(y,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var xe=(c+(n=n+Math.imul(l,ue)|0)|0)+((8191&(i=(i=i+Math.imul(l,ce)|0)+Math.imul(d,ue)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(T,U),i=(i=Math.imul(T,z))+Math.imul(B,U)|0,o=Math.imul(B,z),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,H)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,H)|0,n=n+Math.imul(A,V)|0,i=(i=i+Math.imul(A,G)|0)+Math.imul(P,V)|0,o=o+Math.imul(P,G)|0,n=n+Math.imul(E,J)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(x,Z)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(_,re)|0,i=(i=i+Math.imul(_,ne)|0)+Math.imul(w,re)|0,o=o+Math.imul(w,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(y,oe)|0,o=o+Math.imul(y,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var Oe=(c+(n=n+Math.imul(l,le)|0)|0)+((8191&(i=(i=i+Math.imul(l,de)|0)+Math.imul(d,le)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(L,U),i=(i=Math.imul(L,z))+Math.imul(F,U)|0,o=Math.imul(F,z),n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,H)|0)+Math.imul(B,$)|0,o=o+Math.imul(B,H)|0,n=n+Math.imul(C,V)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(I,V)|0,o=o+Math.imul(I,G)|0,n=n+Math.imul(A,J)|0,i=(i=i+Math.imul(A,Y)|0)+Math.imul(P,J)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(x,re)|0,i=(i=i+Math.imul(x,ne)|0)+Math.imul(O,re)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(_,oe)|0,i=(i=i+Math.imul(_,ae)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(y,ue)|0,o=o+Math.imul(y,ce)|0,n=n+Math.imul(p,le)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(b,le)|0,o=o+Math.imul(b,de)|0;var je=(c+(n=n+Math.imul(l,pe)|0)|0)+((8191&(i=(i=i+Math.imul(l,be)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(L,$),i=(i=Math.imul(L,H))+Math.imul(F,$)|0,o=Math.imul(F,H),n=n+Math.imul(T,V)|0,i=(i=i+Math.imul(T,G)|0)+Math.imul(B,V)|0,o=o+Math.imul(B,G)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,Y)|0)+Math.imul(I,J)|0,o=o+Math.imul(I,Y)|0,n=n+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,ee)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,ae)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,ae)|0,n=n+Math.imul(_,ue)|0,i=(i=i+Math.imul(_,ce)|0)+Math.imul(w,ue)|0,o=o+Math.imul(w,ce)|0,n=n+Math.imul(m,le)|0,i=(i=i+Math.imul(m,de)|0)+Math.imul(y,le)|0,o=o+Math.imul(y,de)|0;var Ee=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(L,V),i=(i=Math.imul(L,G))+Math.imul(F,V)|0,o=Math.imul(F,G),n=n+Math.imul(T,J)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(B,J)|0,o=o+Math.imul(B,Y)|0,n=n+Math.imul(C,Z)|0,i=(i=i+Math.imul(C,ee)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,ee)|0,n=n+Math.imul(A,re)|0,i=(i=i+Math.imul(A,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,ce)|0,n=n+Math.imul(_,le)|0,i=(i=i+Math.imul(_,de)|0)+Math.imul(w,le)|0,o=o+Math.imul(w,de)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(y,pe)|0))<<13)|0;c=((o=o+Math.imul(y,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(L,J),i=(i=Math.imul(L,Y))+Math.imul(F,J)|0,o=Math.imul(F,Y),n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(B,Z)|0,o=o+Math.imul(B,ee)|0,n=n+Math.imul(C,re)|0,i=(i=i+Math.imul(C,ne)|0)+Math.imul(I,re)|0,o=o+Math.imul(I,ne)|0,n=n+Math.imul(A,oe)|0,i=(i=i+Math.imul(A,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(x,le)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(O,le)|0,o=o+Math.imul(O,de)|0;var ke=(c+(n=n+Math.imul(_,pe)|0)|0)+((8191&(i=(i=i+Math.imul(_,be)|0)+Math.imul(w,pe)|0))<<13)|0;c=((o=o+Math.imul(w,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(L,Z),i=(i=Math.imul(L,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(B,re)|0,o=o+Math.imul(B,ne)|0,n=n+Math.imul(C,oe)|0,i=(i=i+Math.imul(C,ae)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,ae)|0,n=n+Math.imul(A,ue)|0,i=(i=i+Math.imul(A,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(E,le)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,le)|0,o=o+Math.imul(M,de)|0;var Ae=(c+(n=n+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,be)|0)+Math.imul(O,pe)|0))<<13)|0;c=((o=o+Math.imul(O,be)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(L,re),i=(i=Math.imul(L,ne))+Math.imul(F,re)|0,o=Math.imul(F,ne),n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(B,oe)|0,o=o+Math.imul(B,ae)|0,n=n+Math.imul(C,ue)|0,i=(i=i+Math.imul(C,ce)|0)+Math.imul(I,ue)|0,o=o+Math.imul(I,ce)|0,n=n+Math.imul(A,le)|0,i=(i=i+Math.imul(A,de)|0)+Math.imul(P,le)|0,o=o+Math.imul(P,de)|0;var Pe=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(L,oe),i=(i=Math.imul(L,ae))+Math.imul(F,oe)|0,o=Math.imul(F,ae),n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(B,ue)|0,o=o+Math.imul(B,ce)|0,n=n+Math.imul(C,le)|0,i=(i=i+Math.imul(C,de)|0)+Math.imul(I,le)|0,o=o+Math.imul(I,de)|0;var Re=(c+(n=n+Math.imul(A,pe)|0)|0)+((8191&(i=(i=i+Math.imul(A,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(L,ue),i=(i=Math.imul(L,ce))+Math.imul(F,ue)|0,o=Math.imul(F,ce),n=n+Math.imul(T,le)|0,i=(i=i+Math.imul(T,de)|0)+Math.imul(B,le)|0,o=o+Math.imul(B,de)|0;var Ce=(c+(n=n+Math.imul(C,pe)|0)|0)+((8191&(i=(i=i+Math.imul(C,be)|0)+Math.imul(I,pe)|0))<<13)|0;c=((o=o+Math.imul(I,be)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(L,le),i=(i=Math.imul(L,de))+Math.imul(F,le)|0,o=Math.imul(F,de);var Ie=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(B,pe)|0))<<13)|0;c=((o=o+Math.imul(B,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863;var De=(c+(n=Math.imul(L,pe))|0)+((8191&(i=(i=Math.imul(L,be))+Math.imul(F,pe)|0))<<13)|0;return c=((o=Math.imul(F,be))+(i>>>13)|0)+(De>>>26)|0,De&=67108863,u[0]=ve,u[1]=me,u[2]=ye,u[3]=ge,u[4]=_e,u[5]=we,u[6]=Se,u[7]=xe,u[8]=Oe,u[9]=je,u[10]=Ee,u[11]=Me,u[12]=ke,u[13]=Ae,u[14]=Pe,u[15]=Re,u[16]=Ce,u[17]=Ie,u[18]=De,0!==c&&(u[19]=c,r.length++),r};function b(e,t,r){return(new v).mulp(e,t,r)}function v(e,t){this.x=e,this.y=t}Math.imul||(p=h),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?p(this,e,t):r<63?h(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):b(this,e,t)},v.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},v.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var l=0|this.words[c];this.words[c]=f<<26-o|l>>>o,f=l&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;l--){var d=67108864*(0|n.words[i.length+l])+(0|n.words[i.length+l-1]);for(d=Math.min(d/a|0,67108863),n._ishlnsubmul(i,d,l);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(i,1,l),n.isZero()||(n.negative^=1);s&&(s.words[l]=d)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),l=t.clone();!t.isZero();){for(var d=0,h=1;0==(t.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(l)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(l)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var l=0,d=1;0==(r.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(r.iushrn(l);l-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new x(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var m={k256:null,p224:null,p192:null,p25519:null};function y(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function g(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function _(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function x(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function O(e){x.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}y.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},y.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},y.prototype.split=function(e,t){e.iushrn(this.n,0,t)},y.prototype.imulK=function(e){return e.imul(this.k)},i(g,y),g.prototype.split=function(e,t){for(var r=4194303,n=Math.min(e.length,9),i=0;i>>22,o=a}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},g.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(m[e])return m[e];var t;if("k256"===e)t=new g;else if("p224"===e)t=new _;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return m[e]=t,t},x.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},x.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},x.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},x.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},x.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},x.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},x.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},x.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},x.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},x.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},x.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},x.prototype.isqr=function(e){return this.imul(e,e.clone())},x.prototype.sqr=function(e){return this.mul(e,e)},x.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var l=this.pow(f,i),d=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=a;0!==h.cmp(s);){for(var b=h,v=0;0!==b.cmp(s);v++)b=b.redSqr();n(v=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var l=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==l||0!==a?(a<<=1,a|=l,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},x.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},x.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new O(e)},i(O,x),O.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},O.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},O.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},O.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},O.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:125}],90:[function(e,t,r){(function(e){(function(){"use strict";var r=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"];t.exports=function(){for(var t=[],n=0;n0?a-4:a;for(r=0;r>16&255,u[f++]=t>>8&255,u[f++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[f++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[f++]=t>>8&255,u[f++]=255&t);return u},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],a=16383,s=0,u=r-i;su?u:s+a));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function f(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],92:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./util"),i=e("./find-similar-node"),o=function(){function e(e,t,r){this.level=e,this.id=n.nextNodeId(),this.deleted=!1,this.type=r,this.rootNode=t,t&&this.rootNode.addNode(this)}return e.prototype.isEqualToOtherNode=function(e,t){return void 0===t&&(t=this.toString()),t===e.toString()},e.prototype.remove=function(){var e;if((this.ensureNotDeleted("remove"),this.isInternalNode())&&(e=this).parents.size>0)throw new Error("cannot remove node with parents "+this.id);this.branches&&((e=this).branches.areBranchesStrictEqual()?e.branches.getBranch("0").parents.remove(e):(e.branches.getBranch("0").parents.remove(e),e.branches.getBranch("1").parents.remove(e)));this.deleted=!0,this.rootNode.removeNode(this)},e.prototype.toJSON=function(e){void 0===e&&(e=!1);var t={id:e?this.id:void 0,deleted:e?this.deleted:void 0,type:this.type,level:this.level};if(e&&this.parents&&(t.parents=this.parents.toString()),this.isLeafNode()&&(t.value=this.asLeafNode().value),this.branches&&!this.branches.deleted){var r=this.branches;t.branches={0:r.getBranch("0").toJSON(e),1:r.getBranch("1").toJSON(e)}}return t},e.prototype.toString=function(){var e="<"+this.type+":"+this.level;if(this.branches){var t=this.branches;e+="|0:"+t.getBranch("0"),e+="|1:"+t.getBranch("1")}return this.isLeafNode()&&(e+="|v:"+this.asLeafNode().value),e+=">"},e.prototype.isRootNode=function(){return"RootNode"===this.type},e.prototype.isInternalNode=function(){return"InternalNode"===this.type},e.prototype.isLeafNode=function(){return"LeafNode"===this.type},e.prototype.asRootNode=function(){if(!this.isRootNode())throw new Error("ouch");return this},e.prototype.asInternalNode=function(){if(!this.isInternalNode())throw new Error("ouch");return this},e.prototype.asLeafNode=function(){if(!this.isLeafNode())throw new Error("ouch");return this},e.prototype.ensureNotDeleted=function(e){if(void 0===e&&(e="unknown"),this.deleted)throw new Error("forbidden operation "+e+" on deleted node "+this.id)},e.prototype.log=function(){console.log(JSON.stringify(this.toJSON(!0),null,2))},e.prototype.applyEliminationRule=function(e){var t=this;this.ensureNotDeleted("applyEliminationRule"),e||(e=this.rootNode.getNodesOfLevel(this.level));var r=i.findSimilarNode(this,e);if(r){var n=this.parents.getAll(),o=[];return n.forEach((function(e){var n=e.branches.getKeyOfNode(t);e.branches.setBranch(n,r),e.branches.areBranchesStrictEqual()&&o.push(e),t.parents.remove(e)})),o.forEach((function(e){e.isInternalNode()&&e.applyReductionRule()})),!0}return!1},e}();r.AbstractNode=o},{"./find-similar-node":97,"./util":110}],93:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e){this.node=e,this.deleted=!1,this.branches={}}return e.prototype.setBranch=function(e,t){this.branches[e]!==t&&(this.branches[e]=t,t.parents.add(this.node))},e.prototype.getKeyOfNode=function(e){if(this.getBranch("0")===e)return"0";if(this.getBranch("1")===e)return"1";throw new Error("none matched")},e.prototype.getBranch=function(e){return this.branches[e]},e.prototype.getBothBranches=function(){return[this.getBranch("0"),this.getBranch("1")]},e.prototype.hasBranchAsNode=function(e){return this.getBranch("0")===e||this.getBranch("1")===e},e.prototype.hasNodeIdAsBranch=function(e){return this.getBranch("0").id===e||this.getBranch("1").id===e},e.prototype.areBranchesStrictEqual=function(){return this.branches[0]===this.branches[1]},e.prototype.hasEqualBranches=function(){return JSON.stringify(this.branches[0])===JSON.stringify(this.branches[1])},e}();r.Branches=n,r.ensureNodesNotStrictEqual=function(e,t){if(e===t)throw new Error("cannot have two strict equal branches")}},{}],94:[function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a};Object.defineProperty(r,"__esModule",{value:!0});var o=e("./root-node"),a=e("./util"),s=e("./internal-node"),u=e("./leaf-node");r.createBddFromTruthTable=function(e){var t,r,c=new o.RootNode,f=e.keys().next().value.length,l=Math.pow(2,f);if(e.size!==l)throw new Error("truth table has missing entries");try{for(var d=n(e),h=d.next();!h.done;h=d.next()){for(var p=i(h.value,2),b=p[0],v=p[1],m=c,y=0;yr.length){var u=s[0],c=r.find((function(e){return!!e.isInternalNode()&&e.branches.hasNodeIdAsBranch(u)}));console.log("referenceToFirst:"),null==c||c.log()}throw new Error("ensureCorrectBdd() nodes in list not equal size to recursive nodes allNodes: "+r.length+" recursiveNodes: "+o.size+" nodesOnlyInRecursive: "+s.join(", ")+" ")}if(r.forEach((function(e){if(!e.isRootNode()){var t=e;if(e.deleted)throw new Error("ensureCorrectBdd() bdd includes a deleted node");if(0===t.parents.size)throw new Error("ensureCorrectBdd() node has no parent "+t.id);if(t.isInternalNode()){var r=t,n=r.branches.getBothBranches();if(r.branches.areBranchesStrictEqual())throw new Error("ensureCorrectBdd() node has two equal branches: "+n.map((function(e){return e.id})).join(", "));n.forEach((function(e){if(!e.parents.has(r))throw new Error("ensureCorrectBdd() branch must have the node as parent")}))}t.parents.getAll().forEach((function(e){if(!e.branches.hasBranchAsNode(t))throw new Error("ensureCorrectBdd() parent node does not have child as branch")}))}})),t.includes('"deleted":true'))throw new Error("ensureCorrectBdd() bdd includes a deleted node")},r.getNodesRecursive=n},{}],96:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./util");r.fillTruthTable=function(e,t,r){for(var i=n.maxBinaryWithLength(t),o=n.minBinaryWithLength(t),a=!1;!a;)e.has(o)||e.set(o,r),o===i?a=!0:o=n.getNextStateSet(o)}},{"./util":110}],97:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.findSimilarNode=function(e,t){for(var r=e.toString(),n=0;n99)throw new Error("cannot build string with too many leaf nodes");t+=n.toString().padStart(2,"0");var a=e.levels.slice().reverse(),s=new Map;return a.forEach((function(n){e.getNodesOfLevel(n).forEach((function(e){var n=o(e,s,r);r=n.nextCode,s.set(e,n.id),t+=n.str}))})),t},r.nodeToString=o},{"./string-format":106}],102:[function(e,t,r){"use strict";function n(e){var t=e.branches.getBranch("0"),r=e.branches.getBranch("1");return{l:e.level,0:t.isLeafNode()?t.asLeafNode().value:n(t),1:r.isLeafNode()?r.asLeafNode().value:n(r)}}Object.defineProperty(r,"__esModule",{value:!0}),r.bddToSimpleBdd=function(e){return n(e)},r.nodeToSimpleBddNode=n},{}],103:[function(e,t,r){"use strict";function n(e){for(var t in e)r.hasOwnProperty(t)||(r[t]=e[t])}Object.defineProperty(r,"__esModule",{value:!0}),n(e("./bdd-to-minimal-string")),n(e("./minimal-string-to-simple-bdd")),n(e("./resolve-with-simple-bdd")),n(e("./string-format")),n(e("./bdd-to-simple-bdd"))},{"./bdd-to-minimal-string":101,"./bdd-to-simple-bdd":102,"./minimal-string-to-simple-bdd":104,"./resolve-with-simple-bdd":105,"./string-format":106}],104:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("../util"),i=e("./string-format");r.minimalStringToSimpleBdd=function(e){for(var t=new Map,r=2+2*parseInt(e.charAt(0)+e.charAt(1),10),o=e.substring(2,r),a=n.splitStringToChunks(o,2),s=0;s=128&&e<=160&&(e=161),{char:String.fromCharCode(e),nextCode:e+1}}},{}],107:[function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function a(e){try{u(n.next(e))}catch(e){o(e)}}function s(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}u((n=n.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var r,n,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a};Object.defineProperty(r,"__esModule",{value:!0});var s=e("./create-bdd-from-truth-table"),u=e("./util");function c(e){var t,r,n=l(u.firstKeyOfMap(e).length),i=u.shuffleArray(n),s={},c={};i.forEach((function(e,t){s[t]=e,c[e]=t}));var d=new Map;try{for(var h=o(e.entries()),p=h.next();!p.done;p=h.next()){var b=a(p.value,2),v=b[0],m=b[1],y=f(v,s);d.set(y,m)}}catch(e){t={error:e}}finally{try{p&&!p.done&&(r=h.return)&&r.call(h)}finally{if(t)throw t.error}}return{newTable:d,mapping:s,mappingBeforeToAfter:c}}function f(e,t){return e.split("").map((function(e,r){return{char:e,indexBefore:r,indexAfter:t[r]}})).sort((function(e,t){return e.indexAfter-t.indexAfter})).map((function(e){return e.char})).join("")}function l(e){for(var t=[],r=0;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function e(e){this.node=e,this.parents=new Set}return e.prototype.remove=function(e){this.parents.delete(e),0===this.parents.size&&this.node.remove()},e.prototype.getAll=function(){return Array.from(this.parents)},e.prototype.add=function(e){if(this.node.level===e.level)throw new Error("a node cannot be parent of a node with the same level");this.parents.add(e)},e.prototype.has=function(e){return this.parents.has(e)},e.prototype.toString=function(){var e,t,r=[];try{for(var i=n(this.parents),o=i.next();!o.done;o=i.next()){var a=o.value;r.push(a.id)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return r.join(", ")},Object.defineProperty(e.prototype,"size",{get:function(){return this.parents.size},enumerable:!0,configurable:!0}),e}();r.Parents=i},{}],109:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var a=e("./abstract-node"),s=e("./branches"),u=e("./util"),c=e("./minimal-string"),f=function(e){function t(){var t=e.call(this,0,null,"RootNode")||this;t.branches=new s.Branches(t),t.levels=[],t.nodesByLevel=new Map,t.levels.push(0);var r=new Set;return r.add(t),t.nodesByLevel.set(0,r),t}return i(t,e),t.prototype.addNode=function(e){var t=e.level;this.levels.includes(t)||this.levels.push(t),this.ensureLevelSetExists(t);var r=this.nodesByLevel.get(t);null==r||r.add(e)},t.prototype.removeNode=function(e){var t=this.nodesByLevel.get(e.level);if(!t.has(e))throw new Error("removed non-existing node "+e.id);t.delete(e)},t.prototype.ensureLevelSetExists=function(e){this.nodesByLevel.has(e)||this.nodesByLevel.set(e,new Set)},t.prototype.getLevels=function(){return Array.from(this.levels).sort((function(e,t){return e-t}))},t.prototype.getNodesOfLevel=function(e){this.ensureLevelSetExists(e);var t=this.nodesByLevel.get(e);return Array.from(t)},t.prototype.countNodes=function(){var e=this,t=0;return this.getLevels().forEach((function(r){var n=e.getNodesOfLevel(r).length;t+=n})),t},t.prototype.minimize=function(e){var t,r;void 0===e&&(e=!1);for(var n=!1;!n;){e&&console.log("minimize() itterate once");for(var i=0,a=u.lastOfArray(this.getLevels());a>0;){var s=this.getNodesOfLevel(a);e&&console.log("minimize() run for level "+a+" with "+s.length+" nodes");var c=0;try{for(var f=(t=void 0,o(s)),l=f.next();!l.done;l=f.next()){var d=l.value;if(c++,e&&c%4e3==0&&console.log("minimize() node #"+d.id),d.isLeafNode())(p=d.asLeafNode().applyEliminationRule())&&i++;if(!d.deleted&&d.isInternalNode()){var h=d,p=h.applyReductionRule(),b=!1;h.deleted||(b=h.applyEliminationRule(s)),(p||b)&&i++}}}catch(e){t={error:e}}finally{try{l&&!l.done&&(r=f.return)&&r.call(f)}finally{if(t)throw t.error}}a--}0===i?n=!0:e&&console.log("minimize() itteration done with "+i+" minimisations")}},t.prototype.getLeafNodes=function(){var e=u.lastOfArray(this.getLevels());return this.getNodesOfLevel(e).reverse()},t.prototype.removeIrrelevantLeafNodes=function(e){for(var t,r,n=!1;!n;){var i=0,a=this.getLeafNodes();try{for(var s=(t=void 0,o(a)),u=s.next();!u.done;u=s.next()){u.value.removeIfValueEquals(e)&&i++}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}this.minimize(),0===i&&(n=!0)}},t.prototype.resolve=function(e,t){for(var r=this;;){var n=e[r.level](t),i=u.booleanToBooleanString(n);if((r=r.branches.getBranch(i)).isLeafNode())return r.asLeafNode().value}},t.prototype.toSimpleBdd=function(){return c.bddToSimpleBdd(this)},t}(a.AbstractNode);r.RootNode=f},{"./abstract-node":92,"./branches":93,"./minimal-string":103,"./util":110}],110:[function(e,t,r){"use strict";var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a};Object.defineProperty(r,"__esModule",{value:!0}),r.booleanStringToBoolean=function(e){return"1"===e},r.booleanToBooleanString=function(e){return e?"1":"0"},r.oppositeBoolean=function(e){return"1"===e?"0":"1"},r.lastChar=function(e){return e.slice(-1)};var i=function(e){void 0===e&&(e=6);for(var t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;i>>0).toString(2).padStart(t,"0")}function s(e){return parseInt(e,2)}r.nextNodeId=function(){var e="node_"+i+"_"+o;return o++,e},r.decimalToPaddedBinary=a,r.oppositeBinary=function(e){if("1"===e)return"0";if("0"===e)return"1";throw new Error("non-binary given")},r.binaryToDecimal=s,r.minBinaryWithLength=function(e){return new Array(e).fill(0).map((function(){return"0"})).join("")},r.maxBinaryWithLength=function(e){return new Array(e).fill(0).map((function(){return"1"})).join("")},r.getNextStateSet=function(e){return a(s(e)+1,e.length)},r.firstKeyOfMap=function(e){return e.keys().next().value},r.shuffleArray=function(e){for(var t,r=e.length-1;r>0;r--){var i=Math.floor(Math.random()*(r+1));t=n([e[i],e[r]],2),e[r]=t[0],e[i]=t[1]}return e},r.lastOfArray=function(e){return e[e.length-1]},r.splitStringToChunks=function(e,t){for(var r=[],n=0,i=e.length;n=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function u(e,t,r){var n=s(e,r);return r-1>=t&&(n|=s(e,r-1)<<4),n}function c(e,t,r,i){for(var o=0,a=0,s=Math.min(e.length,r),u=t;u=49?c-49+10:c>=17?c-17+10:c,n(c>=0&&a0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this._strip()},o.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)i=u(e,t,n)<=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;this._strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,u=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(e){o.prototype.inspect=l}else o.prototype.inspect=l;function l(){return(this.red?""}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?d[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var c=h[e],f=p[e];r="";var l=this.clone();for(l.negative=0;!l.isZero();){var b=l.modrn(f).toString(e);r=(l=l.idivn(f)).isZero()?b+r:d[c-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},a&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(a,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function b(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,l=67108863&u,d=Math.min(c,t.length-1),h=Math.max(0,c-e.length+1);h<=d;h++){var p=c-h|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[h])+l)/67108864|0,l=67108863&a}r.words[c]=0|l,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r._strip()}o.prototype.toArrayLike=function(e,t,r){this._strip();var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var a=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](a,i),a},o.prototype._toArrayLikeLE=function(e,t){for(var r=0,n=0,i=0,o=0;i>8&255),r>16&255),6===o?(r>24&255),n=0,o=0):(n=a>>>24,o+=2)}if(r=0&&(e[r--]=a>>8&255),r>=0&&(e[r--]=a>>16&255),6===o?(r>=0&&(e[r--]=a>>24&255),n=0,o=0):(n=a>>>24,o+=2)}if(r>=0)for(e[r--]=n;r>=0;)e[r--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,h=0|a[1],p=8191&h,b=h>>>13,v=0|a[2],m=8191&v,y=v>>>13,g=0|a[3],_=8191&g,w=g>>>13,S=0|a[4],x=8191&S,O=S>>>13,j=0|a[5],E=8191&j,M=j>>>13,k=0|a[6],A=8191&k,P=k>>>13,R=0|a[7],C=8191&R,I=R>>>13,D=0|a[8],T=8191&D,B=D>>>13,N=0|a[9],L=8191&N,F=N>>>13,q=0|s[0],U=8191&q,z=q>>>13,W=0|s[1],$=8191&W,H=W>>>13,K=0|s[2],V=8191&K,G=K>>>13,Q=0|s[3],J=8191&Q,Y=Q>>>13,X=0|s[4],Z=8191&X,ee=X>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],le=8191&fe,de=fe>>>13,he=0|s[9],pe=8191&he,be=he>>>13;r.negative=e.negative^t.negative,r.length=19;var ve=(c+(n=Math.imul(l,U))|0)+((8191&(i=(i=Math.imul(l,z))+Math.imul(d,U)|0))<<13)|0;c=((o=Math.imul(d,z))+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,U),i=(i=Math.imul(p,z))+Math.imul(b,U)|0,o=Math.imul(b,z);var me=(c+(n=n+Math.imul(l,$)|0)|0)+((8191&(i=(i=i+Math.imul(l,H)|0)+Math.imul(d,$)|0))<<13)|0;c=((o=o+Math.imul(d,H)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,U),i=(i=Math.imul(m,z))+Math.imul(y,U)|0,o=Math.imul(y,z),n=n+Math.imul(p,$)|0,i=(i=i+Math.imul(p,H)|0)+Math.imul(b,$)|0,o=o+Math.imul(b,H)|0;var ye=(c+(n=n+Math.imul(l,V)|0)|0)+((8191&(i=(i=i+Math.imul(l,G)|0)+Math.imul(d,V)|0))<<13)|0;c=((o=o+Math.imul(d,G)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(_,U),i=(i=Math.imul(_,z))+Math.imul(w,U)|0,o=Math.imul(w,z),n=n+Math.imul(m,$)|0,i=(i=i+Math.imul(m,H)|0)+Math.imul(y,$)|0,o=o+Math.imul(y,H)|0,n=n+Math.imul(p,V)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(b,V)|0,o=o+Math.imul(b,G)|0;var ge=(c+(n=n+Math.imul(l,J)|0)|0)+((8191&(i=(i=i+Math.imul(l,Y)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,Y)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(x,U),i=(i=Math.imul(x,z))+Math.imul(O,U)|0,o=Math.imul(O,z),n=n+Math.imul(_,$)|0,i=(i=i+Math.imul(_,H)|0)+Math.imul(w,$)|0,o=o+Math.imul(w,H)|0,n=n+Math.imul(m,V)|0,i=(i=i+Math.imul(m,G)|0)+Math.imul(y,V)|0,o=o+Math.imul(y,G)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,Y)|0;var _e=(c+(n=n+Math.imul(l,Z)|0)|0)+((8191&(i=(i=i+Math.imul(l,ee)|0)+Math.imul(d,Z)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(E,U),i=(i=Math.imul(E,z))+Math.imul(M,U)|0,o=Math.imul(M,z),n=n+Math.imul(x,$)|0,i=(i=i+Math.imul(x,H)|0)+Math.imul(O,$)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(_,V)|0,i=(i=i+Math.imul(_,G)|0)+Math.imul(w,V)|0,o=o+Math.imul(w,G)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(y,J)|0,o=o+Math.imul(y,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,ee)|0;var we=(c+(n=n+Math.imul(l,re)|0)|0)+((8191&(i=(i=i+Math.imul(l,ne)|0)+Math.imul(d,re)|0))<<13)|0;c=((o=o+Math.imul(d,ne)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(A,U),i=(i=Math.imul(A,z))+Math.imul(P,U)|0,o=Math.imul(P,z),n=n+Math.imul(E,$)|0,i=(i=i+Math.imul(E,H)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(x,V)|0,i=(i=i+Math.imul(x,G)|0)+Math.imul(O,V)|0,o=o+Math.imul(O,G)|0,n=n+Math.imul(_,J)|0,i=(i=i+Math.imul(_,Y)|0)+Math.imul(w,J)|0,o=o+Math.imul(w,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Se=(c+(n=n+Math.imul(l,oe)|0)|0)+((8191&(i=(i=i+Math.imul(l,ae)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,ae)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(C,U),i=(i=Math.imul(C,z))+Math.imul(I,U)|0,o=Math.imul(I,z),n=n+Math.imul(A,$)|0,i=(i=i+Math.imul(A,H)|0)+Math.imul(P,$)|0,o=o+Math.imul(P,H)|0,n=n+Math.imul(E,V)|0,i=(i=i+Math.imul(E,G)|0)+Math.imul(M,V)|0,o=o+Math.imul(M,G)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,Y)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Y)|0,n=n+Math.imul(_,Z)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(y,re)|0,o=o+Math.imul(y,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var xe=(c+(n=n+Math.imul(l,ue)|0)|0)+((8191&(i=(i=i+Math.imul(l,ce)|0)+Math.imul(d,ue)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(T,U),i=(i=Math.imul(T,z))+Math.imul(B,U)|0,o=Math.imul(B,z),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,H)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,H)|0,n=n+Math.imul(A,V)|0,i=(i=i+Math.imul(A,G)|0)+Math.imul(P,V)|0,o=o+Math.imul(P,G)|0,n=n+Math.imul(E,J)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(x,Z)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(_,re)|0,i=(i=i+Math.imul(_,ne)|0)+Math.imul(w,re)|0,o=o+Math.imul(w,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(y,oe)|0,o=o+Math.imul(y,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var Oe=(c+(n=n+Math.imul(l,le)|0)|0)+((8191&(i=(i=i+Math.imul(l,de)|0)+Math.imul(d,le)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(L,U),i=(i=Math.imul(L,z))+Math.imul(F,U)|0,o=Math.imul(F,z),n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,H)|0)+Math.imul(B,$)|0,o=o+Math.imul(B,H)|0,n=n+Math.imul(C,V)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(I,V)|0,o=o+Math.imul(I,G)|0,n=n+Math.imul(A,J)|0,i=(i=i+Math.imul(A,Y)|0)+Math.imul(P,J)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(x,re)|0,i=(i=i+Math.imul(x,ne)|0)+Math.imul(O,re)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(_,oe)|0,i=(i=i+Math.imul(_,ae)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(y,ue)|0,o=o+Math.imul(y,ce)|0,n=n+Math.imul(p,le)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(b,le)|0,o=o+Math.imul(b,de)|0;var je=(c+(n=n+Math.imul(l,pe)|0)|0)+((8191&(i=(i=i+Math.imul(l,be)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(L,$),i=(i=Math.imul(L,H))+Math.imul(F,$)|0,o=Math.imul(F,H),n=n+Math.imul(T,V)|0,i=(i=i+Math.imul(T,G)|0)+Math.imul(B,V)|0,o=o+Math.imul(B,G)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,Y)|0)+Math.imul(I,J)|0,o=o+Math.imul(I,Y)|0,n=n+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,ee)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,ae)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,ae)|0,n=n+Math.imul(_,ue)|0,i=(i=i+Math.imul(_,ce)|0)+Math.imul(w,ue)|0,o=o+Math.imul(w,ce)|0,n=n+Math.imul(m,le)|0,i=(i=i+Math.imul(m,de)|0)+Math.imul(y,le)|0,o=o+Math.imul(y,de)|0;var Ee=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(L,V),i=(i=Math.imul(L,G))+Math.imul(F,V)|0,o=Math.imul(F,G),n=n+Math.imul(T,J)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(B,J)|0,o=o+Math.imul(B,Y)|0,n=n+Math.imul(C,Z)|0,i=(i=i+Math.imul(C,ee)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,ee)|0,n=n+Math.imul(A,re)|0,i=(i=i+Math.imul(A,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,ce)|0,n=n+Math.imul(_,le)|0,i=(i=i+Math.imul(_,de)|0)+Math.imul(w,le)|0,o=o+Math.imul(w,de)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(y,pe)|0))<<13)|0;c=((o=o+Math.imul(y,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(L,J),i=(i=Math.imul(L,Y))+Math.imul(F,J)|0,o=Math.imul(F,Y),n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(B,Z)|0,o=o+Math.imul(B,ee)|0,n=n+Math.imul(C,re)|0,i=(i=i+Math.imul(C,ne)|0)+Math.imul(I,re)|0,o=o+Math.imul(I,ne)|0,n=n+Math.imul(A,oe)|0,i=(i=i+Math.imul(A,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(x,le)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(O,le)|0,o=o+Math.imul(O,de)|0;var ke=(c+(n=n+Math.imul(_,pe)|0)|0)+((8191&(i=(i=i+Math.imul(_,be)|0)+Math.imul(w,pe)|0))<<13)|0;c=((o=o+Math.imul(w,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(L,Z),i=(i=Math.imul(L,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(B,re)|0,o=o+Math.imul(B,ne)|0,n=n+Math.imul(C,oe)|0,i=(i=i+Math.imul(C,ae)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,ae)|0,n=n+Math.imul(A,ue)|0,i=(i=i+Math.imul(A,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(E,le)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,le)|0,o=o+Math.imul(M,de)|0;var Ae=(c+(n=n+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,be)|0)+Math.imul(O,pe)|0))<<13)|0;c=((o=o+Math.imul(O,be)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(L,re),i=(i=Math.imul(L,ne))+Math.imul(F,re)|0,o=Math.imul(F,ne),n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(B,oe)|0,o=o+Math.imul(B,ae)|0,n=n+Math.imul(C,ue)|0,i=(i=i+Math.imul(C,ce)|0)+Math.imul(I,ue)|0,o=o+Math.imul(I,ce)|0,n=n+Math.imul(A,le)|0,i=(i=i+Math.imul(A,de)|0)+Math.imul(P,le)|0,o=o+Math.imul(P,de)|0;var Pe=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(L,oe),i=(i=Math.imul(L,ae))+Math.imul(F,oe)|0,o=Math.imul(F,ae),n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(B,ue)|0,o=o+Math.imul(B,ce)|0,n=n+Math.imul(C,le)|0,i=(i=i+Math.imul(C,de)|0)+Math.imul(I,le)|0,o=o+Math.imul(I,de)|0;var Re=(c+(n=n+Math.imul(A,pe)|0)|0)+((8191&(i=(i=i+Math.imul(A,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(L,ue),i=(i=Math.imul(L,ce))+Math.imul(F,ue)|0,o=Math.imul(F,ce),n=n+Math.imul(T,le)|0,i=(i=i+Math.imul(T,de)|0)+Math.imul(B,le)|0,o=o+Math.imul(B,de)|0;var Ce=(c+(n=n+Math.imul(C,pe)|0)|0)+((8191&(i=(i=i+Math.imul(C,be)|0)+Math.imul(I,pe)|0))<<13)|0;c=((o=o+Math.imul(I,be)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(L,le),i=(i=Math.imul(L,de))+Math.imul(F,le)|0,o=Math.imul(F,de);var Ie=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(B,pe)|0))<<13)|0;c=((o=o+Math.imul(B,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863;var De=(c+(n=Math.imul(L,pe))|0)+((8191&(i=(i=Math.imul(L,be))+Math.imul(F,pe)|0))<<13)|0;return c=((o=Math.imul(F,be))+(i>>>13)|0)+(De>>>26)|0,De&=67108863,u[0]=ve,u[1]=me,u[2]=ye,u[3]=ge,u[4]=_e,u[5]=we,u[6]=Se,u[7]=xe,u[8]=Oe,u[9]=je,u[10]=Ee,u[11]=Me,u[12]=ke,u[13]=Ae,u[14]=Pe,u[15]=Re,u[16]=Ce,u[17]=Ie,u[18]=De,0!==c&&(u[19]=c,r.length++),r};function m(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r._strip()}function y(e,t,r){return m(e,t,r)}function g(e,t){this.x=e,this.y=t}Math.imul||(v=b),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?v(this,e,t):r<63?b(this,e,t):r<1024?m(this,e,t):y(this,e,t)},g.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},g.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,r+=o/67108864|0,r+=a>>>26,this.words[i]=67108863&a}return 0!==r&&(this.words[i]=r,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i&1}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var l=0|this.words[c];this.words[c]=f<<26-o|l>>>o,f=l&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this._strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;l--){var d=67108864*(0|n.words[i.length+l])+(0|n.words[i.length+l-1]);for(d=Math.min(d/a|0,67108863),n._ishlnsubmul(i,d,l);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(i,1,l),n.isZero()||(n.negative^=1);s&&(s.words[l]=d)}return s&&s._strip(),n._strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(r*i+(0|this.words[o]))%e;return t?-i:i},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var o=(0|this.words[i])+67108864*r;this.words[i]=o/e|0,r=o%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),l=t.clone();!t.isZero();){for(var d=0,h=1;0==(t.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(l)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(l)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var l=0,d=1;0==(r.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(r.iushrn(l);l-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new E(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var _={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function S(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function x(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function O(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function j(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function M(e){E.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},i(S,w),S.prototype.split=function(e,t){for(var r=4194303,n=Math.min(e.length,9),i=0;i>>22,o=a}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},S.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(_[e])return _[e];var t;if("k256"===e)t=new S;else if("p224"===e)t=new x;else if("p192"===e)t=new O;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new j}return _[e]=t,t},E.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},E.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(f(e,e.umod(this.m)._forceRed(this)),e)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var l=this.pow(f,i),d=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=a;0!==h.cmp(s);){for(var b=h,v=0;0!==b.cmp(s);v++)b=b.redSqr();n(v=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var l=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==l||0!==a?(a<<=1,a|=l,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new M(e)},i(M,E),M.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},M.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},M.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},M.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},M.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:125}],112:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.clearNodeFolder=function(e){e=(0,a.fillOptionsWithDefaults)(e);var t=(0,o.chooseMethod)(e);return"node"===t.type?t.clearNodeFolder().then((function(){return!0})):Promise.resolve(!1)},r.enforceOptions=function(e){n=e},r.BroadcastChannel=void 0;var n,i=e("./util.js"),o=e("./method-chooser.js"),a=e("./options.js"),s=function(e,t){var r,s;this.name=e,n&&(t=n),this.options=(0,a.fillOptionsWithDefaults)(t),this.method=(0,o.chooseMethod)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,s=(r=this).method.create(r.name,r.options),(0,i.isPromise)(s)?(r._prepP=s,s.then((function(e){r._state=e}))):r._state=s};function u(e,t,r){var n={time:e.method.microSeconds(),type:t,data:r};return(e._prepP?e._prepP:Promise.resolve()).then((function(){var t=e.method.postMessage(e._state,n);return e._uMP.add(t),t.catch().then((function(){return e._uMP.delete(t)})),t}))}function c(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function f(e,t,r){e._addEL[t].push(r),function(e){if(!e._iL&&c(e)){var t=function(t){e._addEL[t.type].forEach((function(e){t.time>=e.time&&e.fn(t.data)}))},r=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,r)})):(e._iL=!0,e.method.onMessage(e._state,t,r))}}(e)}function l(e,t,r){e._addEL[t]=e._addEL[t].filter((function(e){return e!==r})),function(e){if(e._iL&&!c(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}r.BroadcastChannel=s,s._pubkey=!0,s.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return u(this,"message",e)},postInternal:function(e){return u(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};l(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,f(this,"message",t)):this._onML=null},addEventListener:function(e,t){f(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){l(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}}},{"./method-chooser.js":116,"./options.js":122,"./util.js":123}],113:[function(e,t,r){"use strict";var n=e("./index.js");t.exports={BroadcastChannel:n.BroadcastChannel,createLeaderElection:n.createLeaderElection,clearNodeFolder:n.clearNodeFolder,enforceOptions:n.enforceOptions,beLeader:n.beLeader}},{"./index.js":114}],114:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"BroadcastChannel",{enumerable:!0,get:function(){return n.BroadcastChannel}}),Object.defineProperty(r,"clearNodeFolder",{enumerable:!0,get:function(){return n.clearNodeFolder}}),Object.defineProperty(r,"enforceOptions",{enumerable:!0,get:function(){return n.enforceOptions}}),Object.defineProperty(r,"createLeaderElection",{enumerable:!0,get:function(){return i.createLeaderElection}}),Object.defineProperty(r,"beLeader",{enumerable:!0,get:function(){return i.beLeader}});var n=e("./broadcast-channel"),i=e("./leader-election")},{"./broadcast-channel":112,"./leader-election":115}],115:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.beLeader=u,r.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e||(e={});(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var r=new a(e,t);return e._befC.push((function(){return r.die()})),e._leaderElector=r,r};var i=e("./util.js"),o=n(e("unload")),a=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[],this._dpL=function(){},this._dpLC=!1};function s(e,t){var r={context:"leader",action:t,token:e.token};return e._channel.postInternal(r)}function u(e){e.isLeader=!0;var t=o.default.add((function(){return e.die()}));e._unl.push(t);var r=function(t){"leader"===t.context&&"apply"===t.action&&s(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),s(e,"tell"))};return e._channel.addEventListener("internal",r),e._lstns.push(r),s(e,"tell")}a.prototype={applyOnce:function(){var e=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);this._isApl=!0;var t=!1,r=[],n=function(n){"leader"===n.context&&n.token!=e.token&&(r.push(n),"apply"===n.action&&n.token>e.token&&(t=!0),"tell"===n.action&&(t=!0))};return this._channel.addEventListener("internal",n),s(this,"apply").then((function(){return(0,i.sleep)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):s(e,"apply")})).then((function(){return(0,i.sleep)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):s(e)})).then((function(){return u(e)})).then((function(){return!0})).catch((function(){return!1})).then((function(t){return e._channel.removeEventListener("internal",n),e._isApl=!1,!t&&e._reApply?(e._reApply=!1,e.applyOnce()):t}))},awaitLeadership:function(){var e;return this._aLP||(this._aLP=(e=this).isLeader?Promise.resolve():new Promise((function(t){var r=!1;function n(){r||(r=!0,clearInterval(i),e._channel.removeEventListener("internal",o),t(!0))}e.applyOnce().then((function(){e.isLeader&&n()}));var i=setInterval((function(){e.applyOnce().then((function(){e.isLeader&&n()}))}),e._options.fallbackInterval);e._invs.push(i);var o=function(t){"leader"===t.context&&"death"===t.action&&e.applyOnce().then((function(){e.isLeader&&n()}))};e._channel.addEventListener("internal",o),e._lstns.push(o)}))),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach((function(t){return e._channel.removeEventListener("internal",t)})),this._invs.forEach((function(e){return clearInterval(e)})),this._unl.forEach((function(e){e.remove()})),s(this,"death")}}},{"./util.js":123,"@babel/runtime/helpers/interopRequireDefault":67,unload:938}],116:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.chooseMethod=function(e){var t=[].concat(e.methods,c).filter(Boolean);if(e.type){if("simulate"===e.type)return s.default;var r=t.find((function(t){return t.type===e.type}));if(r)return r;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||u.isNode||(t=t.filter((function(e){return"idb"!==e.type})));var n=t.find((function(e){return e.canBeUsed()}));if(n)return n;throw new Error("No useable methode found:"+JSON.stringify(c.map((function(e){return e.type}))))};var i=n(e("./methods/native.js")),o=n(e("./methods/indexed-db.js")),a=n(e("./methods/localstorage.js")),s=n(e("./methods/simulate.js")),u=e("./util"),c=[i.default,o.default,a.default];if(u.isNode){var f=e("../../src/methods/node.js");"function"==typeof f.canBeUsed&&c.push(f)}},{"./methods/indexed-db.js":117,"./methods/localstorage.js":118,"./methods/native.js":119,"./methods/simulate.js":120,"./util":123,"@babel/runtime/helpers/interopRequireDefault":67}],117:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.getIdb=c,r.createDatabase=f,r.writeMessage=l,r.getAllMessages=function(e){var t=e.transaction(u).objectStore(u),r=[];return new Promise((function(e){t.openCursor().onsuccess=function(t){var n=t.target.result;n?(r.push(n.value),n.continue()):e(r)}}))},r.getMessagesHigherThan=d,r.removeMessageById=h,r.getOldMessages=p,r.cleanOldMessages=b,r.create=v,r.close=g,r.postMessage=_,r.onMessage=w,r.canBeUsed=S,r.averageResponseTime=x,r.default=r.type=r.microSeconds=void 0;var i=e("../util.js"),o=n(e("../oblivious-set")),a=e("../options"),s=i.microSeconds;r.microSeconds=s;var u="messages";function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function f(e){var t="pubkey.broadcast-channel-0-"+e,r=c().open(t,1);return r.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise((function(e,t){r.onerror=function(e){return t(e)},r.onsuccess=function(){e(r.result)}}))}function l(e,t,r){var n={uuid:t,time:(new Date).getTime(),data:r},i=e.transaction([u],"readwrite");return new Promise((function(e,t){i.oncomplete=function(){return e()},i.onerror=function(e){return t(e)},i.objectStore(u).add(n)}))}function d(e,t){var r=e.transaction(u).objectStore(u),n=[];return new Promise((function(e){(function(){try{var e=IDBKeyRange.bound(t+1,1/0);return r.openCursor(e)}catch(e){return r.openCursor()}}()).onsuccess=function(r){var i=r.target.result;i?i.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return!(e.uuid===t.uuid||t.eMIs.has(e.id)||e.data.time0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0);t.idb||(t.idb={});t.idb.ttl||(t.idb.ttl=45e3);t.idb.fallbackInterval||(t.idb.fallbackInterval=150);e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose);t.localstorage||(t.localstorage={});t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4);e.methods&&(t.methods=e.methods);t.node||(t.node={});t.node.ttl||(t.node.ttl=12e4);void 0===t.node.useFastPath&&(t.node.useFastPath=!0);return t}},{}],123:[function(e,t,r){(function(e){(function(){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.isPromise=function(e){return!(!e||"function"!=typeof e.then)},r.sleep=function(e){e||(e=0);return new Promise((function(t){return setTimeout(t,e)}))},r.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},r.randomToken=function(){return Math.random().toString(36).substring(2)},r.microSeconds=function(){var e=(new Date).getTime();return e===t?(n++,1e3*e+n):(t=e,n=0,1e3*e)},r.isNode=void 0;var t=0,n=0;var i="[object process]"===Object.prototype.toString.call(void 0!==e?e:0);r.isNode=i}).call(this)}).call(this,e("_process"))},{_process:667}],124:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r>>24]^f[p>>>16&255]^l[b>>>8&255]^d[255&v]^t[m++],a=c[p>>>24]^f[b>>>16&255]^l[v>>>8&255]^d[255&h]^t[m++],s=c[b>>>24]^f[v>>>16&255]^l[h>>>8&255]^d[255&p]^t[m++],u=c[v>>>24]^f[h>>>16&255]^l[p>>>8&255]^d[255&b]^t[m++],h=o,p=a,b=s,v=u;return o=(n[h>>>24]<<24|n[p>>>16&255]<<16|n[b>>>8&255]<<8|n[255&v])^t[m++],a=(n[p>>>24]<<24|n[b>>>16&255]<<16|n[v>>>8&255]<<8|n[255&h])^t[m++],s=(n[b>>>24]<<24|n[v>>>16&255]<<16|n[h>>>8&255]<<8|n[255&p])^t[m++],u=(n[v>>>24]<<24|n[h>>>16&255]<<16|n[p>>>8&255]<<8|n[255&b])^t[m++],[o>>>=0,a>>>=0,s>>>=0,u>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,u=0;u<256;++u){var c=s^s<<1^s<<2^s<<3^s<<4;c=c>>>8^255&c^99,r[a]=c,n[c]=a;var f=e[a],l=e[f],d=e[l],h=257*e[c]^16843008*c;i[0][a]=h<<24|h>>>8,i[1][a]=h<<16|h>>>16,i[2][a]=h<<8|h>>>24,i[3][a]=h,h=16843009*d^65537*l^257*f^16843008*a,o[0][c]=h<<24|h>>>8,o[1][c]=h<<16|h>>>16,o[2][c]=h<<8|h>>>24,o[3][c]=h,0===a?a=s=1:(a=f^e[e[e[d^f]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a]),i[o]=i[o-t]^a}for(var c=[],f=0;f>>24]]^u.INV_SUB_MIX[1][u.SBOX[d>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[d>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&d]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=c},{"safe-buffer":909}],127:[function(e,t,r){var n=e("./aes"),i=e("safe-buffer").Buffer,o=e("cipher-base"),a=e("inherits"),s=e("./ghash"),u=e("buffer-xor"),c=e("./incr32");function f(e,t,r,a){o.call(this);var u=i.alloc(4,0);this._cipher=new n.AES(t);var f=this._cipher.encryptBlock(u);this._ghash=new s(f),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var u=8*o,f=i.alloc(8);f.writeUIntBE(u,0,8),n.update(f),e._finID=n.state;var l=i.from(e._finID);return c(l),l}(this,r,f),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(f,o),f.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},f.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=u(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i16)throw new Error("unable to decrypt data");var r=-1;for(;++r16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},l.prototype.flush=function(){if(this.cache.length)return this.cache},r.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=c(t,!1,r.key,r.iv);return d(e,n.key,n.iv)},r.createDecipheriv=d},{"./aes":126,"./authCipher":127,"./modes":139,"./streamCipher":142,"cipher-base":173,evp_bytestokey:539,inherits:586,"safe-buffer":909}],130:[function(e,t,r){var n=e("./modes"),i=e("./authCipher"),o=e("safe-buffer").Buffer,a=e("./streamCipher"),s=e("cipher-base"),u=e("./aes"),c=e("evp_bytestokey");function f(e,t,r){s.call(this),this._cache=new d,this._cipher=new u.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}e("inherits")(f,s),f.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var l=o.alloc(16,16);function d(){this.cache=o.allocUnsafe(0)}function h(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new f(s.module,t,r)}f.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(l))throw this._cipher.scrub(),new Error("data not multiple of block length")},f.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},d.prototype.add=function(e){this.cache=o.concat([this.cache,e])},d.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},d.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":909}],132:[function(e,t,r){t.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},{}],133:[function(e,t,r){var n=e("buffer-xor");r.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},r.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},{"buffer-xor":169}],134:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("buffer-xor");function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}r.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},{"buffer-xor":169,"safe-buffer":909}],135:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}r.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function a(e,t){var i=function(e){var t=o(e);return{blinder:t.toRed(n.mont(e.modulus)).redPow(new n(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(t),a=t.modulus.byteLength(),s=new n(e).mul(i.blinder).umod(t.modulus),u=s.toRed(n.mont(t.prime1)),c=s.toRed(n.mont(t.prime2)),f=t.coefficient,l=t.prime1,d=t.prime2,h=u.redPow(t.exponent1).fromRed(),p=c.redPow(t.exponent2).fromRed(),b=h.isub(p).imul(f).umod(l).imul(d);return p.iadd(b).imul(i.unblinder).umod(t.modulus).toArrayLike(r,"be",a)}a.getr=o,t.exports=a}).call(this)}).call(this,e("buffer").Buffer)},{"bn.js":111,buffer:170,randombytes:676}],147:[function(e,t,r){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":148}],148:[function(e,t,r){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],149:[function(e,t,r){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],150:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("create-hash"),o=e("readable-stream"),a=e("inherits"),s=e("./sign"),u=e("./verify"),c=e("./algorithms.json");function f(e){o.Writable.call(this);var t=c[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function l(e){o.Writable.call(this);var t=c[e];if(!t)throw new Error("Unknown message digest");this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function d(e){return new f(e)}function h(e){return new l(e)}Object.keys(c).forEach((function(e){c[e].id=n.from(c[e].id,"hex"),c[e.toLowerCase()]=c[e]})),a(f,o.Writable),f.prototype._write=function(e,t,r){this._hash.update(e),r()},f.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},f.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=s(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},a(l,o.Writable),l.prototype._write=function(e,t,r){this._hash.update(e),r()},l.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},l.prototype.verify=function(e,t,r){"string"==typeof t&&(t=n.from(t,r)),this.end();var i=this._hash.digest();return u(t,i,e,this._signType,this._tag)},t.exports={Sign:d,Verify:h,createSign:d,createVerify:h}},{"./algorithms.json":148,"./sign":151,"./verify":152,"create-hash":481,inherits:586,"readable-stream":167,"safe-buffer":168}],151:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("create-hmac"),o=e("browserify-rsa"),a=e("elliptic").ec,s=e("bn.js"),u=e("parse-asn1"),c=e("./curves.json");function f(e,t,r,o){if((e=n.from(e.toArray())).length0&&r.ishrn(n),r}function d(e,t,r){var o,a;do{for(o=n.alloc(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,r,c,f){var l=a(r);if("ec"===l.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=s[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var i=new o(n),a=r.data.subjectPrivateKey.data;return i.verify(t,e,a)}(e,t,l)}if("dsa"===l.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=r.data.p,o=r.data.q,s=r.data.g,c=r.data.pub_key,f=a.signature.decode(e,"der"),l=f.s,d=f.r;u(l,o),u(d,o);var h=i.mont(n),p=l.invm(o);return 0===s.toRed(h).redPow(new i(t).mul(p).mod(o)).fromRed().mul(c.toRed(h).redPow(d.mul(p).mod(o)).fromRed()).mod(n).mod(o).cmp(d)}(e,t,l)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=n.concat([f,t]);for(var d=l.modulus.byteLength(),h=[1],p=0;t.length+h.length+22?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}i("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),i("ERR_INVALID_ARG_TYPE",(function(e,t,r){var n,i,a,s;if("string"==typeof t&&(i="not ",t.substr(!a||a<0?0:+a,i.length)===i)?(n="must not be",t=t.replace(/^not /,"")):n="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))s="The ".concat(e," ").concat(n," ").concat(o(t,"type"));else{var u=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(u," ").concat(n," ").concat(o(t,"type"))}return s+=". Received type ".concat(typeof r)}),TypeError),i("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),i("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),i("ERR_STREAM_PREMATURE_CLOSE","Premature close"),i("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),i("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),i("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),i("ERR_STREAM_WRITE_AFTER_END","write after end"),i("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),i("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=n},{}],154:[function(e,t,r){(function(r){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=c;var i=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(c,i);for(var a=n(o.prototype),s=0;s0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===s.prototype||(t=function(e){return s.from(e)}(t)),n)a.endEmitted?S(e,new w):M(e,a,t,!0);else if(a.ended)S(e,new g);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?M(e,a,t,!1):C(e,a)):M(e,a,t,!1)}else n||(a.reading=!1,C(e,a));return!a.ended&&(a.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function P(e){var t=e._readableState;c("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(c("emitReadable",t.flowing),t.emittedReadable=!0,r.nextTick(R,e))}function R(e){var t=e._readableState;c("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,N(e)}function C(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(I,e,t))}function I(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function T(e){c("readable nexttick read 0"),e.read(0)}function B(e,t){c("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),N(e),t.flowing&&!t.reading&&e.read(0)}function N(e){var t=e._readableState;for(c("flow",t.flowing);t.flowing&&null!==e.read(););}function L(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function F(e){var t=e._readableState;c("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,r.nextTick(q,t,e))}function q(e,t){if(c("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function U(e,t){for(var r=0,n=e.length;r=t.highWaterMark:t.length>0)||t.ended))return c("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?F(this):P(this),null;if(0===(e=A(e,t))&&t.ended)return 0===t.length&&F(this),null;var n,i=t.needReadable;return c("need readable",i),(0===t.length||t.length-e0?L(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&F(this)),null!==n&&this.emit("data",n),n},j.prototype._read=function(e){S(this,new _("_read()"))},j.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,c("pipe count=%d opts=%j",i.pipesCount,t);var a=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?u:v;function s(t,r){c("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,c("cleanup"),e.removeListener("close",p),e.removeListener("finish",b),e.removeListener("drain",f),e.removeListener("error",h),e.removeListener("unpipe",s),n.removeListener("end",u),n.removeListener("end",v),n.removeListener("data",d),l=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function u(){c("onend"),e.end()}i.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",s);var f=function(e){return function(){var t=e._readableState;c("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,N(e))}}(n);e.on("drain",f);var l=!1;function d(t){c("ondata");var r=e.write(t);c("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==U(i.pipes,e))&&!l&&(c("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function h(t){c("onerror",t),v(),e.removeListener("error",h),0===o(e,"error")&&S(e,t)}function p(){e.removeListener("finish",b),v()}function b(){c("onfinish"),e.removeListener("close",p),v()}function v(){c("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",h),e.once("close",p),e.once("finish",b),e.emit("pipe",n),i.flowing||(c("pipe resume"),n.resume()),e},j.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,c("on readable",i.length,i.reading),i.length?P(this):i.reading||r.nextTick(T,this))),n},j.prototype.addListener=j.prototype.on,j.prototype.removeListener=function(e,t){var n=a.prototype.removeListener.call(this,e,t);return"readable"===e&&r.nextTick(D,this),n},j.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||r.nextTick(D,this),t},j.prototype.resume=function(){var e=this._readableState;return e.flowing||(c("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(B,e,t))}(this,e)),e.paused=!1,this},j.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},j.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var i in e.on("end",(function(){if(c("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(c("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(t.push(i)||(n=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(j.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(j.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),j.prototype._write=function(e,t,r){r(new b("_write()"))},j.prototype._writev=null,j.prototype.end=function(e,t,n){var i=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,t,n){t.ending=!0,R(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,i,n),this},Object.defineProperty(j.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(j.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),j.prototype.destroy=l.destroy,j.prototype._undestroy=l.undestroy,j.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":153,"./_stream_duplex":154,"./internal/streams/destroy":161,"./internal/streams/state":165,"./internal/streams/stream":166,_process:667,buffer:170,inherits:586,"util-deprecate":939}],159:[function(e,t,r){(function(r){(function(){"use strict";var n;function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var o=e("./end-of-stream"),a=Symbol("lastResolve"),s=Symbol("lastReject"),u=Symbol("error"),c=Symbol("ended"),f=Symbol("lastPromise"),l=Symbol("handlePromise"),d=Symbol("stream");function h(e,t){return{value:e,done:t}}function p(e){var t=e[a];if(null!==t){var r=e[d].read();null!==r&&(e[f]=null,e[a]=null,e[s]=null,t(h(r,!1)))}}function b(e){r.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((i(n={get stream(){return this[d]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[c])return Promise.resolve(h(void 0,!0));if(this[d].destroyed)return new Promise((function(t,n){r.nextTick((function(){e[u]?n(e[u]):t(h(void 0,!0))}))}));var n,i=this[f];if(i)n=new Promise(function(e,t){return function(r,n){e.then((function(){t[c]?r(h(void 0,!0)):t[l](r,n)}),n)}}(i,this));else{var o=this[d].read();if(null!==o)return Promise.resolve(h(o,!1));n=new Promise(this[l])}return this[f]=n,n}},Symbol.asyncIterator,(function(){return this})),i(n,"return",(function(){var e=this;return new Promise((function(t,r){e[d].destroy(null,(function(e){e?r(e):t(h(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,r=Object.create(m,(i(t={},d,{value:e,writable:!0}),i(t,a,{value:null,writable:!0}),i(t,s,{value:null,writable:!0}),i(t,u,{value:null,writable:!0}),i(t,c,{value:e._readableState.endEmitted,writable:!0}),i(t,l,{value:function(e,t){var n=r[d].read();n?(r[f]=null,r[a]=null,r[s]=null,e(h(n,!1))):(r[a]=e,r[s]=t)},writable:!0}),t));return r[f]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=r[s];return null!==t&&(r[f]=null,r[a]=null,r[s]=null,t(e)),void(r[u]=e)}var n=r[a];null!==n&&(r[f]=null,r[a]=null,r[s]=null,n(h(void 0,!0))),r[c]=!0})),e.on("readable",b.bind(null,r)),r}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":162,_process:667}],160:[function(e,t,r){"use strict";function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){for(var r=0;r0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return a.alloc(0);for(var t,r,n,i=a.allocUnsafe(e>>>0),o=this.head,s=0;o;)t=o.data,r=i,n=s,a.prototype.copy.call(t,r,n),s+=o.data.length,o=o.next;return i}},{key:"consume",value:function(e,t){var r;return ei.length?i.length:e;if(o===i.length?n+=i:n+=i.slice(0,e),0==(e-=o)){o===i.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=a.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var i=r.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0==(e-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,t}},{key:u,value:function(e,t){return s(this,function(e){for(var t=1;t0,(function(e){n||(n=e),e&&a.forEach(c),o||(a.forEach(c),i(n))}))}));return t.reduce(f)}},{"../../../errors":153,"./end-of-stream":162}],165:[function(e,t,r){"use strict";var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;t.exports={getHighWaterMark:function(e,t,r,i){var o=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,i,r);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new n(i?r:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}}},{"../../../errors":153}],166:[function(e,t,r){t.exports=e("events").EventEmitter},{events:538}],167:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js"),r.finished=e("./lib/internal/streams/end-of-stream.js"),r.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":154,"./lib/_stream_passthrough.js":155,"./lib/_stream_readable.js":156,"./lib/_stream_transform.js":157,"./lib/_stream_writable.js":158,"./lib/internal/streams/end-of-stream.js":162,"./lib/internal/streams/pipeline.js":164}],168:[function(e,t,r){ /*! safe-buffer. MIT License. Feross Aboukhadijeh */ -var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),a.prototype=Object.create(i.prototype),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:169}],168:[function(e,t,r){(function(e){(function(){t.exports=function(t,r){for(var n=Math.min(t.length,r.length),i=new e(n),o=0;o * @license MIT */ -"use strict";var t=e("base64-js"),n=e("ieee754");r.Buffer=a,r.SlowBuffer=function(e){+e!=e&&(e=0);return a.alloc(+e)},r.INSPECT_MAX_BYTES=50;var i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=a.prototype,t}function a(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return c(e)}return s(e,t,r)}function s(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!a.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|d(e,t),n=o(r),i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(ArrayBuffer.isView(e))return f(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(q(e,ArrayBuffer)||e&&q(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function d(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return N(e).length;default:if(i)return n?-1:L(e).length;t=(""+t).toLowerCase(),i=!0}}function h(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return E(this,t,r);case"latin1":case"binary":return M(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),U(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=a.from(t,n)),a.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var f=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var l=!0,d=0;di&&(n=i):n=i;var o=t.length;n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function x(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function O(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+l<=r)switch(l){case 1:c<128&&(f=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(f=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(f=u)}null===f?(f=65533,l=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=l}return function(e){var t=e.length;if(t<=j)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nt&&(e+=" ... "),""},a.prototype.compare=function(e,t,r,n,i){if(q(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),!a.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),u=Math.min(o,s),c=this.slice(n,i),f=e.slice(t,r),l=0;l>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return y(this,e,t,r);case"utf8":case"utf-8":return m(this,e,t,r);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return _(this,e,t,r);case"base64":return w(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var j=4096;function E(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,r,n,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function C(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function I(e,t,r,i,o){return t=+t,r>>>=0,o||C(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function D(e,t,r,i,o){return t=+t,r>>>=0,o||C(e,0,r,8),n.write(e,t,r,i,52,8),r+8}a.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||P(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||P(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},a.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},a.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||R(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||R(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},a.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,1,255,0),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},a.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);R(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},a.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);R(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},a.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},a.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeFloatLE=function(e,t,r){return I(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return I(this,e,t,!1,r)},a.prototype.writeDoubleLE=function(e,t,r){return D(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return D(this,e,t,!1,r)},a.prototype.copy=function(e,t,r,n){if(!a.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+r];else Uint8Array.prototype.set.call(e,this.subarray(r,n),t);return i},a.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!a.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var i=e.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(e=i)}}else"number"==typeof e&&(e&=255);if(t<0||this.length>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function N(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(B,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function F(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function U(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":90,buffer:169,ieee754:580}],170:[function(e,t,r){"use strict";var n=e("get-intrinsic"),i=e("./"),o=i(n("String.prototype.indexOf"));t.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&o(e,".prototype.")>-1?i(r):r}},{"./":171,"get-intrinsic":546}],171:[function(e,t,r){"use strict";var n=e("function-bind"),i=e("get-intrinsic"),o=i("%Function.prototype.apply%"),a=i("%Function.prototype.call%"),s=i("%Reflect.apply%",!0)||n.call(a,o),u=i("%Object.getOwnPropertyDescriptor%",!0),c=i("%Object.defineProperty%",!0),f=i("%Math.max%");if(c)try{c({},"a",{value:1})}catch(e){c=null}t.exports=function(e){var t=s(n,a,arguments);if(u&&c){var r=u(t,"length");r.configurable&&c(t,"length",{value:1+f(0,e.length-(arguments.length-1))})}return t};var l=function(){return s(n,o,arguments)};c?c(t.exports,"apply",{value:l}):t.exports.apply=l},{"function-bind":543,"get-intrinsic":546}],172:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("stream").Transform,o=e("string_decoder").StringDecoder;function a(e){i.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(a,i),a.prototype.update=function(e,t,r){"string"==typeof e&&(e=n.from(e,t));var i=this._update(e);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)},a.prototype.setAutoPadding=function(){},a.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},a.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},a.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},a.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{r(n)}},a.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},a.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},a.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n},t.exports=a},{inherits:587,"safe-buffer":909,stream:921,string_decoder:936}],173:[function(e,t,r){(function(e){(function(){var r=function(){"use strict";function t(e,t){return null!=t&&e instanceof t}var r,n,i;try{r=Map}catch(e){r=function(){}}try{n=Set}catch(e){n=function(){}}try{i=Promise}catch(e){i=function(){}}function o(a,u,c,f,l){"object"==typeof u&&(c=u.depth,f=u.prototype,l=u.includeNonEnumerable,u=u.circular);var d=[],h=[],p=void 0!==e;return void 0===u&&(u=!0),void 0===c&&(c=1/0),function a(c,b){if(null===c)return null;if(0===b)return c;var v,y;if("object"!=typeof c)return c;if(t(c,r))v=new r;else if(t(c,n))v=new n;else if(t(c,i))v=new i((function(e,t){c.then((function(t){e(a(t,b-1))}),(function(e){t(a(e,b-1))}))}));else if(o.__isArray(c))v=[];else if(o.__isRegExp(c))v=new RegExp(c.source,s(c)),c.lastIndex&&(v.lastIndex=c.lastIndex);else if(o.__isDate(c))v=new Date(c.getTime());else{if(p&&e.isBuffer(c))return v=e.allocUnsafe?e.allocUnsafe(c.length):new e(c.length),c.copy(v),v;t(c,Error)?v=Object.create(c):void 0===f?(y=Object.getPrototypeOf(c),v=Object.create(y)):(v=Object.create(f),y=f)}if(u){var m=d.indexOf(c);if(-1!=m)return h[m];d.push(c),h.push(v)}for(var g in t(c,r)&&c.forEach((function(e,t){var r=a(t,b-1),n=a(e,b-1);v.set(r,n)})),t(c,n)&&c.forEach((function(e){var t=a(e,b-1);v.add(t)})),c){var _;y&&(_=Object.getOwnPropertyDescriptor(y,g)),_&&null==_.set||(v[g]=a(c[g],b-1))}if(Object.getOwnPropertySymbols){var w=Object.getOwnPropertySymbols(c);for(g=0;g2?arguments[2]:void 0,f=Math.min((void 0===c?a:i(c,a))-u,a-s),l=1;for(u0;)u in r?r[s]=r[u]:delete r[s],s+=l,u+=l;return r}},{"./_to-absolute-index":308,"./_to-length":312,"./_to-object":313}],211:[function(e,t,r){"use strict";var n=e("./_to-object"),i=e("./_to-absolute-index"),o=e("./_to-length");t.exports=function(e){for(var t=n(this),r=o(t.length),a=arguments.length,s=i(a>1?arguments[1]:void 0,r),u=a>2?arguments[2]:void 0,c=void 0===u?r:i(u,r);c>s;)t[s++]=e;return t}},{"./_to-absolute-index":308,"./_to-length":312,"./_to-object":313}],212:[function(e,t,r){var n=e("./_to-iobject"),i=e("./_to-length"),o=e("./_to-absolute-index");t.exports=function(e){return function(t,r,a){var s,u=n(t),c=i(u.length),f=o(a,c);if(e&&r!=r){for(;c>f;)if((s=u[f++])!=s)return!0}else for(;c>f;f++)if((e||f in u)&&u[f]===r)return e||f||0;return!e&&-1}}},{"./_to-absolute-index":308,"./_to-iobject":311,"./_to-length":312}],213:[function(e,t,r){var n=e("./_ctx"),i=e("./_iobject"),o=e("./_to-object"),a=e("./_to-length"),s=e("./_array-species-create");t.exports=function(e,t){var r=1==e,u=2==e,c=3==e,f=4==e,l=6==e,d=5==e||l,h=t||s;return function(t,s,p){for(var b,v,y=o(t),m=i(y),g=n(s,p,3),_=a(m.length),w=0,S=r?h(t,_):u?h(t,0):void 0;_>w;w++)if((d||w in m)&&(v=g(b=m[w],w,y),e))if(r)S[w]=v;else if(v)switch(e){case 3:return!0;case 5:return b;case 6:return w;case 2:S.push(b)}else if(f)return!1;return l?-1:c||f?f:S}}},{"./_array-species-create":216,"./_ctx":225,"./_iobject":248,"./_to-length":312,"./_to-object":313}],214:[function(e,t,r){var n=e("./_a-function"),i=e("./_to-object"),o=e("./_iobject"),a=e("./_to-length");t.exports=function(e,t,r,s,u){n(t);var c=i(e),f=o(c),l=a(c.length),d=u?l-1:0,h=u?-1:1;if(r<2)for(;;){if(d in f){s=f[d],d+=h;break}if(d+=h,u?d<0:l<=d)throw TypeError("Reduce of empty array with no initial value")}for(;u?d>=0:l>d;d+=h)d in f&&(s=t(s,f[d],d,c));return s}},{"./_a-function":204,"./_iobject":248,"./_to-length":312,"./_to-object":313}],215:[function(e,t,r){var n=e("./_is-object"),i=e("./_is-array"),o=e("./_wks")("species");t.exports=function(e){var t;return i(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!i(t.prototype)||(t=void 0),n(t)&&null===(t=t[o])&&(t=void 0)),void 0===t?Array:t}},{"./_is-array":250,"./_is-object":252,"./_wks":323}],216:[function(e,t,r){var n=e("./_array-species-constructor");t.exports=function(e,t){return new(n(e))(t)}},{"./_array-species-constructor":215}],217:[function(e,t,r){"use strict";var n=e("./_a-function"),i=e("./_is-object"),o=e("./_invoke"),a=[].slice,s={},u=function(e,t,r){if(!(t in s)){for(var n=[],i=0;i1?arguments[1]:void 0,3);r=r?r.n:this._f;)for(n(r.v,r.k,this);r&&r.r;)r=r.p},has:function(e){return!!v(p(this,t),e)}}),d&&n(f.prototype,"size",{get:function(){return p(this,t)[b]}}),f},def:function(e,t,r){var n,i,o=v(e,t);return o?o.v=r:(e._l=o={i:i=h(t,!0),k:t,v:r,p:n=e._l,n:void 0,r:!1},e._f||(e._f=o),n&&(n.n=o),e[b]++,"F"!==i&&(e._i[i]=o)),e},getEntry:v,setStrong:function(e,t,r){c(e,t,(function(e,r){this._t=p(e,t),this._k=r,this._l=void 0}),(function(){for(var e=this,t=e._k,r=e._l;r&&r.r;)r=r.p;return e._t&&(e._l=r=r?r.n:e._t._f)?f(0,"keys"==t?r.k:"values"==t?r.v:[r.k,r.v]):(e._t=void 0,f(1))}),r?"entries":"values",!r,!0),l(t)}}},{"./_an-instance":208,"./_ctx":225,"./_descriptors":229,"./_for-of":239,"./_iter-define":256,"./_iter-step":258,"./_meta":265,"./_object-create":269,"./_object-dp":270,"./_redefine-all":288,"./_set-species":294,"./_validate-collection":320}],221:[function(e,t,r){"use strict";var n=e("./_redefine-all"),i=e("./_meta").getWeak,o=e("./_an-object"),a=e("./_is-object"),s=e("./_an-instance"),u=e("./_for-of"),c=e("./_array-methods"),f=e("./_has"),l=e("./_validate-collection"),d=c(5),h=c(6),p=0,b=function(e){return e._l||(e._l=new v)},v=function(){this.a=[]},y=function(e,t){return d(e.a,(function(e){return e[0]===t}))};v.prototype={get:function(e){var t=y(this,e);if(t)return t[1]},has:function(e){return!!y(this,e)},set:function(e,t){var r=y(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=h(this.a,(function(t){return t[0]===e}));return~t&&this.a.splice(t,1),!!~t}},t.exports={getConstructor:function(e,t,r,o){var c=e((function(e,n){s(e,c,t,"_i"),e._t=t,e._i=p++,e._l=void 0,null!=n&&u(n,r,e[o],e)}));return n(c.prototype,{delete:function(e){if(!a(e))return!1;var r=i(e);return!0===r?b(l(this,t)).delete(e):r&&f(r,this._i)&&delete r[this._i]},has:function(e){if(!a(e))return!1;var r=i(e);return!0===r?b(l(this,t)).has(e):r&&f(r,this._i)}}),c},def:function(e,t,r){var n=i(o(t),!0);return!0===n?b(e).set(t,r):n[e._i]=r,e},ufstore:b}},{"./_an-instance":208,"./_an-object":209,"./_array-methods":213,"./_for-of":239,"./_has":242,"./_is-object":252,"./_meta":265,"./_redefine-all":288,"./_validate-collection":320}],222:[function(e,t,r){"use strict";var n=e("./_global"),i=e("./_export"),o=e("./_redefine"),a=e("./_redefine-all"),s=e("./_meta"),u=e("./_for-of"),c=e("./_an-instance"),f=e("./_is-object"),l=e("./_fails"),d=e("./_iter-detect"),h=e("./_set-to-string-tag"),p=e("./_inherit-if-required");t.exports=function(e,t,r,b,v,y){var m=n[e],g=m,_=v?"set":"add",w=g&&g.prototype,S={},x=function(e){var t=w[e];o(w,e,"delete"==e||"has"==e?function(e){return!(y&&!f(e))&&t.call(this,0===e?0:e)}:"get"==e?function(e){return y&&!f(e)?void 0:t.call(this,0===e?0:e)}:"add"==e?function(e){return t.call(this,0===e?0:e),this}:function(e,r){return t.call(this,0===e?0:e,r),this})};if("function"==typeof g&&(y||w.forEach&&!l((function(){(new g).entries().next()})))){var O=new g,j=O[_](y?{}:-0,1)!=O,E=l((function(){O.has(1)})),M=d((function(e){new g(e)})),k=!y&&l((function(){for(var e=new g,t=5;t--;)e[_](t,t);return!e.has(-0)}));M||((g=t((function(t,r){c(t,g,e);var n=p(new m,t,g);return null!=r&&u(r,v,n[_],n),n}))).prototype=w,w.constructor=g),(E||k)&&(x("delete"),x("has"),v&&x("get")),(k||j)&&x(_),y&&w.clear&&delete w.clear}else g=b.getConstructor(t,e,v,_),a(g.prototype,r),s.NEED=!0;return h(g,e),S[e]=g,i(i.G+i.W+i.F*(g!=m),S),y||b.setStrong(g,e,v),g}},{"./_an-instance":208,"./_export":233,"./_fails":235,"./_for-of":239,"./_global":241,"./_inherit-if-required":246,"./_is-object":252,"./_iter-detect":257,"./_meta":265,"./_redefine":289,"./_redefine-all":288,"./_set-to-string-tag":295}],223:[function(e,t,r){arguments[4][189][0].apply(r,arguments)},{dup:189}],224:[function(e,t,r){"use strict";var n=e("./_object-dp"),i=e("./_property-desc");t.exports=function(e,t,r){t in e?n.f(e,t,i(0,r)):e[t]=r}},{"./_object-dp":270,"./_property-desc":287}],225:[function(e,t,r){arguments[4][190][0].apply(r,arguments)},{"./_a-function":204,dup:190}],226:[function(e,t,r){"use strict";var n=e("./_fails"),i=Date.prototype.getTime,o=Date.prototype.toISOString,a=function(e){return e>9?e:"0"+e};t.exports=n((function(){return"0385-07-25T07:06:39.999Z"!=o.call(new Date(-50000000000001))}))||!n((function(){o.call(new Date(NaN))}))?function(){if(!isFinite(i.call(this)))throw RangeError("Invalid time value");var e=this,t=e.getUTCFullYear(),r=e.getUTCMilliseconds(),n=t<0?"-":t>9999?"+":"";return n+("00000"+Math.abs(t)).slice(n?-6:-4)+"-"+a(e.getUTCMonth()+1)+"-"+a(e.getUTCDate())+"T"+a(e.getUTCHours())+":"+a(e.getUTCMinutes())+":"+a(e.getUTCSeconds())+"."+(r>99?r:"0"+a(r))+"Z"}:o},{"./_fails":235}],227:[function(e,t,r){"use strict";var n=e("./_an-object"),i=e("./_to-primitive"),o="number";t.exports=function(e){if("string"!==e&&e!==o&&"default"!==e)throw TypeError("Incorrect hint");return i(n(this),e!=o)}},{"./_an-object":209,"./_to-primitive":314}],228:[function(e,t,r){t.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},{}],229:[function(e,t,r){arguments[4][191][0].apply(r,arguments)},{"./_fails":235,dup:191}],230:[function(e,t,r){arguments[4][192][0].apply(r,arguments)},{"./_global":241,"./_is-object":252,dup:192}],231:[function(e,t,r){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},{}],232:[function(e,t,r){var n=e("./_object-keys"),i=e("./_object-gops"),o=e("./_object-pie");t.exports=function(e){var t=n(e),r=i.f;if(r)for(var a,s=r(e),u=o.f,c=0;s.length>c;)u.call(e,a=s[c++])&&t.push(a);return t}},{"./_object-gops":275,"./_object-keys":278,"./_object-pie":279}],233:[function(e,t,r){var n=e("./_global"),i=e("./_core"),o=e("./_hide"),a=e("./_redefine"),s=e("./_ctx"),u=function(e,t,r){var c,f,l,d,h=e&u.F,p=e&u.G,b=e&u.S,v=e&u.P,y=e&u.B,m=p?n:b?n[t]||(n[t]={}):(n[t]||{}).prototype,g=p?i:i[t]||(i[t]={}),_=g.prototype||(g.prototype={});for(c in p&&(r=t),r)l=((f=!h&&m&&void 0!==m[c])?m:r)[c],d=y&&f?s(l,n):v&&"function"==typeof l?s(Function.call,l):l,m&&a(m,c,l,e&u.U),g[c]!=l&&o(g,c,d),v&&_[c]!=l&&(_[c]=l)};n.core=i,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},{"./_core":223,"./_ctx":225,"./_global":241,"./_hide":243,"./_redefine":289}],234:[function(e,t,r){var n=e("./_wks")("match");t.exports=function(e){var t=/./;try{"/./"[e](t)}catch(r){try{return t[n]=!1,!"/./"[e](t)}catch(e){}}return!0}},{"./_wks":323}],235:[function(e,t,r){arguments[4][194][0].apply(r,arguments)},{dup:194}],236:[function(e,t,r){"use strict";e("./es6.regexp.exec");var n=e("./_redefine"),i=e("./_hide"),o=e("./_fails"),a=e("./_defined"),s=e("./_wks"),u=e("./_regexp-exec"),c=s("species"),f=!o((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")})),l=function(){var e=/(?:)/,t=e.exec;e.exec=function(){return t.apply(this,arguments)};var r="ab".split(e);return 2===r.length&&"a"===r[0]&&"b"===r[1]}();t.exports=function(e,t,r){var d=s(e),h=!o((function(){var t={};return t[d]=function(){return 7},7!=""[e](t)})),p=h?!o((function(){var t=!1,r=/a/;return r.exec=function(){return t=!0,null},"split"===e&&(r.constructor={},r.constructor[c]=function(){return r}),r[d](""),!t})):void 0;if(!h||!p||"replace"===e&&!f||"split"===e&&!l){var b=/./[d],v=r(a,d,""[e],(function(e,t,r,n,i){return t.exec===u?h&&!i?{done:!0,value:b.call(t,r,n)}:{done:!0,value:e.call(r,t,n)}:{done:!1}})),y=v[0],m=v[1];n(String.prototype,e,y),i(RegExp.prototype,d,2==t?function(e,t){return m.call(e,this,t)}:function(e){return m.call(e,this)})}}},{"./_defined":228,"./_fails":235,"./_hide":243,"./_redefine":289,"./_regexp-exec":291,"./_wks":323,"./es6.regexp.exec":419}],237:[function(e,t,r){"use strict";var n=e("./_an-object");t.exports=function(){var e=n(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t}},{"./_an-object":209}],238:[function(e,t,r){"use strict";var n=e("./_is-array"),i=e("./_is-object"),o=e("./_to-length"),a=e("./_ctx"),s=e("./_wks")("isConcatSpreadable");t.exports=function e(t,r,u,c,f,l,d,h){for(var p,b,v=f,y=0,m=!!d&&a(d,h,3);y0)v=e(t,r,p,o(p.length),v,l-1)-1;else{if(v>=9007199254740991)throw TypeError();t[v]=p}v++}y++}return v}},{"./_ctx":225,"./_is-array":250,"./_is-object":252,"./_to-length":312,"./_wks":323}],239:[function(e,t,r){var n=e("./_ctx"),i=e("./_iter-call"),o=e("./_is-array-iter"),a=e("./_an-object"),s=e("./_to-length"),u=e("./core.get-iterator-method"),c={},f={};(r=t.exports=function(e,t,r,l,d){var h,p,b,v,y=d?function(){return e}:u(e),m=n(r,l,t?2:1),g=0;if("function"!=typeof y)throw TypeError(e+" is not iterable!");if(o(y)){for(h=s(e.length);h>g;g++)if((v=t?m(a(p=e[g])[0],p[1]):m(e[g]))===c||v===f)return v}else for(b=y.call(e);!(p=b.next()).done;)if((v=i(b,m,p.value,t))===c||v===f)return v}).BREAK=c,r.RETURN=f},{"./_an-object":209,"./_ctx":225,"./_is-array-iter":249,"./_iter-call":254,"./_to-length":312,"./core.get-iterator-method":324}],240:[function(e,t,r){t.exports=e("./_shared")("native-function-to-string",Function.toString)},{"./_shared":297}],241:[function(e,t,r){arguments[4][195][0].apply(r,arguments)},{dup:195}],242:[function(e,t,r){arguments[4][196][0].apply(r,arguments)},{dup:196}],243:[function(e,t,r){arguments[4][197][0].apply(r,arguments)},{"./_descriptors":229,"./_object-dp":270,"./_property-desc":287,dup:197}],244:[function(e,t,r){var n=e("./_global").document;t.exports=n&&n.documentElement},{"./_global":241}],245:[function(e,t,r){arguments[4][198][0].apply(r,arguments)},{"./_descriptors":229,"./_dom-create":230,"./_fails":235,dup:198}],246:[function(e,t,r){var n=e("./_is-object"),i=e("./_set-proto").set;t.exports=function(e,t,r){var o,a=t.constructor;return a!==r&&"function"==typeof a&&(o=a.prototype)!==r.prototype&&n(o)&&i&&i(e,o),e}},{"./_is-object":252,"./_set-proto":293}],247:[function(e,t,r){t.exports=function(e,t,r){var n=void 0===r;switch(t.length){case 0:return n?e():e.call(r);case 1:return n?e(t[0]):e.call(r,t[0]);case 2:return n?e(t[0],t[1]):e.call(r,t[0],t[1]);case 3:return n?e(t[0],t[1],t[2]):e.call(r,t[0],t[1],t[2]);case 4:return n?e(t[0],t[1],t[2],t[3]):e.call(r,t[0],t[1],t[2],t[3])}return e.apply(r,t)}},{}],248:[function(e,t,r){var n=e("./_cof");t.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==n(e)?e.split(""):Object(e)}},{"./_cof":219}],249:[function(e,t,r){var n=e("./_iterators"),i=e("./_wks")("iterator"),o=Array.prototype;t.exports=function(e){return void 0!==e&&(n.Array===e||o[i]===e)}},{"./_iterators":259,"./_wks":323}],250:[function(e,t,r){var n=e("./_cof");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"./_cof":219}],251:[function(e,t,r){var n=e("./_is-object"),i=Math.floor;t.exports=function(e){return!n(e)&&isFinite(e)&&i(e)===e}},{"./_is-object":252}],252:[function(e,t,r){arguments[4][199][0].apply(r,arguments)},{dup:199}],253:[function(e,t,r){var n=e("./_is-object"),i=e("./_cof"),o=e("./_wks")("match");t.exports=function(e){var t;return n(e)&&(void 0!==(t=e[o])?!!t:"RegExp"==i(e))}},{"./_cof":219,"./_is-object":252,"./_wks":323}],254:[function(e,t,r){var n=e("./_an-object");t.exports=function(e,t,r,i){try{return i?t(n(r)[0],r[1]):t(r)}catch(t){var o=e.return;throw void 0!==o&&n(o.call(e)),t}}},{"./_an-object":209}],255:[function(e,t,r){"use strict";var n=e("./_object-create"),i=e("./_property-desc"),o=e("./_set-to-string-tag"),a={};e("./_hide")(a,e("./_wks")("iterator"),(function(){return this})),t.exports=function(e,t,r){e.prototype=n(a,{next:i(1,r)}),o(e,t+" Iterator")}},{"./_hide":243,"./_object-create":269,"./_property-desc":287,"./_set-to-string-tag":295,"./_wks":323}],256:[function(e,t,r){"use strict";var n=e("./_library"),i=e("./_export"),o=e("./_redefine"),a=e("./_hide"),s=e("./_iterators"),u=e("./_iter-create"),c=e("./_set-to-string-tag"),f=e("./_object-gpo"),l=e("./_wks")("iterator"),d=!([].keys&&"next"in[].keys()),h="keys",p="values",b=function(){return this};t.exports=function(e,t,r,v,y,m,g){u(r,t,v);var _,w,S,x=function(e){if(!d&&e in M)return M[e];switch(e){case h:case p:return function(){return new r(this,e)}}return function(){return new r(this,e)}},O=t+" Iterator",j=y==p,E=!1,M=e.prototype,k=M[l]||M["@@iterator"]||y&&M[y],A=k||x(y),P=y?j?x("entries"):A:void 0,R="Array"==t&&M.entries||k;if(R&&(S=f(R.call(new e)))!==Object.prototype&&S.next&&(c(S,O,!0),n||"function"==typeof S[l]||a(S,l,b)),j&&k&&k.name!==p&&(E=!0,A=function(){return k.call(this)}),n&&!g||!d&&!E&&M[l]||a(M,l,A),s[t]=A,s[O]=b,y)if(_={values:j?A:x(p),keys:m?A:x(h),entries:P},g)for(w in _)w in M||o(M,w,_[w]);else i(i.P+i.F*(d||E),t,_);return _}},{"./_export":233,"./_hide":243,"./_iter-create":255,"./_iterators":259,"./_library":260,"./_object-gpo":276,"./_redefine":289,"./_set-to-string-tag":295,"./_wks":323}],257:[function(e,t,r){var n=e("./_wks")("iterator"),i=!1;try{var o=[7][n]();o.return=function(){i=!0},Array.from(o,(function(){throw 2}))}catch(e){}t.exports=function(e,t){if(!t&&!i)return!1;var r=!1;try{var o=[7],a=o[n]();a.next=function(){return{done:r=!0}},o[n]=function(){return a},e(o)}catch(e){}return r}},{"./_wks":323}],258:[function(e,t,r){t.exports=function(e,t){return{value:t,done:!!e}}},{}],259:[function(e,t,r){t.exports={}},{}],260:[function(e,t,r){t.exports=!1},{}],261:[function(e,t,r){var n=Math.expm1;t.exports=!n||n(10)>22025.465794806718||n(10)<22025.465794806718||-2e-17!=n(-2e-17)?function(e){return 0==(e=+e)?e:e>-1e-6&&e<1e-6?e+e*e/2:Math.exp(e)-1}:n},{}],262:[function(e,t,r){var n=e("./_math-sign"),i=Math.pow,o=i(2,-52),a=i(2,-23),s=i(2,127)*(2-a),u=i(2,-126);t.exports=Math.fround||function(e){var t,r,i=Math.abs(e),c=n(e);return is||r!=r?c*(1/0):c*r}},{"./_math-sign":264}],263:[function(e,t,r){t.exports=Math.log1p||function(e){return(e=+e)>-1e-8&&e<1e-8?e-e*e/2:Math.log(1+e)}},{}],264:[function(e,t,r){t.exports=Math.sign||function(e){return 0==(e=+e)||e!=e?e:e<0?-1:1}},{}],265:[function(e,t,r){var n=e("./_uid")("meta"),i=e("./_is-object"),o=e("./_has"),a=e("./_object-dp").f,s=0,u=Object.isExtensible||function(){return!0},c=!e("./_fails")((function(){return u(Object.preventExtensions({}))})),f=function(e){a(e,n,{value:{i:"O"+ ++s,w:{}}})},l=t.exports={KEY:n,NEED:!1,fastKey:function(e,t){if(!i(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!o(e,n)){if(!u(e))return"F";if(!t)return"E";f(e)}return e[n].i},getWeak:function(e,t){if(!o(e,n)){if(!u(e))return!0;if(!t)return!1;f(e)}return e[n].w},onFreeze:function(e){return c&&l.NEED&&u(e)&&!o(e,n)&&f(e),e}}},{"./_fails":235,"./_has":242,"./_is-object":252,"./_object-dp":270,"./_uid":318}],266:[function(e,t,r){var n=e("./_global"),i=e("./_task").set,o=n.MutationObserver||n.WebKitMutationObserver,a=n.process,s=n.Promise,u="process"==e("./_cof")(a);t.exports=function(){var e,t,r,c=function(){var n,i;for(u&&(n=a.domain)&&n.exit();e;){i=e.fn,e=e.next;try{i()}catch(n){throw e?r():t=void 0,n}}t=void 0,n&&n.enter()};if(u)r=function(){a.nextTick(c)};else if(!o||n.navigator&&n.navigator.standalone)if(s&&s.resolve){var f=s.resolve(void 0);r=function(){f.then(c)}}else r=function(){i.call(n,c)};else{var l=!0,d=document.createTextNode("");new o(c).observe(d,{characterData:!0}),r=function(){d.data=l=!l}}return function(n){var i={fn:n,next:void 0};t&&(t.next=i),e||(e=i,r()),t=i}}},{"./_cof":219,"./_global":241,"./_task":307}],267:[function(e,t,r){"use strict";var n=e("./_a-function");function i(e){var t,r;this.promise=new e((function(e,n){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=n})),this.resolve=n(t),this.reject=n(r)}t.exports.f=function(e){return new i(e)}},{"./_a-function":204}],268:[function(e,t,r){"use strict";var n=e("./_descriptors"),i=e("./_object-keys"),o=e("./_object-gops"),a=e("./_object-pie"),s=e("./_to-object"),u=e("./_iobject"),c=Object.assign;t.exports=!c||e("./_fails")((function(){var e={},t={},r=Symbol(),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach((function(e){t[e]=e})),7!=c({},e)[r]||Object.keys(c({},t)).join("")!=n}))?function(e,t){for(var r=s(e),c=arguments.length,f=1,l=o.f,d=a.f;c>f;)for(var h,p=u(arguments[f++]),b=l?i(p).concat(l(p)):i(p),v=b.length,y=0;v>y;)h=b[y++],n&&!d.call(p,h)||(r[h]=p[h]);return r}:c},{"./_descriptors":229,"./_fails":235,"./_iobject":248,"./_object-gops":275,"./_object-keys":278,"./_object-pie":279,"./_to-object":313}],269:[function(e,t,r){var n=e("./_an-object"),i=e("./_object-dps"),o=e("./_enum-bug-keys"),a=e("./_shared-key")("IE_PROTO"),s=function(){},u=function(){var t,r=e("./_dom-create")("iframe"),n=o.length;for(r.style.display="none",e("./_html").appendChild(r),r.src="javascript:",(t=r.contentWindow.document).open(),t.write("