diff --git a/dist/cjs/doc-cache.js b/dist/cjs/doc-cache.js index c5923c32fce..40859edf81e 100644 --- a/dist/cjs/doc-cache.js +++ b/dist/cjs/doc-cache.js @@ -92,14 +92,13 @@ var DocumentCache = exports.DocumentCache = /*#__PURE__*/function () { return cacheItem.last; } }; - (0, _createClass2.default)(DocumentCache, [{ + return (0, _createClass2.default)(DocumentCache, [{ key: "getCachedRxDocument", get: function () { var fn = getCachedRxDocumentMonad(this); return (0, _index.overwriteGetterForCaching)(this, 'getCachedRxDocument', fn); } }]); - return DocumentCache; }(); /** * This function is called very very often. diff --git a/dist/cjs/doc-cache.js.map b/dist/cjs/doc-cache.js.map index 7362b38162a..6586396855b 100644 --- a/dist/cjs/doc-cache.js.map +++ b/dist/cjs/doc-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"doc-cache.js","names":["_index","require","_overwritable","_rxChangeEvent","DocumentCache","exports","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","byRev","delete","revisionHeight","size","undefined","registerIdleTasks","subscribe","changeEvent","documentId","documentData","getDocumentDataOfRxChangeEvent","last","_proto","prototype","getLatestDocumentData","getFromMapOrThrow","getLatestDocumentDataIfExists","_createClass2","default","key","fn","getCachedRxDocumentMonad","overwriteGetterForCaching","docCache","deepFreezeWhenDevMode","overwritable","docData","getHeightOfRevision","_rev","getFromMapOrCreate","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","set","createWeakRefWithFallback","push","registerIdlePromise","requestIdlePromiseNoQueue","then","tasks","length","forEach","doc","register","primary","revision","mapDocumentsDataToCacheDocs","docsData","getCachedRxDocument","documents","i","HAS_WEAK_REF","WeakRef","createWeakRef","createWeakRefFallback","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types/index.d.ts';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision,\n overwriteGetterForCaching,\n requestIdlePromiseNoQueue\n} from './plugins/utils/index.ts';\nimport {\n overwritable\n} from './overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event.ts';\nimport { Observable } from 'rxjs';\n\ndeclare type CacheItem = {\n /**\n * Store the different document states of time\n * based on their revision height.\n * We store WeakRefs so that we can later clean up\n * document states that are no longer needed.\n */\n byRev: Map>>;\n\n /**\n * Store the latest known document state.\n * As long as any state of the document is in the cache,\n * we observe the changestream and update the latestDoc accordingly.\n * This makes it easier to optimize performance on other parts\n * because for each known document we can always get the current state\n * in the storage.\n * Also it makes it possible to call RxDocument.latest() in a non-async way\n * to retrieve the latest document state or to observe$ some property.\n *\n * To not prevent the whole cacheItem from being garbage collected,\n * we store only the document data here, but not the RxDocument.\n */\n last: RxDocumentData;\n};\n\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\ndeclare type FinalizationRegistryValue = {\n docId: string;\n revisionHeight: number;\n};\n\n/**\n * The DocumentCache stores RxDocument objects\n * by their primary key and revision.\n * This is useful on client side applications where\n * it is not known how much memory can be used, so\n * we de-duplicate RxDocument states to save memory.\n * To not fill up the memory with old document states, the DocumentCache\n * only contains weak references to the RxDocuments themself.\n * @link https://caniuse.com/?search=weakref\n */\nexport class DocumentCache {\n public cacheItemByDocId = new Map>();\n\n /**\n * Some JavaScript runtimes like QuickJS,\n * so not have a FinalizationRegistry or WeakRef.\n * Therefore we need a workaround which might waste a lot of memory,\n * but at least works.\n */\n public readonly registry?: FinalizationRegistry = typeof FinalizationRegistry === 'function' ?\n new FinalizationRegistry(docMeta => {\n const docId = docMeta.docId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n cacheItem.byRev.delete(docMeta.revisionHeight);\n if (cacheItem.byRev.size === 0) {\n /**\n * No state of the document is cached anymore,\n * so we can clean up.\n */\n this.cacheItemByDocId.delete(docId);\n }\n }\n }) :\n undefined;\n\n /**\n * Calling registry.register(() has shown to have\n * really bad performance. So we add the cached documents\n * lazily.\n */\n public registerIdlePromise?: Promise;\n public registerIdleTasks: RxDocument[] = [];\n\n constructor(\n public readonly primaryPath: string,\n public readonly changes$: Observable>,\n /**\n * A method that can create a RxDocument by the given document data.\n */\n public documentCreator: (docData: RxDocumentData) => RxDocument\n ) {\n changes$.subscribe(changeEvent => {\n const docId = changeEvent.documentId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n const documentData = getDocumentDataOfRxChangeEvent(changeEvent);\n cacheItem.last = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n * @overwrites itself with the actual function\n * because this is @performance relevant.\n * It is called on each document row for each write and read.\n */\n get getCachedRxDocument(): (docData: RxDocumentData) => RxDocument {\n const fn = getCachedRxDocumentMonad(this);\n return overwriteGetterForCaching(\n this,\n 'getCachedRxDocument',\n fn\n );\n }\n\n /**\n * Throws if not exists\n */\n public getLatestDocumentData(docId: string): RxDocumentData {\n const cacheItem = getFromMapOrThrow(this.cacheItemByDocId, docId);\n return cacheItem.last;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.last;\n }\n }\n}\n\n/**\n * This function is called very very often.\n * This is likely the most important function for RxDB overall performance\n */\nfunction getCachedRxDocumentMonad(\n docCache: DocumentCache\n): (docData: RxDocumentData) => RxDocument {\n const primaryPath = docCache.primaryPath;\n const cacheItemByDocId = docCache.cacheItemByDocId;\n const registry = docCache.registry;\n const deepFreezeWhenDevMode = overwritable.deepFreezeWhenDevMode;\n const documentCreator = docCache.documentCreator;\n const fn: (docData: RxDocumentData) => RxDocument = (docData: RxDocumentData) => {\n const docId: string = (docData as any)[primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const byRev = cacheItem.byRev;\n const cachedRxDocumentWeakRef: WeakRef> | undefined = byRev.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = documentCreator(docData) as RxDocument;\n byRev.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n if (registry) {\n docCache.registerIdleTasks.push(cachedRxDocument);\n if (!docCache.registerIdlePromise) {\n docCache.registerIdlePromise = requestIdlePromiseNoQueue().then(() => {\n docCache.registerIdlePromise = undefined;\n const tasks = docCache.registerIdleTasks;\n if (tasks.length === 0) {\n return;\n }\n docCache.registerIdleTasks = [];\n tasks.forEach(doc => {\n registry.register(doc, {\n docId: doc.primary,\n revisionHeight: getHeightOfRevision(doc.revision)\n });\n });\n });\n }\n }\n }\n return cachedRxDocument;\n };\n return fn;\n}\n\nexport function mapDocumentsDataToCacheDocs(\n docCache: DocumentCache,\n docsData: RxDocumentData[]\n) {\n const getCachedRxDocument = docCache.getCachedRxDocument;\n const documents: RxDocument[] = [];\n for (let i = 0; i < docsData.length; i++) {\n const docData = docsData[i];\n const doc = getCachedRxDocument(docData);\n documents.push(doc);\n }\n return documents;\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n byRev: new Map(),\n last: docData\n };\n}\n\n\n\n\n/**\n * Fallback for JavaScript runtimes that do not support WeakRef.\n * The fallback will keep the items in cache forever,\n * but at least works.\n */\nconst HAS_WEAK_REF = typeof WeakRef === 'function';\nconst createWeakRefWithFallback = HAS_WEAK_REF ? createWeakRef : createWeakRefFallback;\nfunction createWeakRef(obj: T): WeakRef {\n return new WeakRef(obj) as any;\n}\nfunction createWeakRefFallback(obj: T): WeakRef {\n return {\n deref() {\n return obj;\n }\n } as any;\n}\n"],"mappings":";;;;;;;;;AAKA,IAAAA,MAAA,GAAAC,OAAA;AAOA,IAAAC,aAAA,GAAAD,OAAA;A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cAAc,EAAE,IAAAyB,0BAAmB,EAACgB,GAAG,CAACG,QAAQ;cACpD,CAAC,CAAC;YACN,CAAC,CAAC;UACN,CAAC,CAAC;QACN;MACJ;IACJ;IACA,OAAOd,gBAAgB;EAC3B,CAAC;EACD,OAAOZ,EAAE;AACb;AAEO,SAAS2B,2BAA2BA,CACvCxB,QAA8C,EAC9CyB,QAAqC,EACvC;EACE,IAAMC,mBAAmB,GAAG1B,QAAQ,CAAC0B,mBAAmB;EACxD,IAAMC,SAA8C,GAAG,EAAE;EACzD,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,QAAQ,CAACP,MAAM,EAAEU,CAAC,EAAE,EAAE;IACtC,IAAMzB,QAAO,GAAGsB,QAAQ,CAACG,CAAC,CAAC;IAC3B,IAAMR,GAAG,GAAGM,mBAAmB,CAACvB,QAAO,CAAC;IACxCwB,SAAS,CAACd,IAAI,CAACO,GAAG,CAAC;EACvB;EACA,OAAOO,SAAS;AACpB;AAGA,SAASpB,eAAeA,CAAwBJ,OAAkC,EAAoC;EAClH,OAAO;IACH1B,KAAK,EAAE,IAAIP,GAAG,CAAC,CAAC;IAChBkB,IAAI,EAAEe;EACV,CAAC;AACL;;AAKA;AACA;AACA;AACA;AACA;AACA,IAAM0B,YAAY,GAAG,OAAOC,OAAO,KAAK,UAAU;AAClD,IAAMlB,yBAAyB,GAAGiB,YAAY,GAAGE,aAAa,GAAGC,qBAAqB;AACtF,SAASD,aAAaA,CAAmBE,GAAM,EAAc;EACzD,OAAO,IAAIH,OAAO,CAACG,GAAG,CAAC;AAC3B;AACA,SAASD,qBAAqBA,CAAmBC,GAAM,EAAc;EACjE,OAAO;IACHvB,KAAKA,CAAA,EAAG;MACJ,OAAOuB,GAAG;IACd;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"doc-cache.js","names":["_index","require","_overwritable","_rxChangeEvent","DocumentCache","exports","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","byRev","delete","revisionHeight","size","undefined","registerIdleTasks","subscribe","changeEvent","documentId","documentData","getDocumentDataOfRxChangeEvent","last","_proto","prototype","getLatestDocumentData","getFromMapOrThrow","getLatestDocumentDataIfExists","_createClass2","default","key","fn","getCachedRxDocumentMonad","overwriteGetterForCaching","docCache","deepFreezeWhenDevMode","overwritable","docData","getHeightOfRevision","_rev","getFromMapOrCreate","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","set","createWeakRefWithFallback","push","registerIdlePromise","requestIdlePromiseNoQueue","then","tasks","length","forEach","doc","register","primary","revision","mapDocumentsDataToCacheDocs","docsData","getCachedRxDocument","documents","i","HAS_WEAK_REF","WeakRef","createWeakRef","createWeakRefFallback","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types/index.d.ts';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision,\n overwriteGetterForCaching,\n requestIdlePromiseNoQueue\n} from './plugins/utils/index.ts';\nimport {\n overwritable\n} from './overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event.ts';\nimport { Observable } from 'rxjs';\n\ndeclare type CacheItem = {\n /**\n * Store the different document states of time\n * based on their revision height.\n * We store WeakRefs so that we can later clean up\n * document states that are no longer needed.\n */\n byRev: Map>>;\n\n /**\n * Store the latest known document state.\n * As long as any state of the document is in the cache,\n * we observe the changestream and update the latestDoc accordingly.\n * This makes it easier to optimize performance on other parts\n * because for each known document we can always get the current state\n * in the storage.\n * Also it makes it possible to call RxDocument.latest() in a non-async way\n * to retrieve the latest document state or to observe$ some property.\n *\n * To not prevent the whole cacheItem from being garbage collected,\n * we store only the document data here, but not the RxDocument.\n */\n last: RxDocumentData;\n};\n\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\ndeclare type FinalizationRegistryValue = {\n docId: string;\n revisionHeight: number;\n};\n\n/**\n * The DocumentCache stores RxDocument objects\n * by their primary key and revision.\n * This is useful on client side applications where\n * it is not known how much memory can be used, so\n * we de-duplicate RxDocument states to save memory.\n * To not fill up the memory with old document states, the DocumentCache\n * only contains weak references to the RxDocuments themself.\n * @link https://caniuse.com/?search=weakref\n */\nexport class DocumentCache {\n public cacheItemByDocId = new Map>();\n\n /**\n * Some JavaScript runtimes like QuickJS,\n * so not have a FinalizationRegistry or WeakRef.\n * Therefore we need a workaround which might waste a lot of memory,\n * but at least works.\n */\n public readonly registry?: FinalizationRegistry = typeof FinalizationRegistry === 'function' ?\n new FinalizationRegistry(docMeta => {\n const docId = docMeta.docId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n cacheItem.byRev.delete(docMeta.revisionHeight);\n if (cacheItem.byRev.size === 0) {\n /**\n * No state of the document is cached anymore,\n * so we can clean up.\n */\n this.cacheItemByDocId.delete(docId);\n }\n }\n }) :\n undefined;\n\n /**\n * Calling registry.register(() has shown to have\n * really bad performance. So we add the cached documents\n * lazily.\n */\n public registerIdlePromise?: Promise;\n public registerIdleTasks: RxDocument[] = [];\n\n constructor(\n public readonly primaryPath: string,\n public readonly changes$: Observable>,\n /**\n * A method that can create a RxDocument by the given document data.\n */\n public documentCreator: (docData: RxDocumentData) => RxDocument\n ) {\n changes$.subscribe(changeEvent => {\n const docId = changeEvent.documentId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n const documentData = getDocumentDataOfRxChangeEvent(changeEvent);\n cacheItem.last = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n * @overwrites itself with the actual function\n * because this is @performance relevant.\n * It is called on each document row for each write and read.\n */\n get getCachedRxDocument(): (docData: RxDocumentData) => RxDocument {\n const fn = getCachedRxDocumentMonad(this);\n return overwriteGetterForCaching(\n this,\n 'getCachedRxDocument',\n fn\n );\n }\n\n /**\n * Throws if not exists\n */\n public getLatestDocumentData(docId: string): RxDocumentData {\n const cacheItem = getFromMapOrThrow(this.cacheItemByDocId, docId);\n return cacheItem.last;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.last;\n }\n }\n}\n\n/**\n * This function is called very very often.\n * This is likely the most important function for RxDB overall performance\n */\nfunction getCachedRxDocumentMonad(\n docCache: DocumentCache\n): (docData: RxDocumentData) => RxDocument {\n const primaryPath = docCache.primaryPath;\n const cacheItemByDocId = docCache.cacheItemByDocId;\n const registry = docCache.registry;\n const deepFreezeWhenDevMode = overwritable.deepFreezeWhenDevMode;\n const documentCreator = docCache.documentCreator;\n const fn: (docData: RxDocumentData) => RxDocument = (docData: RxDocumentData) => {\n const docId: string = (docData as any)[primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const byRev = cacheItem.byRev;\n const cachedRxDocumentWeakRef: WeakRef> | undefined = byRev.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = documentCreator(docData) as RxDocument;\n byRev.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n if (registry) {\n docCache.registerIdleTasks.push(cachedRxDocument);\n if (!docCache.registerIdlePromise) {\n docCache.registerIdlePromise = requestIdlePromiseNoQueue().then(() => {\n docCache.registerIdlePromise = undefined;\n const tasks = docCache.registerIdleTasks;\n if (tasks.length === 0) {\n return;\n }\n docCache.registerIdleTasks = [];\n tasks.forEach(doc => {\n registry.register(doc, {\n docId: doc.primary,\n revisionHeight: getHeightOfRevision(doc.revision)\n });\n });\n });\n }\n }\n }\n return cachedRxDocument;\n };\n return fn;\n}\n\nexport function mapDocumentsDataToCacheDocs(\n docCache: DocumentCache,\n docsData: RxDocumentData[]\n) {\n const getCachedRxDocument = docCache.getCachedRxDocument;\n const documents: RxDocument[] = [];\n for (let i = 0; i < docsData.length; i++) {\n const docData = docsData[i];\n const doc = getCachedRxDocument(docData);\n documents.push(doc);\n }\n return documents;\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n byRev: new Map(),\n last: docData\n };\n}\n\n\n\n\n/**\n * Fallback for JavaScript runtimes that do not support WeakRef.\n * The fallback will keep the items in cache forever,\n * but at least works.\n */\nconst HAS_WEAK_REF = typeof WeakRef === 'function';\nconst createWeakRefWithFallback = HAS_WEAK_REF ? createWeakRef : createWeakRefFallback;\nfunction createWeakRef(obj: T): WeakRef {\n return new WeakRef(obj) as any;\n}\nfunction createWeakRefFallback(obj: T): WeakRef {\n return {\n deref() {\n return obj;\n }\n } as any;\n}\n"],"mappings":";;;;;;;;;AAKA,IAAAA,MAAA,GAAAC,OAAA;AAOA,IAAAC,aAAA,GAAAD,OAAA;AAGA,IAAAE,cAAA,GAAAF,OAAA;AA6BA;AACA;AACA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AATA,IAUaG,aAAa,GAAAC,OAAA,CAAAD,aAAA;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI;AACJ;AACA;AACA;AACA;;EAII,SAAAA,cACoBE,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA,KAxCKC,gBAAgB,GAAG,IAAIC,GAAG,CAA2C,CAAC;IAAA,KAQ7DC,QAAQ,GAAqD,OAAOC,oBAAoB,KAAK,UAAU,GACnH,IAAIA,oBAAoB,CAA4BC,OAAO,IAAI;MAC3D,IAAMC,KAAK,GAAGD,OAAO,CAACC,KAAK;MAC3B,IAAMC,SAAS,GAAG,IAAI,CAACN,gBAAgB,CAACO,GAAG,CAACF,KAAK,CAAC;MAClD,IAAIC,SAAS,EAAE;QACXA,SAAS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AGA,SAASpB,eAAeA,CAAwBJ,OAAkC,EAAoC;EAClH,OAAO;IACH1B,KAAK,EAAE,IAAIP,GAAG,CAAC,CAAC;IAChBkB,IAAI,EAAEe;EACV,CAAC;AACL;;AAKA;AACA;AACA;AACA;AACA;AACA,IAAM0B,YAAY,GAAG,OAAOC,OAAO,KAAK,UAAU;AAClD,IAAMlB,yBAAyB,GAAGiB,YAAY,GAAGE,aAAa,GAAGC,qBAAqB;AACtF,SAASD,aAAaA,CAAmBE,GAAM,EAAc;EACzD,OAAO,IAAIH,OAAO,CAACG,GAAG,CAAC;AAC3B;AACA,SAASD,qBAAqBA,CAAmBC,GAAM,EAAc;EACjE,OAAO;IACHvB,KAAKA,CAAA,EAAG;MACJ,OAAOuB,GAAG;IACd;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/backup/file-util.js b/dist/cjs/plugins/backup/file-util.js index be804c7e2d4..f7e5087f09e 100644 --- a/dist/cjs/plugins/backup/file-util.js +++ b/dist/cjs/plugins/backup/file-util.js @@ -17,7 +17,7 @@ var fs = _interopRequireWildcard(require("node:fs")); var path = _interopRequireWildcard(require("node:path")); var _index = require("../../plugins/utils/index.js"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * ensure that the given folder exists */ diff --git a/dist/cjs/plugins/backup/file-util.js.map b/dist/cjs/plugins/backup/file-util.js.map index aacc34b6b75..4df111a9c62 100644 --- a/dist/cjs/plugins/backup/file-util.js.map +++ b/dist/cjs/plugins/backup/file-util.js.map @@ -1 +1 @@ -{"version":3,"file":"file-util.js","names":["fs","_interopRequireWildcard","require","path","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","ensureFolderExists","folderPath","existsSync","mkdirSync","recursive","clearFolder","deleteFolder","rmdirSync","prepareFolders","database","options","directory","metaLoc","metaFileLocation","currentTime","now","metaData","createdAt","updatedAt","collectionStates","writeFileSync","JSON","stringify","keys","collections","forEach","collectionName","join","writeToFile","location","data","blobToString","Promise","res","rej","writeFile","err","writeJsonToFile","getMeta","loc","readFile","metaContent","parse","setMeta","meta","documentFolder","docId"],"sources":["../../../../src/plugins/backup/file-util.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n BackupMetaFileContent,\n BackupOptions,\n RxDatabase\n} from '../../types/index.d.ts';\nimport { blobToString, now } from '../../plugins/utils/index.ts';\n\n/**\n * ensure that the given folder exists\n */\nexport function ensureFolderExists(folderPath: string): void {\n if (!fs.existsSync(folderPath)) {\n fs.mkdirSync(folderPath, { recursive: true });\n }\n}\n\n/**\n * deletes and recreates the folder\n */\nexport function clearFolder(folderPath: string): void {\n deleteFolder(folderPath);\n ensureFolderExists(folderPath);\n}\n\nexport function deleteFolder(folderPath: string): void {\n // only remove if exists to not raise warning\n if (fs.existsSync(folderPath)) {\n fs.rmdirSync(folderPath, { recursive: true });\n }\n}\n\nexport function prepareFolders(\n database: RxDatabase,\n options: BackupOptions\n) {\n ensureFolderExists(options.directory);\n\n const metaLoc = metaFileLocation(options);\n\n if (!fs.existsSync(metaLoc)) {\n const currentTime = now();\n const metaData: BackupMetaFileContent = {\n createdAt: currentTime,\n updatedAt: currentTime,\n collectionStates: {}\n };\n fs.writeFileSync(metaLoc, JSON.stringify(metaData), 'utf-8');\n }\n\n Object.keys(database.collections).forEach(collectionName => {\n ensureFolderExists(\n path.join(\n options.directory,\n collectionName\n )\n );\n });\n}\n\nexport async function writeToFile(\n location: string,\n data: string | Blob\n): Promise {\n if (typeof data !== 'string') {\n data = await blobToString(data);\n }\n return new Promise(function (res, rej) {\n fs.writeFile(\n location,\n data as string,\n 'utf-8',\n (err) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n }\n );\n });\n}\n\nexport function writeJsonToFile(\n location: string,\n data: any\n): Promise {\n return writeToFile(\n location,\n JSON.stringify(data)\n );\n}\n\nexport function metaFileLocation(options: BackupOptions): string {\n return path.join(\n options.directory,\n 'backup_meta.json'\n );\n}\n\nexport function getMeta(options: BackupOptions): Promise {\n const loc = metaFileLocation(options);\n return new Promise((res, rej) => {\n fs.readFile(loc, 'utf-8', (err, data) => {\n if (err) {\n rej(err);\n } else {\n const metaContent = JSON.parse(data);\n res(metaContent);\n }\n });\n });\n}\n\nexport function setMeta(\n options: BackupOptions,\n meta: BackupMetaFileContent\n): Promise {\n const loc = metaFileLocation(options);\n return writeJsonToFile(loc, meta);\n}\n\nexport function documentFolder(\n options: BackupOptions,\n docId: string\n): string {\n return path.join(\n options.directory,\n docId\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAAA,EAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,IAAA,GAAAF,uBAAA,CAAAC,OAAA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Ae,CAACE,GAAG,EAAEK,IAAI,CAAC;AACrC;AAEO,SAASC,cAAcA,CAC1BnC,OAAsB,EACtBoC,KAAa,EACP;EACN,OAAOrE,IAAI,CAACkD,IAAI,CACZjB,OAAO,CAACC,SAAS,EACjBmC,KACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"file-util.js","names":["fs","_interopRequireWildcard","require","path","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","ensureFolderExists","folderPath","existsSync","mkdirSync","recursive","clearFolder","deleteFolder","rmdirSync","prepareFolders","database","options","directory","metaLoc","metaFileLocation","currentTime","now","metaData","createdAt","updatedAt","collectionStates","writeFileSync","JSON","stringify","keys","collections","forEach","collectionName","join","writeToFile","location","data","blobToString","Promise","res","rej","writeFile","err","writeJsonToFile","getMeta","loc","readFile","metaContent","parse","setMeta","meta","documentFolder","docId"],"sources":["../../../../src/plugins/backup/file-util.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n BackupMetaFileContent,\n BackupOptions,\n RxDatabase\n} from '../../types/index.d.ts';\nimport { blobToString, now } from '../../plugins/utils/index.ts';\n\n/**\n * ensure that the given folder exists\n */\nexport function ensureFolderExists(folderPath: string): void {\n if (!fs.existsSync(folderPath)) {\n fs.mkdirSync(folderPath, { recursive: true });\n }\n}\n\n/**\n * deletes and recreates the folder\n */\nexport function clearFolder(folderPath: string): void {\n deleteFolder(folderPath);\n ensureFolderExists(folderPath);\n}\n\nexport function deleteFolder(folderPath: string): void {\n // only remove if exists to not raise warning\n if (fs.existsSync(folderPath)) {\n fs.rmdirSync(folderPath, { recursive: true });\n }\n}\n\nexport function prepareFolders(\n database: RxDatabase,\n options: BackupOptions\n) {\n ensureFolderExists(options.directory);\n\n const metaLoc = metaFileLocation(options);\n\n if (!fs.existsSync(metaLoc)) {\n const currentTime = now();\n const metaData: BackupMetaFileContent = {\n createdAt: currentTime,\n updatedAt: currentTime,\n collectionStates: {}\n };\n fs.writeFileSync(metaLoc, JSON.stringify(metaData), 'utf-8');\n }\n\n Object.keys(database.collections).forEach(collectionName => {\n ensureFolderExists(\n path.join(\n options.directory,\n collectionName\n )\n );\n });\n}\n\nexport async function writeToFile(\n location: string,\n data: string | Blob\n): Promise {\n if (typeof data !== 'string') {\n data = await blobToString(data);\n }\n return new Promise(function (res, rej) {\n fs.writeFile(\n location,\n data as string,\n 'utf-8',\n (err) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n }\n );\n });\n}\n\nexport function writeJsonToFile(\n location: string,\n data: any\n): Promise {\n return writeToFile(\n location,\n JSON.stringify(data)\n );\n}\n\nexport function metaFileLocation(options: BackupOptions): string {\n return path.join(\n options.directory,\n 'backup_meta.json'\n );\n}\n\nexport function getMeta(options: BackupOptions): Promise {\n const loc = metaFileLocation(options);\n return new Promise((res, rej) => {\n fs.readFile(loc, 'utf-8', (err, data) => {\n if (err) {\n rej(err);\n } else {\n const metaContent = JSON.parse(data);\n res(metaContent);\n }\n });\n });\n}\n\nexport function setMeta(\n options: BackupOptions,\n meta: BackupMetaFileContent\n): Promise {\n const loc = metaFileLocation(options);\n return writeJsonToFile(loc, meta);\n}\n\nexport function documentFolder(\n options: BackupOptions,\n docId: string\n): string {\n return path.join(\n options.directory,\n docId\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAAA,EAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,IAAA,GAAAF,uBAAA,CAAAC,OAAA;AAMA,IAAAE,MAAA,GAAAF,OAAA;AAAiE,SAAAG,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAL,wBAAAK,CAAA,EAAA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CAAC;MACZ,CAAC,MAAM;QACHH,GAAG,CAAC,CAAC;MACT;IACJ,CACJ,CAAC;EACL,CAAC,CAAC;AACN;AAEO,SAASI,eAAeA,CAC3BR,QAAgB,EAChBC,IAAS,EACI;EACb,OAAOF,WAAW,CACdC,QAAQ,EACRR,IAAI,CAACC,SAAS,CAACQ,IAAI,CACvB,CAAC;AACL;AAEO,SAASjB,gBAAgBA,CAACH,OAAsB,EAAU;EAC7D,OAAOhC,IAAI,CAACiD,IAAI,CACZjB,OAAO,CAACC,SAAS,EACjB,kBACJ,CAAC;AACL;AAEO,SAAS2B,OAAOA,CAAC5B,OAAsB,EAAkC;EAC5E,IAAM6B,GAAG,GAAG1B,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAO,IAAIsB,OAAO,CAAC,CAACC,GAAG,EAAEC,GAAG,KAAK;IAC7B3D,EAAE,CAACiE,QAAQ,CAACD,GAAG,EAAE,OAAO,EAAE,CAACH,GAAG,EAAEN,IAAI,KAAK;MACrC,IAAIM,GAAG,EAAE;QACLF,GAAG,CAACE,GAAG,CAAC;MACZ,CAAC,MAAM;QACH,IAAMK,WAAW,GAAGpB,IAAI,CAACqB,KAAK,CAACZ,IAAI,CAAC;QACpCG,GAAG,CAACQ,WAAW,CAAC;MACpB;IACJ,CAAC,CAAC;EACN,CAAC,CAAC;AACN;AAEO,SAASE,OAAOA,CACnBjC,OAAsB,EACtBkC,IAA2B,EACd;EACb,IAAML,GAAG,GAAG1B,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAO2B,eAAe,CAACE,GAAG,EAAEK,IAAI,CAAC;AACrC;AAEO,SAASC,cAAcA,CAC1BnC,OAAsB,EACtBoC,KAAa,EACP;EACN,OAAOpE,IAAI,CAACiD,IAAI,CACZjB,OAAO,CAACC,SAAS,EACjBmC,KACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/backup/index.js b/dist/cjs/plugins/backup/index.js index e140f17edd3..a7ee8c49e9b 100644 --- a/dist/cjs/plugins/backup/index.js +++ b/dist/cjs/plugins/backup/index.js @@ -29,7 +29,7 @@ Object.keys(_fileUtil).forEach(function (key) { }); var _rxStorageHelper = require("../../rx-storage-helper.js"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * Backups a single documents, * returns the paths to all written files diff --git a/dist/cjs/plugins/backup/index.js.map b/dist/cjs/plugins/backup/index.js.map index c9b686ae16f..86627b9be54 100644 --- a/dist/cjs/plugins/backup/index.js.map +++ b/dist/cjs/plugins/backup/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["path","_interopRequireWildcard","require","_rxjs","_index","_fileUtil","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_rxStorageHelper","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","n","__proto__","a","getOwnPropertyDescriptor","u","i","set","backupSingleDocument","rxDocument","options","data","toJSON","writtenFiles","docFolder","documentFolder","primary","clearFolder","fileLocation","join","writeJsonToFile","push","attachments","attachmentsFolder","ensureFolderExists","allAttachments","Promise","all","map","attachment","content","getData","attachmentFileLocation","id","writeToFile","BACKUP_STATES_BY_DB","addToBackupStates","db","state","ar","getFromMapOrCreate","RxBackupState","database","isStopped","subs","persistRunning","PROMISE_RESOLVE_VOID","initialReplicationDone$","BehaviorSubject","internalWriteEvents$","Subject","writeEvents$","asObservable","batchSize","prepareFolders","_proto","persistOnce","then","_persistOnce","_this","meta","getMeta","entries","collections","collectionName","collection","primaryKey","schema","primaryPath","processedDocuments","Set","requestIdlePromise","collectionStates","lastCheckpoint","checkpoint","hasMore","_loop","changesResult","getChangedDocumentsSince","storageInstance","documents","length","docIds","doc","filter","add","elem","pos","arr","indexOf","docs","findByIds","exec","size","Array","from","values","next","name","documentId","files","deleted","docId","deleteFolder","setMeta","getValue","watchForChanges","changes$","changeStream","sub","subscribe","awaitInitialBackup","firstValueFrom","pipe","v","cancel","PROMISE_RESOLVE_FALSE","unsubscribe","PROMISE_RESOLVE_TRUE","backup","backupState","live","RxDBBackupPlugin","rxdb","prototypes","RxDatabase","proto","hooks","preDestroyRxDatabase","after","states"],"sources":["../../../../src/plugins/backup/index.ts"],"sourcesContent":["import * as path from 'node:path';\nimport {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n filter,\n map\n} from 'rxjs';\nimport type {\n BackupOptions,\n RxBackupWriteEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxPlugin\n} from '../../types/index.d.ts';\nimport {\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils/index.ts';\nimport {\n clearFolder,\n deleteFolder,\n documentFolder,\n ensureFolderExists,\n getMeta,\n prepareFolders,\n setMeta,\n writeJsonToFile,\n writeToFile\n} from './file-util.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\n\n\n/**\n * Backups a single documents,\n * returns the paths to all written files\n */\nexport async function backupSingleDocument(\n rxDocument: RxDocument,\n options: BackupOptions\n): Promise {\n const data = rxDocument.toJSON(true);\n const writtenFiles: string[] = [];\n\n const docFolder = documentFolder(options, rxDocument.primary);\n await clearFolder(docFolder);\n\n const fileLocation = path.join(\n docFolder,\n 'document.json'\n );\n await writeJsonToFile(fileLocation, data);\n writtenFiles.push(fileLocation);\n\n if (options.attachments) {\n const attachmentsFolder = path.join(\n docFolder,\n 'attachments'\n );\n ensureFolderExists(attachmentsFolder);\n const attachments = (rxDocument as RxDocument).allAttachments();\n await Promise.all(\n attachments\n .map(async (attachment) => {\n const content = await attachment.getData();\n const attachmentFileLocation = path.join(\n attachmentsFolder,\n attachment.id\n );\n await writeToFile(attachmentFileLocation, content);\n writtenFiles.push(attachmentFileLocation);\n })\n );\n }\n\n return writtenFiles;\n}\n\nconst BACKUP_STATES_BY_DB: WeakMap = new WeakMap();\nfunction addToBackupStates(db: RxDatabase, state: RxBackupState) {\n const ar = getFromMapOrCreate(\n BACKUP_STATES_BY_DB,\n db,\n () => []\n );\n ar.push(state);\n}\n\nexport class RxBackupState {\n public isStopped: boolean = false;\n private subs: Subscription[] = [];\n private persistRunning: Promise = PROMISE_RESOLVE_VOID;\n private initialReplicationDone$: BehaviorSubject = new BehaviorSubject(false as any);\n\n private readonly internalWriteEvents$: Subject = new Subject();\n public readonly writeEvents$: Observable = this.internalWriteEvents$.asObservable();\n\n constructor(\n public readonly database: RxDatabase,\n public readonly options: BackupOptions\n ) {\n if (!this.options.batchSize) {\n this.options.batchSize = 10;\n }\n addToBackupStates(database, this);\n prepareFolders(database, options);\n }\n\n /**\n * Persists all data from all collections,\n * beginning from the oldest sequence checkpoint\n * to the newest one.\n * Do not call this while it is already running.\n * Returns true if there are more documents to process\n */\n public persistOnce() {\n return this.persistRunning = this.persistRunning.then(() => this._persistOnce());\n }\n\n public async _persistOnce() {\n const meta = await getMeta(this.options);\n\n await Promise.all(\n Object\n .entries(this.database.collections)\n .map(async ([collectionName, collection]) => {\n const primaryKey = collection.schema.primaryPath;\n const processedDocuments: Set = new Set();\n\n await this.database.requestIdlePromise();\n\n if (!meta.collectionStates[collectionName]) {\n meta.collectionStates[collectionName] = {};\n }\n let lastCheckpoint = meta.collectionStates[collectionName].checkpoint;\n\n let hasMore = true;\n while (hasMore && !this.isStopped) {\n await this.database.requestIdlePromise();\n const changesResult = await getChangedDocumentsSince(\n collection.storageInstance,\n this.options.batchSize ? this.options.batchSize : 0,\n lastCheckpoint\n );\n lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint;\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n\n const docIds: string[] = changesResult.documents\n .map(doc => doc[primaryKey])\n .filter(id => {\n if (\n processedDocuments.has(id)\n ) {\n return false;\n } else {\n processedDocuments.add(id);\n return true;\n }\n })\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos); // unique\n await this.database.requestIdlePromise();\n\n const docs: Map = await collection.findByIds(docIds).exec();\n if (docs.size === 0) {\n hasMore = false;\n continue;\n }\n await Promise.all(\n Array\n .from(docs.values())\n .map(async (doc) => {\n const writtenFiles = await backupSingleDocument(doc, this.options);\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: doc.primary,\n files: writtenFiles,\n deleted: false\n });\n })\n );\n // handle deleted documents\n await Promise.all(\n docIds\n .filter(docId => !docs.has(docId))\n .map(async (docId) => {\n await deleteFolder(documentFolder(this.options, docId));\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: docId,\n files: [],\n deleted: true\n });\n })\n );\n }\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n await setMeta(this.options, meta);\n })\n );\n\n if (!this.initialReplicationDone$.getValue()) {\n this.initialReplicationDone$.next(true);\n }\n }\n\n public watchForChanges() {\n const collections: RxCollection[] = Object.values(this.database.collections);\n collections.forEach(collection => {\n const changes$ = collection.storageInstance.changeStream();\n const sub = changes$.subscribe(() => {\n this.persistOnce();\n });\n this.subs.push(sub);\n });\n }\n\n /**\n * Returns a promise that resolves when the initial backup is done\n * and the filesystem is in sync with the database state\n */\n public awaitInitialBackup(): Promise {\n return firstValueFrom(\n this.initialReplicationDone$.pipe(\n filter(v => !!v),\n map(() => true)\n )\n );\n }\n\n cancel(): Promise {\n if (this.isStopped) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.isStopped = true;\n this.subs.forEach(sub => sub.unsubscribe());\n return PROMISE_RESOLVE_TRUE;\n }\n}\n\n\nexport function backup(\n this: RxDatabase,\n options: BackupOptions\n): RxBackupState {\n const backupState = new RxBackupState(this, options);\n backupState.persistOnce();\n\n if (options.live) {\n backupState.watchForChanges();\n }\n\n return backupState;\n}\n\nexport * from './file-util.ts';\nexport const RxDBBackupPlugin: RxPlugin = {\n name: 'backup',\n rxdb: true,\n prototypes: {\n RxDatabase(proto: any) {\n proto.backup = backup;\n }\n },\n hooks: {\n preDestroyRxDatabase: {\n after: function preDestroyRxDatabase(db: RxDatabase) {\n const states = BACKUP_STATES_BY_DB.get(db);\n if (states) {\n states.forEach(state => state.cancel());\n }\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAAA,IAAAA,IAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAmBA,IAAAE,MAAA,GAAAF,OAAA;AAMA,IAAAG,SAAA,GAAAH,OAAA;AA2OAI,MAAA,CAAAC,IAAA,CAAAF,SAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,S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AI6F,MAAM,EAAE;UACRA,MAAM,CAACpJ,OAAO,CAACwD,KAAK,IAAIA,KAAK,CAAC6E,MAAM,CAAC,CAAC,CAAC;QAC3C;MACJ;IACJ;EACJ;AACJ,CAAC","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["path","_interopRequireWildcard","require","_rxjs","_index","_fileUtil","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_rxStorageHelper","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","n","__proto__","a","getOwnPropertyDescriptor","u","i","set","backupSingleDocument","rxDocument","options","data","toJSON","writtenFiles","docFolder","documentFolder","primary","clearFolder","fileLocation","join","writeJsonToFile","push","attachments","attachmentsFolder","ensureFolderExists","allAttachments","Promise","all","map","attachment","content","getData","attachmentFileLocation","id","writeToFile","BACKUP_STATES_BY_DB","addToBackupStates","db","state","ar","getFromMapOrCreate","RxBackupState","database","isStopped","subs","persistRunning","PROMISE_RESOLVE_VOID","initialReplicationDone$","BehaviorSubject","internalWriteEvents$","Subject","writeEvents$","asObservable","batchSize","prepareFolders","_proto","persistOnce","then","_persistOnce","_this","meta","getMeta","entries","collections","collectionName","collection","primaryKey","schema","primaryPath","processedDocuments","Set","requestIdlePromise","collectionStates","lastCheckpoint","checkpoint","hasMore","_loop","changesResult","getChangedDocumentsSince","storageInstance","documents","length","docIds","doc","filter","add","elem","pos","arr","indexOf","docs","findByIds","exec","size","Array","from","values","next","name","documentId","files","deleted","docId","deleteFolder","setMeta","getValue","watchForChanges","changes$","changeStream","sub","subscribe","awaitInitialBackup","firstValueFrom","pipe","v","cancel","PROMISE_RESOLVE_FALSE","unsubscribe","PROMISE_RESOLVE_TRUE","backup","backupState","live","RxDBBackupPlugin","rxdb","prototypes","RxDatabase","proto","hooks","preDestroyRxDatabase","after","states"],"sources":["../../../../src/plugins/backup/index.ts"],"sourcesContent":["import * as path from 'node:path';\nimport {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n filter,\n map\n} from 'rxjs';\nimport type {\n BackupOptions,\n RxBackupWriteEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxPlugin\n} from '../../types/index.d.ts';\nimport {\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils/index.ts';\nimport {\n clearFolder,\n deleteFolder,\n documentFolder,\n ensureFolderExists,\n getMeta,\n prepareFolders,\n setMeta,\n writeJsonToFile,\n writeToFile\n} from './file-util.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\n\n\n/**\n * Backups a single documents,\n * returns the paths to all written files\n */\nexport async function backupSingleDocument(\n rxDocument: RxDocument,\n options: BackupOptions\n): Promise {\n const data = rxDocument.toJSON(true);\n const writtenFiles: string[] = [];\n\n const docFolder = documentFolder(options, rxDocument.primary);\n await clearFolder(docFolder);\n\n const fileLocation = path.join(\n docFolder,\n 'document.json'\n );\n await writeJsonToFile(fileLocation, data);\n writtenFiles.push(fileLocation);\n\n if (options.attachments) {\n const attachmentsFolder = path.join(\n docFolder,\n 'attachments'\n );\n ensureFolderExists(attachmentsFolder);\n const attachments = (rxDocument as RxDocument).allAttachments();\n await Promise.all(\n attachments\n .map(async (attachment) => {\n const content = await attachment.getData();\n const attachmentFileLocation = path.join(\n attachmentsFolder,\n attachment.id\n );\n await writeToFile(attachmentFileLocation, content);\n writtenFiles.push(attachmentFileLocation);\n })\n );\n }\n\n return writtenFiles;\n}\n\nconst BACKUP_STATES_BY_DB: WeakMap = new WeakMap();\nfunction addToBackupStates(db: RxDatabase, state: RxBackupState) {\n const ar = getFromMapOrCreate(\n BACKUP_STATES_BY_DB,\n db,\n () => []\n );\n ar.push(state);\n}\n\nexport class RxBackupState {\n public isStopped: boolean = false;\n private subs: Subscription[] = [];\n private persistRunning: Promise = PROMISE_RESOLVE_VOID;\n private initialReplicationDone$: BehaviorSubject = new BehaviorSubject(false as any);\n\n private readonly internalWriteEvents$: Subject = new Subject();\n public readonly writeEvents$: Observable = this.internalWriteEvents$.asObservable();\n\n constructor(\n public readonly database: RxDatabase,\n public readonly options: BackupOptions\n ) {\n if (!this.options.batchSize) {\n this.options.batchSize = 10;\n }\n addToBackupStates(database, this);\n prepareFolders(database, options);\n }\n\n /**\n * Persists all data from all collections,\n * beginning from the oldest sequence checkpoint\n * to the newest one.\n * Do not call this while it is already running.\n * Returns true if there are more documents to process\n */\n public persistOnce() {\n return this.persistRunning = this.persistRunning.then(() => this._persistOnce());\n }\n\n public async _persistOnce() {\n const meta = await getMeta(this.options);\n\n await Promise.all(\n Object\n .entries(this.database.collections)\n .map(async ([collectionName, collection]) => {\n const primaryKey = collection.schema.primaryPath;\n const processedDocuments: Set = new Set();\n\n await this.database.requestIdlePromise();\n\n if (!meta.collectionStates[collectionName]) {\n meta.collectionStates[collectionName] = {};\n }\n let lastCheckpoint = meta.collectionStates[collectionName].checkpoint;\n\n let hasMore = true;\n while (hasMore && !this.isStopped) {\n await this.database.requestIdlePromise();\n const changesResult = await getChangedDocumentsSince(\n collection.storageInstance,\n this.options.batchSize ? this.options.batchSize : 0,\n lastCheckpoint\n );\n lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint;\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n\n const docIds: string[] = changesResult.documents\n .map(doc => doc[primaryKey])\n .filter(id => {\n if (\n processedDocuments.has(id)\n ) {\n return false;\n } else {\n processedDocuments.add(id);\n return true;\n }\n })\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos); // unique\n await this.database.requestIdlePromise();\n\n const docs: Map = await collection.findByIds(docIds).exec();\n if (docs.size === 0) {\n hasMore = false;\n continue;\n }\n await Promise.all(\n Array\n .from(docs.values())\n .map(async (doc) => {\n const writtenFiles = await backupSingleDocument(doc, this.options);\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: doc.primary,\n files: writtenFiles,\n deleted: false\n });\n })\n );\n // handle deleted documents\n await Promise.all(\n docIds\n .filter(docId => !docs.has(docId))\n .map(async (docId) => {\n await deleteFolder(documentFolder(this.options, docId));\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: docId,\n files: [],\n deleted: true\n });\n })\n );\n }\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n await setMeta(this.options, meta);\n })\n );\n\n if (!this.initialReplicationDone$.getValue()) {\n this.initialReplicationDone$.next(true);\n }\n }\n\n public watchForChanges() {\n const collections: RxCollection[] = Object.values(this.database.collections);\n collections.forEach(collection => {\n const changes$ = collection.storageInstance.changeStream();\n const sub = changes$.subscribe(() => {\n this.persistOnce();\n });\n this.subs.push(sub);\n });\n }\n\n /**\n * Returns a promise that resolves when the initial backup is done\n * and the filesystem is in sync with the database state\n */\n public awaitInitialBackup(): Promise {\n return firstValueFrom(\n this.initialReplicationDone$.pipe(\n filter(v => !!v),\n map(() => true)\n )\n );\n }\n\n cancel(): Promise {\n if (this.isStopped) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.isStopped = true;\n this.subs.forEach(sub => sub.unsubscribe());\n return PROMISE_RESOLVE_TRUE;\n }\n}\n\n\nexport function backup(\n this: RxDatabase,\n options: BackupOptions\n): RxBackupState {\n const backupState = new RxBackupState(this, options);\n backupState.persistOnce();\n\n if (options.live) {\n backupState.watchForChanges();\n }\n\n return backupState;\n}\n\nexport * from './file-util.ts';\nexport const RxDBBackupPlugin: RxPlugin = {\n name: 'backup',\n rxdb: true,\n prototypes: {\n RxDatabase(proto: any) {\n proto.backup = backup;\n }\n },\n hooks: {\n preDestroyRxDatabase: {\n after: function preDestroyRxDatabase(db: RxDatabase) {\n const states = BACKUP_STATES_BY_DB.get(db);\n if (states) {\n states.forEach(state => state.cancel());\n }\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAAA,IAAAA,IAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,KAAA,GA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dyB,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAUA,CAACC,KAAU,EAAE;MACnBA,KAAK,CAACP,MAAM,GAAGA,MAAM;IACzB;EACJ,CAAC;EACDQ,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAE,SAASD,oBAAoBA,CAAC3F,EAAc,EAAE;QACjD,IAAM6F,MAAM,GAAG/F,mBAAmB,CAAC5C,GAAG,CAAC8C,EAAE,CAAC;QAC1C,IAAI6F,MAAM,EAAE;UACRA,MAAM,CAACpJ,OAAO,CAACwD,KAAK,IAAIA,KAAK,CAAC6E,MAAM,CAAC,CAAC,CAAC;QAC3C;MACJ;IACJ;EACJ;AACJ,CAAC","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/local-documents/rx-local-document.js b/dist/cjs/plugins/local-documents/rx-local-document.js index df6c1bf90da..74a8919ba6b 100644 --- a/dist/cjs/plugins/local-documents/rx-local-document.js +++ b/dist/cjs/plugins/local-documents/rx-local-document.js @@ -18,7 +18,6 @@ var _localDocumentsHelper = require("./local-documents-helper.js"); var _rxDatabase = require("../../rx-database.js"); var RxDocumentParent = (0, _rxDocument.createRxDocumentConstructor)(); var RxLocalDocumentClass = /*#__PURE__*/function (_RxDocumentParent) { - (0, _inheritsLoose2.default)(RxLocalDocumentClass, _RxDocumentParent); function RxLocalDocumentClass(id, jsonData, parent) { var _this2; _this2 = _RxDocumentParent.call(this, null, jsonData) || this; @@ -26,6 +25,7 @@ var RxLocalDocumentClass = /*#__PURE__*/function (_RxDocumentParent) { _this2.parent = parent; return _this2; } + (0, _inheritsLoose2.default)(RxLocalDocumentClass, _RxDocumentParent); return RxLocalDocumentClass; }(RxDocumentParent); var RxLocalDocumentPrototype = { diff --git a/dist/cjs/plugins/local-documents/rx-local-document.js.map b/dist/cjs/plugins/local-documents/rx-local-document.js.map index 8fd2876df85..54b87cdecdf 100644 --- a/dist/cjs/plugins/local-documents/rx-local-document.js.map +++ b/dist/cjs/plugins/local-documents/rx-local-document.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-local-document.js","names":["_rxjs","require","_overwritable","_rxChangeEvent","_rxDocument","_rxError","_rxStorageHelper","_index","_localDocumentsHelper","_rxDatabase","RxDocumentParent","createRxDocumentConstructor","RxLocalDocumentClass","_RxDocumentParent","_inheritsLoose2","default","id","jsonData","parent","_this2","call","RxLocalDocumentPrototype","isLocal","allAttachments$","newRxError","document","primaryPath","primary","$","_this","state","getFromMapOrThrow","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","pipe","filter","changeEvent","documentId","map","getDocumentDataOfRxChangeEvent","startWith","docCache","getLatestDocumentData","distinctUntilChanged","prev","curr","_rev","docData","getCachedRxDocument","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","$$","db","getRxDatabaseFromLocalDocument","reactivity","getReactivityFactory","fromObservable","getLatest","_data","deleted$$","deleted$","deleted","latestDocData","get","objPath","undefined","newRxTypeError","valueObj","getProperty","overwritable","deepFreezeWhenDevMode","get$","isDevMode","includes","localDocument","data","get$$","incrementalModify","mutationFunction","getLocalDocStateByParent","incrementalWriteQueue","addWrite","then","result","incrementalPatch","patch","Object","entries","forEach","k","v","_saveData","newData","oldData","storageInstance","bulkWrite","previous","res","docResult","success","error","flatClone","remove","writeData","_deleted","_meta","getDefaultRxDocumentMeta","getDefaultRevision","_attachments","writeSingle","writeResult","INIT_DONE","_init","docBaseProto","basePrototype","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","setPrototypeOf","prototype","doc","isRxDatabase","database"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs';\nimport { overwritable } from '../../overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from '../../rx-change-event.ts';\nimport {\n basePrototype,\n createRxDocumentConstructor\n} from '../../rx-document.ts';\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error.ts';\nimport { writeSingle } from '../../rx-storage-helper.ts';\nimport type {\n LocalDocumentModifyFunction,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types/index.d.ts';\nimport {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromMapOrThrow,\n getProperty,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from './local-documents-helper.ts';\nimport { isRxDatabase } from '../../rx-database.ts';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $(): Observable> {\n const _this: RxLocalDocumentClass = this as any;\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n return _this.parent.$.pipe(\n filter(changeEvent => changeEvent.documentId === this.primary),\n filter(changeEvent => changeEvent.isLocal),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(state.docCache.getLatestDocumentData(this.primary)),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n map(docData => state.docCache.getCachedRxDocument(docData)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n ) as Observable;\n },\n get $$(): any {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.$,\n _this.getLatest()._data\n );\n },\n get deleted$$() {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.deleted$,\n _this.getLatest().deleted\n );\n },\n getLatest(this: RxLocalDocument): RxLocalDocument {\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n const latestDocData = state.docCache.getLatestDocumentData(this.primary);\n return state.docCache.getCachedRxDocument(latestDocData) as any;\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = getProperty(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (overwritable.isDevMode()) {\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n }\n return this.$\n .pipe(\n map(localDocument => localDocument._data),\n map(data => getProperty(data, objPath)),\n distinctUntilChanged()\n );\n },\n get$$(this: RxDocument, objPath: string) {\n const db = getRxDatabaseFromLocalDocument(this as any);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n this.get$(objPath),\n this.getLatest().get(objPath)\n );\n },\n async incrementalModify(\n this: RxLocalDocument,\n mutationFunction: LocalDocumentModifyFunction\n ) {\n const state = await getLocalDocStateByParent(this.parent);\n\n return state.incrementalWriteQueue.addWrite(\n this._data as any,\n async (docData) => {\n docData.data = await mutationFunction(docData.data, this);\n return docData;\n }\n ).then(result => state.docCache.getCachedRxDocument(result as any));\n },\n incrementalPatch(patch: Partial) {\n return this.incrementalModify((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._data;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[0];\n if (!docResult) {\n throw res.error[0];\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: RxLocalDocument): Promise> {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this._data.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then((writeResult) => state.docCache.getCachedRxDocument(writeResult) as any);\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n data: RxDocumentData>,\n parent: any\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(data.id, data, parent);\n Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype);\n newDoc.prototype = RxLocalDocumentPrototype;\n return newDoc as any;\n}\n\n\nexport function getRxDatabaseFromLocalDocument(doc: RxLocalDocument | RxLocalDocumentClass) {\n const parent = doc.parent;\n if (isRxDatabase(parent)) {\n return parent;\n } else {\n return (parent as RxCollection).database;\n }\n}\n"],"mappings":";;;;;;;;;AACA,IAAAA,KAAA,GAAAC,OAAA;AAOA,IAAAC,aAAA,GAAAD,OAAA;AACA,IAAAE,cAAA,GAAAF,OAAA;AACA,IAAAG,WAAA,GAAAH,OAAA;AAIA,IAAAI,QAAA,GAAAJ,OAAA;AAIA,IAAAK,gBAAA,GAAAL,OAAA;AAWA,IAAAM,MAAA,GAAAN,OAAA;AAQA,IAAAO,qBAAA,GAAAP,OAAA;AACA,IAAAQ,WAAA,GAAAR,OAAA;AAEA,IAAMS,gBAAgB,GAAG,IAAAC,uCAA2B,EAAC,CAAQ;AAAC,IAExDC,oBAAoB,0BAAAC,iBAAA;EAAA,IAAAC,eAAA,CAAAC,OAAA,EAAAH,oBAAA,EAAAC,iBAAA;EACtB,SAAAD,qBACoBI,EAAU,EAC1BC,QAAiB,EACDC,MAAiC,EACnD;IAAA,IAAAC,MAAA;IACEA,MAAA,GAAAN,iBAAA,CAAAO,IAAA,OAAM,IAAI,EAAEH,QAAQ,CAAC;IAACE,MAAA,CAJNH,EAAU,GAAVA,EAAU;IAAAG,MAAA,CAEVD,MAAiC,GAAjCA,MAAiC;IAAA,OAAAC,MAAA;EAGrD;EAAC,OAAAP,oBAAA;AAAA,EAP6CF,gBAAgB;AAYlE,IAAMW,wBAA6B,GAAG;EAClC,IAAIC,OAAOA,CAAA,EAAG;IACV,OAAO,IAAI;EACf,CAAC;EAED;EACA;EACA;EACA,IAAIC,eAAeA,CAAA,EAAG;IAClB;IACA,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;MACpBC,QAAQ,EAAE;IACd,CAAC,CAAC;EACN,CAAC;EACD,IAAIC,WAAWA,CAAA,EAAG;IACd,OAAO,IAAI;EACf,CAAC;EACD,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E,CAAC;AAIM,SAASmC,qBAAqBA,CACjCjD,IAAkD,EAClDxD,MAAW,EACa;EACxB6F,KAAK,CAAC,CAAC;EACP,IAAMa,MAAM,GAAG,IAAIhH,oBAAoB,CAAC8D,IAAI,CAAC1D,EAAE,EAAE0D,IAAI,EAAExD,MAAM,CAAC;EAC9DmE,MAAM,CAACwC,cAAc,CAACD,MAAM,EAAEvG,wBAAwB,CAAC;EACvDuG,MAAM,CAACE,SAAS,GAAGzG,wBAAwB;EAC3C,OAAOuG,MAAM;AACjB;AAGO,SAASxE,8BAA8BA,CAAC2E,GAAgD,EAAE;EAC7F,IAAM7G,MAAM,GAAG6G,GAAG,CAAC7G,MAAM;EACzB,IAAI,IAAA8G,wBAAY,EAAC9G,MAAM,CAAC,EAAE;IACtB,OAAOA,MAAM;EACjB,CAAC,MAAM;IACH,OAAQA,MAAM,CAAkB+G,QAAQ;EAC5C;AACJ","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-local-document.js","names":["_rxjs","require","_overwritable","_rxChangeEvent","_rxDocument","_rxError","_rxStorageHelper","_index","_localDocumentsHelper","_rxDatabase","RxDocumentParent","createRxDocumentConstructor","RxLocalDocumentClass","_RxDocumentParent","id","jsonData","parent","_this2","call","_inheritsLoose2","default","RxLocalDocumentPrototype","isLocal","allAttachments$","newRxError","document","primaryPath","primary","$","_this","state","getFromMapOrThrow","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","pipe","filter","changeEvent","documentId","map","getDocumentDataOfRxChangeEvent","startWith","docCache","getLatestDocumentData","distinctUntilChanged","prev","curr","_rev","docData","getCachedRxDocument","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","$$","db","getRxDatabaseFromLocalDocument","reactivity","getReactivityFactory","fromObservable","getLatest","_data","deleted$$","deleted$","deleted","latestDocData","get","objPath","undefined","newRxTypeError","valueObj","getProperty","overwritable","deepFreezeWhenDevMode","get$","isDevMode","includes","localDocument","data","get$$","incrementalModify","mutationFunction","getLocalDocStateByParent","incrementalWriteQueue","addWrite","then","result","incrementalPatch","patch","Object","entries","forEach","k","v","_saveData","newData","oldData","storageInstance","bulkWrite","previous","res","docResult","success","error","flatClone","remove","writeData","_deleted","_meta","getDefaultRxDocumentMeta","getDefaultRevision","_attachments","writeSingle","writeResult","INIT_DONE","_init","docBaseProto","basePrototype","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","setPrototypeOf","prototype","doc","isRxDatabase","database"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs';\nimport { overwritable } from '../../overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from '../../rx-change-event.ts';\nimport {\n basePrototype,\n createRxDocumentConstructor\n} from '../../rx-document.ts';\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error.ts';\nimport { writeSingle } from '../../rx-storage-helper.ts';\nimport type {\n LocalDocumentModifyFunction,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types/index.d.ts';\nimport {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromMapOrThrow,\n getProperty,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from './local-documents-helper.ts';\nimport { isRxDatabase } from '../../rx-database.ts';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $(): Observable> {\n const _this: RxLocalDocumentClass = this as any;\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n return _this.parent.$.pipe(\n filter(changeEvent => changeEvent.documentId === this.primary),\n filter(changeEvent => changeEvent.isLocal),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(state.docCache.getLatestDocumentData(this.primary)),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n map(docData => state.docCache.getCachedRxDocument(docData)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n ) as Observable;\n },\n get $$(): any {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.$,\n _this.getLatest()._data\n );\n },\n get deleted$$() {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.deleted$,\n _this.getLatest().deleted\n );\n },\n getLatest(this: RxLocalDocument): RxLocalDocument {\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n const latestDocData = state.docCache.getLatestDocumentData(this.primary);\n return state.docCache.getCachedRxDocument(latestDocData) as any;\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = getProperty(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (overwritable.isDevMode()) {\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n }\n return this.$\n .pipe(\n map(localDocument => localDocument._data),\n map(data => getProperty(data, objPath)),\n distinctUntilChanged()\n );\n },\n get$$(this: RxDocument, objPath: string) {\n const db = getRxDatabaseFromLocalDocument(this as any);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n this.get$(objPath),\n this.getLatest().get(objPath)\n );\n },\n async incrementalModify(\n this: RxLocalDocument,\n mutationFunction: LocalDocumentModifyFunction\n ) {\n const state = await getLocalDocStateByParent(this.parent);\n\n return state.incrementalWriteQueue.addWrite(\n this._data as any,\n async (docData) => {\n docData.data = await mutationFunction(docData.data, this);\n return docData;\n }\n ).then(result => state.docCache.getCachedRxDocument(result as any));\n },\n incrementalPatch(patch: Partial) {\n return this.incrementalModify((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._data;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[0];\n if (!docResult) {\n throw res.error[0];\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: RxLocalDocument): Promise> {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this._data.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then((writeResult) => state.docCache.getCachedRxDocument(writeResult) as any);\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n data: RxDocumentData>,\n parent: any\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(data.id, data, parent);\n Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype);\n newDoc.prototype = RxLocalDocumentPrototype;\n return newDoc as any;\n}\n\n\nexport function getRxDatabaseFromLocalDocument(doc: RxLocalDocument | RxLocalDocumentClass) {\n const parent = doc.parent;\n if (isRxDatabase(parent)) {\n return parent;\n } else {\n return (parent as RxCollection).database;\n }\n}\n"],"mappings":";;;;;;;;;AACA,IAAAA,KAAA,GAAAC,OAAA;AAOA,IAAAC,aAAA,GAAAD,OAAA;AACA,IAAAE,cAAA,GAAAF,OAAA;AACA,IAAAG,WAAA,GAAAH,OAAA;AAIA,IAAAI,QAAA,GAAAJ,OAAA;AAIA,IAAAK,gBAAA,GAAAL,OAAA;AAWA,IAAAM,MAAA,GAAAN,OAAA;AAQA,IAAAO,qBAAA,GAAAP,OAAA;AACA,IAAAQ,WAAA,GAAAR,OAAA;AAEA,IAAMS,gBAAgB,GAAG,IAAAC,uCAA2B,EAAC,CAAQ;AAAC,IAExDC,oBAAoB,0BAAAC,iBAAA;EACtB,SAAAD,qBACoBE,EAAU,EAC1BC,QAAiB,EACDC,MAAiC,EACnD;IAAA,IAAAC,MAAA;IACEA,MAAA,GAAAJ,iBAAA,CAAA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E+F,GAAG,CAAC;IAC7E,IAAIC,MAAM,EAAE;IACZ,IAAME,IAAS,GAAGlC,MAAM,CAACiC,wBAAwB,CAACN,YAAY,EAAEI,GAAG,CAAC;IACpE/B,MAAM,CAACmC,cAAc,CAACnG,wBAAwB,EAAE+F,GAAG,EAAEG,IAAI,CAAC;EAC9D,CAAC,CAAC;;EAGF;AACJ;AACA;AACA;EACI,IAAME,cAAc,GAAIjC,CAAS,IAAK,MAAM;IACxC,MAAM,IAAAhE,mBAAU,EAAC,KAAK,EAAE;MACpBkG,YAAY,EAAElC;IAClB,CAAC,CAAC;EACN,CAAC;EACD,CACI,UAAU,EACV,QAAQ,EACR,eAAe,EACf,eAAe,EACf,gBAAgB,CACnB,CAACD,OAAO,CAAEC,CAAS,IAAKnE,wBAAwB,CAACmE,CAAC,CAAC,GAAGiC,cAAc,CAACjC,CAAC,CAAC,CAAC;AAC7E,CAAC;AAIM,SAASmC,qBAAqBA,CACjCjD,IAAkD,EAClD1D,MAAW,EACa;EACxB+F,KAAK,CAAC,CAAC;EACP,IAAMa,MAAM,GAAG,IAAIhH,oBAAoB,CAAC8D,IAAI,CAAC5D,EAAE,EAAE4D,IAAI,EAAE1D,MAAM,CAAC;EAC9DqE,MAAM,CAACwC,cAAc,CAACD,MAAM,EAAEvG,wBAAwB,CAAC;EACvDuG,MAAM,CAACE,SAAS,GAAGzG,wBAAwB;EAC3C,OAAOuG,MAAM;AACjB;AAGO,SAASxE,8BAA8BA,CAAC2E,GAAgD,EAAE;EAC7F,IAAM/G,MAAM,GAAG+G,GAAG,CAAC/G,MAAM;EACzB,IAAI,IAAAgH,wBAAY,EAAChH,MAAM,CAAC,EAAE;IACtB,OAAOA,MAAM;EACjB,CAAC,MAAM;IACH,OAAQA,MAAM,CAAkBiH,QAAQ;EAC5C;AACJ","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-couchdb/index.js b/dist/cjs/plugins/replication-couchdb/index.js index ae29bd9ebea..8afe95fffac 100644 --- a/dist/cjs/plugins/replication-couchdb/index.js +++ b/dist/cjs/plugins/replication-couchdb/index.js @@ -45,7 +45,6 @@ Object.keys(_couchdbTypes).forEach(function (key) { * This plugin can be used to sync collections with a remote CouchDB endpoint. */ var RxCouchDBReplicationState = exports.RxCouchDBReplicationState = /*#__PURE__*/function (_RxReplicationState) { - (0, _inheritsLoose2.default)(RxCouchDBReplicationState, _RxReplicationState); function RxCouchDBReplicationState(url, fetch, replicationIdentifier, collection, pull, push, live = true, retryTime = 1000 * 5, autoStart = true) { var _this; _this = _RxReplicationState.call(this, replicationIdentifier, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; @@ -60,6 +59,7 @@ var RxCouchDBReplicationState = exports.RxCouchDBReplicationState = /*#__PURE__* _this.autoStart = autoStart; return _this; } + (0, _inheritsLoose2.default)(RxCouchDBReplicationState, _RxReplicationState); return RxCouchDBReplicationState; }(_index3.RxReplicationState); function replicateCouchDB(options) { diff --git a/dist/cjs/plugins/replication-couchdb/index.js.map b/dist/cjs/plugins/replication-couchdb/index.js.map index fba3ee9ced7..d5182034d82 100644 --- a/dist/cjs/plugins/replication-couchdb/index.js.map +++ b/dist/cjs/plugins/replication-couchdb/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_index","require","_index2","_index3","_index4","_rxjs","_couchdbHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_replicationHelper","_couchdbTypes","RxCouchDBReplicationState","_RxReplicationState","_inheritsLoose2","default","url","fetch","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","RxReplicationState","replicateCouchDB","options","conflictHandler","addRxPlugin","RxDBLeaderElectionPlugin","primaryPath","schema","endsWith","newRxError","args","name","flatClone","waitForLeadership","pullStream$","Subject","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","mergeUrlQueryParams","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","response","replicationState","jsonResponse","json","results","documents","map","row","couchDBDocToRxDocData","ensureNotFalsy","doc","checkpoint","last_seq","modifier","stream$","asObservable","initialCheckpoint","replicationPrimitivesPush","rows","conflicts","pushRowsById","Map","id","newDocumentState","set","docsByIdResponse","method","headers","body","JSON","stringify","deleted","docsByIdRows","nonConflictRows","remoteRevById","Promise","all","getFromMapOrThrow","realMasterState","pushRow","conflictHandlerResult","assumedMasterState","isEqual","_rev","docs","docId","sendDoc","has","couchSwapPrimaryToId","responseJson","conflictAgainIds","writeResultRow","isConflict","error","ok","length","getConflictDocsUrl","conflictResponse","conflictResponseJson","conflictAgainRow","getDefaultFetch","startBefore","start","bind","lastRequestStartTime","now","isStopped","err","subjects","next","errorToPlainJson","promiseWait","awaitRetry","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * This plugin can be used to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrThrow,\n now,\n promiseWait\n} from '../../plugins/utils/index.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n CouchdbChangesResult,\n CouchBulkDocResultRow,\n CouchAllDocsResponse,\n RxConflictHandler\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDB\n} from './couchdb-types.ts';\nimport {\n couchDBDocToRxDocData,\n mergeUrlQueryParams,\n couchSwapPrimaryToId,\n getDefaultFetch\n} from './couchdb-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './couchdb-helper.ts';\nexport * from './couchdb-types.ts';\n\nexport class RxCouchDBReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateCouchDB(\n options: SyncOptionsCouchDB\n) {\n const collection = options.collection;\n const conflictHandler: RxConflictHandler = collection.conflictHandler;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const primaryPath = options.collection.schema.primaryPath;\n\n if (!options.url.endsWith('/')) {\n throw newRxError('RC_COUCHDB_1', {\n args: {\n collection: options.collection.name,\n url: options.url\n }\n });\n }\n\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: CouchdbChangesResult = await response.json();\n if (!jsonResponse.results) {\n throw newRxError('RC_COUCHDB_2', {\n args: { jsonResponse }\n });\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable(),\n initialCheckpoint: options.pull.initialCheckpoint\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const conflicts: WithDeleted[] = [];\n const pushRowsById = new Map>();\n rows.forEach(row => {\n const id = (row.newDocumentState as any)[primaryPath];\n pushRowsById.set(id, row);\n });\n\n /**\n * First get the current master state from the remote\n * to check for conflicts\n */\n const docsByIdResponse = await replicationState.fetch(\n options.url + '_all_docs?' + mergeUrlQueryParams({}),\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify({\n keys: rows.map(row => (row.newDocumentState as any)[primaryPath]),\n include_docs: true,\n deleted: 'ok'\n })\n }\n );\n const docsByIdRows: CouchAllDocsResponse = await docsByIdResponse.json();\n const nonConflictRows: typeof rows = [];\n const remoteRevById = new Map();\n await Promise.all(\n docsByIdRows.rows.map(async (row) => {\n if (!row.doc) {\n nonConflictRows.push(getFromMapOrThrow(pushRowsById, row.key));\n return;\n }\n const realMasterState: WithDeleted = couchDBDocToRxDocData(primaryPath, row.doc);\n const pushRow = getFromMapOrThrow(pushRowsById, row.id);\n const conflictHandlerResult = await conflictHandler({\n realMasterState,\n newDocumentState: pushRow.assumedMasterState\n }, 'couchdb-push-1');\n if (conflictHandlerResult.isEqual) {\n remoteRevById.set(row.id, row.doc._rev);\n nonConflictRows.push(pushRow);\n } else {\n conflicts.push(realMasterState);\n }\n })\n );\n\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: nonConflictRows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n const sendDoc = flatClone(row.newDocumentState);\n if (remoteRevById.has(docId)) {\n (sendDoc as any)._rev = getFromMapOrThrow(remoteRevById, docId);\n }\n return couchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: CouchBulkDocResultRow[] = await response.json();\n\n // get conflicting writes\n const conflictAgainIds: string[] = [];\n responseJson.forEach(writeResultRow => {\n const isConflict = writeResultRow.error === 'conflict';\n if (!writeResultRow.ok && !isConflict) {\n throw newRxError('SNH', { args: { writeResultRow } });\n }\n if (isConflict) {\n conflictAgainIds.push(writeResultRow.id);\n }\n });\n\n if (conflictAgainIds.length === 0) {\n return conflicts;\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflictAgainIds)\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: CouchAllDocsResponse = await conflictResponse.json();\n conflictResponseJson.rows.forEach(conflictAgainRow => {\n conflicts.push(couchDBDocToRxDocData(collection.schema.primaryPath, conflictAgainRow.doc));\n });\n\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier,\n initialCheckpoint: options.push.initialCheckpoint\n };\n }\n\n const replicationState = new RxCouchDBReplicationState(\n options.url,\n options.fetch ? options.fetch : getDefaultFetch(),\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n let lastRequestStartTime = now();\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: CouchdbChangesResult;\n try {\n lastRequestStartTime = now();\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err: any) {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n args: { url },\n error: errorToPlainJson(err)\n })\n );\n\n if (lastRequestStartTime < (now() - replicationState.retryTime)) {\n /**\n * Last request start was long ago,\n * so we directly retry.\n * This mostly happens on timeouts\n * which are normal behavior for long polling requests.\n */\n await promiseWait(0);\n } else {\n // await next tick here otherwise we could go in to a 100% CPU blocking cycle.\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAGA,IAAAA,MAAA,GAAAC,OAAA;AASA,IAAAC,OAAA,GAAAD,OAAA;AAYA,IAAAE,OAAA,GAAAF,OAAA;AAIA,IAAAG,OAAA,GAAAH,OAAA;AAMA,IAAAI,KAAA,GAAAJ,OAAA;AAMA,IAAAK,cAAA,GAAAL,OAAA;AAQAM,MAAA,CAAAC,IAAA,CAAAF,cAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,cAAA,CAAAI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IAAMqC,SAAmC,GAAGH,YAAY,CAACE,OAAO,CAC3DE,GAAG,CAACC,GAAG,IAAI,IAAAC,oCAAqB,EAAC5C,UAAU,CAACc,MAAM,CAACD,WAAW,EAAE,IAAAgC,qBAAc,EAACF,GAAG,CAACG,GAAG,CAAC,CAAC,CAAC;UAC9Ff,KAAK,GAAGO,YAAY,CAACU,QAAQ;UAE7B3B,WAAW,CAACoF,IAAI,CAAC;YACbhE,SAAS;YACTM,UAAU,EAAE;cACRf,QAAQ,EAAEM,YAAY,CAACU;YAC3B;UACJ,CAAC,CAAC;QACN;MACJ,CAAC,EAAE,CAAC;MACJ,OAAOiD,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAY,oCAA4B,EAACpG,OAAO,CAACW,iBAAiB,EAAEiB,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["_index","require","_index2","_index3","_index4","_rxjs","_couchdbHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_replicationHelper","_couchdbTypes","RxCouchDBReplicationState","_RxReplicationState","url","fetch","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","_inheritsLoose2","default","RxReplicationState","replicateCouchDB","options","conflictHandler","addRxPlugin","RxDBLeaderElectionPlugin","primaryPath","schema","endsWith","newRxError","args","name","flatClone","waitForLeadership","pullStream$","Subject","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","mergeUrlQueryParams","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","response","replicationState","jsonResponse","json","results","documents","map","row","couchDBDocToRxDocData","ensureNotFalsy","doc","checkpoint","last_seq","modifier","stream$","asObservable","initialCheckpoint","replicationPrimitivesPush","rows","conflicts","pushRowsById","Map","id","newDocumentState","set","docsByIdResponse","method","headers","body","JSON","stringify","deleted","docsByIdRows","nonConflictRows","remoteRevById","Promise","all","getFromMapOrThrow","realMasterState","pushRow","conflictHandlerResult","assumedMasterState","isEqual","_rev","docs","docId","sendDoc","has","couchSwapPrimaryToId","responseJson","conflictAgainIds","writeResultRow","isConflict","error","ok","length","getConflictDocsUrl","conflictResponse","conflictResponseJson","conflictAgainRow","getDefaultFetch","startBefore","start","bind","lastRequestStartTime","now","isStopped","err","subjects","next","errorToPlainJson","promiseWait","awaitRetry","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * This plugin can be used to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrThrow,\n now,\n promiseWait\n} from '../../plugins/utils/index.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n CouchdbChangesResult,\n CouchBulkDocResultRow,\n CouchAllDocsResponse,\n RxConflictHandler\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDB\n} from './couchdb-types.ts';\nimport {\n couchDBDocToRxDocData,\n mergeUrlQueryParams,\n couchSwapPrimaryToId,\n getDefaultFetch\n} from './couchdb-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './couchdb-helper.ts';\nexport * from './couchdb-types.ts';\n\nexport class RxCouchDBReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateCouchDB(\n options: SyncOptionsCouchDB\n) {\n const collection = options.collection;\n const conflictHandler: RxConflictHandler = collection.conflictHandler;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const primaryPath = options.collection.schema.primaryPath;\n\n if (!options.url.endsWith('/')) {\n throw newRxError('RC_COUCHDB_1', {\n args: {\n collection: options.collection.name,\n url: options.url\n }\n });\n }\n\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: CouchdbChangesResult = await response.json();\n if (!jsonResponse.results) {\n throw newRxError('RC_COUCHDB_2', {\n args: { jsonResponse }\n });\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable(),\n initialCheckpoint: options.pull.initialCheckpoint\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const conflicts: WithDeleted[] = [];\n const pushRowsById = new Map>();\n rows.forEach(row => {\n const id = (row.newDocumentState as any)[primaryPath];\n pushRowsById.set(id, row);\n });\n\n /**\n * First get the current master state from the remote\n * to check for conflicts\n */\n const docsByIdResponse = await replicationState.fetch(\n options.url + '_all_docs?' + mergeUrlQueryParams({}),\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify({\n keys: rows.map(row => (row.newDocumentState as any)[primaryPath]),\n include_docs: true,\n deleted: 'ok'\n })\n }\n );\n const docsByIdRows: CouchAllDocsResponse = await docsByIdResponse.json();\n const nonConflictRows: typeof rows = [];\n const remoteRevById = new Map();\n await Promise.all(\n docsByIdRows.rows.map(async (row) => {\n if (!row.doc) {\n nonConflictRows.push(getFromMapOrThrow(pushRowsById, row.key));\n return;\n }\n const realMasterState: WithDeleted = couchDBDocToRxDocData(primaryPath, row.doc);\n const pushRow = getFromMapOrThrow(pushRowsById, row.id);\n const conflictHandlerResult = await conflictHandler({\n realMasterState,\n newDocumentState: pushRow.assumedMasterState\n }, 'couchdb-push-1');\n if (conflictHandlerResult.isEqual) {\n remoteRevById.set(row.id, row.doc._rev);\n nonConflictRows.push(pushRow);\n } else {\n conflicts.push(realMasterState);\n }\n })\n );\n\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: nonConflictRows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n const sendDoc = flatClone(row.newDocumentState);\n if (remoteRevById.has(docId)) {\n (sendDoc as any)._rev = getFromMapOrThrow(remoteRevById, docId);\n }\n return couchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: CouchBulkDocResultRow[] = await response.json();\n\n // get conflicting writes\n const conflictAgainIds: string[] = [];\n responseJson.forEach(writeResultRow => {\n const isConflict = writeResultRow.error === 'conflict';\n if (!writeResultRow.ok && !isConflict) {\n throw newRxError('SNH', { args: { writeResultRow } });\n }\n if (isConflict) {\n conflictAgainIds.push(writeResultRow.id);\n }\n });\n\n if (conflictAgainIds.length === 0) {\n return conflicts;\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflictAgainIds)\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: CouchAllDocsResponse = await conflictResponse.json();\n conflictResponseJson.rows.forEach(conflictAgainRow => {\n conflicts.push(couchDBDocToRxDocData(collection.schema.primaryPath, conflictAgainRow.doc));\n });\n\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier,\n initialCheckpoint: options.push.initialCheckpoint\n };\n }\n\n const replicationState = new RxCouchDBReplicationState(\n options.url,\n options.fetch ? options.fetch : getDefaultFetch(),\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n let lastRequestStartTime = now();\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: CouchdbChangesResult;\n try {\n lastRequestStartTime = now();\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err: any) {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n args: { url },\n error: errorToPlainJson(err)\n })\n );\n\n if (lastRequestStartTime < (now() - replicationState.retryTime)) {\n /**\n * Last request start was long ago,\n * so we directly retry.\n * This mostly happens on timeouts\n * which are normal behavior for long polling requests.\n */\n await promiseWait(0);\n } else {\n // await next tick here otherwise we could go in to a 100% CPU blocking cycle.\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAGA,IAAAA,MAAA,GAAAC,OAAA;AASA,IAAAC,OAAA,GAAAD,OAAA;AAYA,IAAAE,OAAA,GAAAF,OAAA;AAIA,IAAAG,OAAA,GAAAH,OAAA;AAMA,IAAAI,KAAA,GAAAJ,OAAA;AAMA,IAAAK,cAAA,GAAAL,OAAA;AAQAM,MAAA,CAAAC,IAAA,CAAAF,cAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,cAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,cAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAFA,IAAAS,kBAAA,GAAAlB,OAAA;AAGA,IAAAmB,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AK,GAAGO,YAAY,CAACU,QAAQ;UAE7B3B,WAAW,CAACoF,IAAI,CAAC;YACbhE,SAAS;YACTM,UAAU,EAAE;cACRf,QAAQ,EAAEM,YAAY,CAACU;YAC3B;UACJ,CAAC,CAAC;QACN;MACJ,CAAC,EAAE,CAAC;MACJ,OAAOiD,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAY,oCAA4B,EAACpG,OAAO,CAACW,iBAAiB,EAAEiB,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-firestore/index.js b/dist/cjs/plugins/replication-firestore/index.js index 3aa22cc6fb2..9c6f2628663 100644 --- a/dist/cjs/plugins/replication-firestore/index.js +++ b/dist/cjs/plugins/replication-firestore/index.js @@ -42,7 +42,6 @@ Object.keys(_firestoreTypes).forEach(function (key) { }); }); var RxFirestoreReplicationState = exports.RxFirestoreReplicationState = /*#__PURE__*/function (_RxReplicationState) { - (0, _inheritsLoose2.default)(RxFirestoreReplicationState, _RxReplicationState); function RxFirestoreReplicationState(firestore, replicationIdentifierHash, collection, pull, push, live = true, retryTime = 1000 * 5, autoStart = true) { var _this; _this = _RxReplicationState.call(this, replicationIdentifierHash, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; @@ -56,6 +55,7 @@ var RxFirestoreReplicationState = exports.RxFirestoreReplicationState = /*#__PUR _this.autoStart = autoStart; return _this; } + (0, _inheritsLoose2.default)(RxFirestoreReplicationState, _RxReplicationState); return RxFirestoreReplicationState; }(_index3.RxReplicationState); function replicateFirestore(options) { diff --git a/dist/cjs/plugins/replication-firestore/index.js.map b/dist/cjs/plugins/replication-firestore/index.js.map index d1f690589b8..7f936d7a055 100644 --- a/dist/cjs/plugins/replication-firestore/index.js.map +++ b/dist/cjs/plugins/replication-firestore/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_index","require","_firestore","_index2","_index3","_index4","_rxjs","_firestoreHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_firestoreTypes","RxFirestoreReplicationState","_RxReplicationState","_inheritsLoose2","default","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","_this","RxReplicationState","replicateFirestore","options","addRxPlugin","RxDBLeaderElectionPlugin","pullStream$","Subject","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","getSchemaByObjectPath","jsonSchema","includes","newRxError","field","pullFilters","filter","undefined","toArray","pullQuery","query","handler","lastPulledCheckpoint","batchSize","newerQuery","sameTimeQuery","lastServerTimestamp","isoStringToServerTimestamp","serverTimestamp","where","orderBy","limit","id","mustsReRun","useDocs","waitForPendingWrites","database","runTransaction","_tx","newerQueryResult","sameTimeQueryResult","Promise","all","getDocs","metadata","hasPendingWrites","ensureNotFalsy","docs","missingAmount","length","additionalDocs","slice","x","appendToArray","checkpoint","documents","lastDoc","lastOfArray","map","row","firestoreRowToDocData","newCheckpoint","serverTimestampToIsoString","data","ret","modifier","stream$","asObservable","replicationPrimitivesPush","pushFilter","rows","asyncFilter","newDocumentState","writeRowsById","docIds","docId","conflicts","getQuery","ids","documentId","docsInDbResult","getContentByIds","docsInDbById","docDataInDb","stripServerTimestampField","batch","writeBatch","hasWrite","entries","writeRow","docInDb","assumedMasterState","conflictHandler","realMasterState","isEqual","docRef","doc","writeDocData","flatClone","set","stripPrimaryKey","update","commit","replicationState","replicationIdentifier","startBefore","start","bind","cancelBefore","cancel","lastChangeQuery","unsubscribe","onSnapshot","_querySnapshot","reSync","error","subjects","next","errorToPlainJson","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["import {\n appendToArray,\n asyncFilter,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n lastOfArray,\n toArray\n} from '../../plugins/utils/index.ts';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types.ts';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n getContentByIds,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper.ts';\n\nexport * from './firestore-helper.ts';\nexport * from './firestore-types.ts';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateFirestore(\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(collection.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: collection.schema.jsonSchema\n });\n }\n\n const pullFilters = options.pull?.filter !== undefined\n ? toArray(options.pull.filter)\n : [];\n\n const pullQuery = query(options.firestore.collection, ...pullFilters);\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType | undefined,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(pullQuery,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(pullQuery,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(pullQuery,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additionalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n appendToArray(useDocs, additionalDocs);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint ?? null,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n const pushFilter = options.push?.filter;\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n if (pushFilter !== undefined) {\n rows = await asyncFilter(rows, (row) => pushFilter(row.newDocumentState));\n }\n\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n\n const getQuery = (ids: string[]) => {\n return getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', ids)\n )\n );\n };\n\n const docsInDbResult = await getContentByIds(docIds, getQuery);\n\n const docsInDbById: ById = {};\n docsInDbResult.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n pullQuery,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error: errorToPlainJson(error) })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,UAAA,GAAAD,OAAA;AAgBA,IAAAE,OAAA,GAAAF,OAAA;AAQA,IAAAG,OAAA,GAAAH,OAAA;AAIA,IAAAI,OAAA,GAAAJ,OAAA;AAaA,IAAAK,KAAA,GAAAL,OAAA;AACA,IAAAM,gBAAA,GAAAN,OAAA;AASAO,MAAA,CAAAC,IAAA,CAAAF,gBAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,gBAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,gBAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,eAAA,GAAAnB,OAAA;AAAAO,MAAA,CAAAC,IAAA,CAAAW,eAAA,EAAAV,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA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AyB,EACzBrE,OAAO,CAACN,IAAI,EACZM,OAAO,CAACL,SAAS,EACjBK,OAAO,CAACJ,SACZ,CAAC;;EAED;AACJ;AACA;EACI,IAAII,OAAO,CAACN,IAAI,IAAIM,OAAO,CAACR,IAAI,EAAE;IAC9B,IAAMkH,WAAW,GAAGF,gBAAgB,CAACG,KAAK,CAACC,IAAI,CAACJ,gBAAgB,CAAC;IACjE,IAAMK,YAAY,GAAGL,gBAAgB,CAACM,MAAM,CAACF,IAAI,CAACJ,gBAAgB,CAAC;IACnEA,gBAAgB,CAACG,KAAK,GAAG,MAAM;MAC3B,IAAMI,eAAe,GAAG,IAAA1F,gBAAK,EACzBD,SAAS,EACT,IAAAW,kBAAO,EAACxB,oBAAoB,EAAE,MAAM,CAAC,EACrC,IAAAyB,gBAAK,EAAC,CAAC,CACX,CAAC;MACD,IAAMgF,WAAW,GAAG,IAAAC,qBAAU,EAC1BF,eAAe,EACdG,cAAc,IAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBV,gBAAgB,CAACW,MAAM,CAAC,CAAC;MAC7B,CAAC,EACAC,KAAK,IAAK;QACPZ,gBAAgB,CAACa,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChC,IAAAxG,kBAAU,EAAC,WAAW,EAAE;UAAEsG,KAAK,EAAE,IAAAG,uBAAgB,EAACH,KAAK;QAAE,CAAC,CAC9D,CAAC;MACL,CACJ,CAAC;MACDZ,gBAAgB,CAACM,MAAM,GAAG,MAAM;QAC5BE,WAAW,CAAC,CAAC;QACb,OAAOH,YAAY,CAAC,CAAC;MACzB,CAAC;MACD,OAAOH,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAc,oCAA4B,EAACxH,OAAO,CAACM,iBAAiB,EAAEkG,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["_index","require","_firestore","_index2","_index3","_index4","_rxjs","_firestoreHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_firestoreTypes","RxFirestoreReplicationState","_RxReplicationState","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","_this","_inheritsLoose2","default","RxReplicationState","replicateFirestore","options","addRxPlugin","RxDBLeaderElectionPlugin","pullStream$","Subject","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","getSchemaByObjectPath","jsonSchema","includes","newRxError","field","pullFilters","filter","undefined","toArray","pullQuery","query","handler","lastPulledCheckpoint","batchSize","newerQuery","sameTimeQuery","lastServerTimestamp","isoStringToServerTimestamp","serverTimestamp","where","orderBy","limit","id","mustsReRun","useDocs","waitForPendingWrites","database","runTransaction","_tx","newerQueryResult","sameTimeQueryResult","Promise","all","getDocs","metadata","hasPendingWrites","ensureNotFalsy","docs","missingAmount","length","additionalDocs","slice","x","appendToArray","checkpoint","documents","lastDoc","lastOfArray","map","row","firestoreRowToDocData","newCheckpoint","serverTimestampToIsoString","data","ret","modifier","stream$","asObservable","replicationPrimitivesPush","pushFilter","rows","asyncFilter","newDocumentState","writeRowsById","docIds","docId","conflicts","getQuery","ids","documentId","docsInDbResult","getContentByIds","docsInDbById","docDataInDb","stripServerTimestampField","batch","writeBatch","hasWrite","entries","writeRow","docInDb","assumedMasterState","conflictHandler","realMasterState","isEqual","docRef","doc","writeDocData","flatClone","set","stripPrimaryKey","update","commit","replicationState","replicationIdentifier","startBefore","start","bind","cancelBefore","cancel","lastChangeQuery","unsubscribe","onSnapshot","_querySnapshot","reSync","error","subjects","next","errorToPlainJson","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["import {\n appendToArray,\n asyncFilter,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n lastOfArray,\n toArray\n} from '../../plugins/utils/index.ts';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types.ts';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n getContentByIds,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper.ts';\n\nexport * from './firestore-helper.ts';\nexport * from './firestore-types.ts';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateFirestore(\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(collection.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: collection.schema.jsonSchema\n });\n }\n\n const pullFilters = options.pull?.filter !== undefined\n ? toArray(options.pull.filter)\n : [];\n\n const pullQuery = query(options.firestore.collection, ...pullFilters);\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType | undefined,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(pullQuery,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(pullQuery,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(pullQuery,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additionalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n appendToArray(useDocs, additionalDocs);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint ?? null,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n const pushFilter = options.push?.filter;\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n if (pushFilter !== undefined) {\n rows = await asyncFilter(rows, (row) => pushFilter(row.newDocumentState));\n }\n\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n\n const getQuery = (ids: string[]) => {\n return getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', ids)\n )\n );\n };\n\n const docsInDbResult = await getContentByIds(docIds, getQuery);\n\n const docsInDbById: ById = {};\n docsInDbResult.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n pullQuery,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error: errorToPlainJson(error) })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,UAAA,GAAAD,OAAA;AAgBA,IAAAE,OAAA,GAAAF,OAAA;AAQA,IAAAG,OAAA,GAAAH,OAAA;AAIA,IAAAI,OAAA,GAAAJ,OAAA;AAaA,IAAAK,KAAA,GAAAL,OAAA;AACA,IAAAM,gBAAA,GAAAN,OAAA;AASAO,MAAA,CAAAC,IAAA,CAAAF,gBAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,gBAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,gBAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,eAAA,GAAAnB,OAAA;AAAAO,MAAA,CAAAC,IAAA,CAAAW,eAAA,EAAAV,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH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ACzBrE,OAAO,CAACR,IAAI,EACZQ,OAAO,CAACP,SAAS,EACjBO,OAAO,CAACN,SACZ,CAAC;;EAED;AACJ;AACA;EACI,IAAIM,OAAO,CAACR,IAAI,IAAIQ,OAAO,CAACV,IAAI,EAAE;IAC9B,IAAMoH,WAAW,GAAGF,gBAAgB,CAACG,KAAK,CAACC,IAAI,CAACJ,gBAAgB,CAAC;IACjE,IAAMK,YAAY,GAAGL,gBAAgB,CAACM,MAAM,CAACF,IAAI,CAACJ,gBAAgB,CAAC;IACnEA,gBAAgB,CAACG,KAAK,GAAG,MAAM;MAC3B,IAAMI,eAAe,GAAG,IAAA1F,gBAAK,EACzBD,SAAS,EACT,IAAAW,kBAAO,EAACxB,oBAAoB,EAAE,MAAM,CAAC,EACrC,IAAAyB,gBAAK,EAAC,CAAC,CACX,CAAC;MACD,IAAMgF,WAAW,GAAG,IAAAC,qBAAU,EAC1BF,eAAe,EACdG,cAAc,IAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBV,gBAAgB,CAACW,MAAM,CAAC,CAAC;MAC7B,CAAC,EACAC,KAAK,IAAK;QACPZ,gBAAgB,CAACa,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChC,IAAAxG,kBAAU,EAAC,WAAW,EAAE;UAAEsG,KAAK,EAAE,IAAAG,uBAAgB,EAACH,KAAK;QAAE,CAAC,CAC9D,CAAC;MACL,CACJ,CAAC;MACDZ,gBAAgB,CAACM,MAAM,GAAG,MAAM;QAC5BE,WAAW,CAAC,CAAC;QACb,OAAOH,YAAY,CAAC,CAAC;MACzB,CAAC;MACD,OAAOH,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAc,oCAA4B,EAACxH,OAAO,CAACM,iBAAiB,EAAEkG,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-graphql/index.js b/dist/cjs/plugins/replication-graphql/index.js index b4ed9b035d2..5b09ec77bff 100644 --- a/dist/cjs/plugins/replication-graphql/index.js +++ b/dist/cjs/plugins/replication-graphql/index.js @@ -69,7 +69,6 @@ Object.keys(_queryBuilderFromRxSchema).forEach(function (key) { * you can use it to sync collections with a remote graphql endpoint. */ var RxGraphQLReplicationState = exports.RxGraphQLReplicationState = /*#__PURE__*/function (_RxReplicationState) { - (0, _inheritsLoose2.default)(RxGraphQLReplicationState, _RxReplicationState); function RxGraphQLReplicationState(url, clientState, replicationIdentifier, collection, deletedField, pull, push, live, retryTime, autoStart, customFetch) { var _this; _this = _RxReplicationState.call(this, replicationIdentifier, collection, deletedField, pull, push, live, retryTime, autoStart) || this; @@ -86,6 +85,7 @@ var RxGraphQLReplicationState = exports.RxGraphQLReplicationState = /*#__PURE__* _this.customFetch = customFetch; return _this; } + (0, _inheritsLoose2.default)(RxGraphQLReplicationState, _RxReplicationState); var _proto = RxGraphQLReplicationState.prototype; _proto.setHeaders = function setHeaders(headers) { this.clientState.headers = (0, _index.flatClone)(headers); diff --git a/dist/cjs/plugins/replication-graphql/index.js.map b/dist/cjs/plugins/replication-graphql/index.js.map index a11cddf19eb..e459d430754 100644 --- a/dist/cjs/plugins/replication-graphql/index.js.map +++ b/dist/cjs/plugins/replication-graphql/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_index","require","_helper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_index2","_index3","_index4","_graphqlWebsocket","_rxjs","_graphqlSchemaFromRxSchema","_queryBuilderFromRxSchema","RxGraphQLReplicationState","_RxReplicationState","_inheritsLoose2","default","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","_proto","setHeaders","headers","flatClone","setCredentials","credentials","graphQLRequest","queryParams","fetch","ensureNotFalsy","http","RxReplicationState","replicateGraphQL","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","mutateableClientState","pullStream$","Subject","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","data","getProperty","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","getGraphQLWebSocket","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped","removeGraphQLWebSocketRef","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n flatClone,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState,\n ById\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: ById): void {\n this.clientState.headers = flatClone(headers);\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper.ts';\nexport * from './graphql-schema-from-rx-schema.ts';\nexport * from './query-builder-from-rx-schema.ts';\nexport * from './graphql-websocket.ts';\n"],"mappings":";;;;;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AAMA,IAAAC,OAAA,GAAAD,OAAA;AAqPAE,MAAA,CAAAC,IAAA,CAAAF,OAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,OAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,OAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAjPA,IAAAS,OAAA,GAAAd,OAAA;AAYA,IAAAe,OAAA,GAAAf,OAAA;AAIA,IAAAgB,OAAA,GAAAhB,OAAA;AAMA,IAAAiB,iBAAA,GAAAjB,OAAA;AA8NAE,MAAA,CAAAC,IAAA,CAAAc,iBAAA,EAAAb,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAY,iBAAA,CAAAZ,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAI,iBAAA,CAAAZ,GAAA;IAAA;EAAA;AAAA;AA1NA,IAAAa,KAAA,GAA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ACuC,gBAAgB,CAC9BF,IAAI,EACJ,QACJ,CAAC;UACL;UACAb,WAAW,CAACsC,IAAI,CAACzB,IAAI,CAAC;QAC1B,CAAC;QACD8B,KAAK,EAAGA,KAAU,IAAK;UACnB3C,WAAW,CAAC2C,KAAK,CAACA,KAAK,CAAC;QAC5B,CAAC;QACDC,QAAQ,EAAEA,CAAA,KAAM;UACZ5C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;QAC1B;MACJ,CAAC,CAAC;IACV;IACA,OAAOf,WAAW,CAAC,CAAC;EACxB,CAAC;EAED,IAAMgB,YAAY,GAAGnC,uBAAuB,CAACoC,MAAM,CAACf,IAAI,CAACrB,uBAAuB,CAAC;EACjFA,uBAAuB,CAACoC,MAAM,GAAG,MAAM;IACnC,IAAI,CAACpC,uBAAuB,CAACqC,SAAS,CAAC,CAAC,EAAE;MACtC/C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;MACtB,IAAIlB,aAAa,EAAE;QACf,IAAAsB,2CAAyB,EAAC,IAAAxD,qBAAc,EAACrB,GAAG,CAACwD,EAAE,CAAC,CAAC;MACrD;IACJ;IACA,OAAOkB,YAAY,CAAC,CAAC;EACzB,CAAC;EAED,IAAAI,oCAA4B,EAACrD,iBAAiB,EAAEc,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["_index","require","_helper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_index2","_index3","_index4","_graphqlWebsocket","_rxjs","_graphqlSchemaFromRxSchema","_queryBuilderFromRxSchema","RxGraphQLReplicationState","_RxReplicationState","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","_inheritsLoose2","default","_proto","setHeaders","headers","flatClone","setCredentials","credentials","graphQLRequest","queryParams","fetch","ensureNotFalsy","http","RxReplicationState","replicateGraphQL","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","mutateableClientState","pullStream$","Subject","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","data","getProperty","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","getGraphQLWebSocket","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped","removeGraphQLWebSocketRef","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n flatClone,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState,\n ById\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: ById): void {\n this.clientState.headers = flatClone(headers);\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper.ts';\nexport * from './graphql-schema-from-rx-schema.ts';\nexport * from './query-builder-from-rx-schema.ts';\nexport * from './graphql-websocket.ts';\n"],"mappings":";;;;;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AAMA,IAAAC,OAAA,GAAAD,OAAA;AAqPAE,MAAA,CAAAC,IAAA,CAAAF,OAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,OAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,OAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAjPA,IAAAS,OAAA,GAAAd,OAAA;AAYA,IAAAe,OAAA,GAAAf,OAAA;AAIA,IAAAgB,OAAA,GAAAhB,OAAA;AAMA,IAAAiB,iBAAA,GAAAjB,OAAA;AA8NAE,MAAA,CAAAC,IAAA,CAAAc,iBAAA,EAAAb,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAY,iBAAA,CAAAZ,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAI,iBAA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E,IAAI,CAACyC,gBAAgB,EAAE;YACvBF,IAAI,GAAG,MAAMvC,IAAI,CAACyC,gBAAgB,CAC9BF,IAAI,EACJ,QACJ,CAAC;UACL;UACAb,WAAW,CAACsC,IAAI,CAACzB,IAAI,CAAC;QAC1B,CAAC;QACD8B,KAAK,EAAGA,KAAU,IAAK;UACnB3C,WAAW,CAAC2C,KAAK,CAACA,KAAK,CAAC;QAC5B,CAAC;QACDC,QAAQ,EAAEA,CAAA,KAAM;UACZ5C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;QAC1B;MACJ,CAAC,CAAC;IACV;IACA,OAAOf,WAAW,CAAC,CAAC;EACxB,CAAC;EAED,IAAMgB,YAAY,GAAGnC,uBAAuB,CAACoC,MAAM,CAACf,IAAI,CAACrB,uBAAuB,CAAC;EACjFA,uBAAuB,CAACoC,MAAM,GAAG,MAAM;IACnC,IAAI,CAACpC,uBAAuB,CAACqC,SAAS,CAAC,CAAC,EAAE;MACtC/C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;MACtB,IAAIlB,aAAa,EAAE;QACf,IAAAsB,2CAAyB,EAAC,IAAAxD,qBAAc,EAACvB,GAAG,CAAC0D,EAAE,CAAC,CAAC;MACrD;IACJ;IACA,OAAOkB,YAAY,CAAC,CAAC;EACzB,CAAC;EAED,IAAAI,oCAA4B,EAACrD,iBAAiB,EAAEc,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-nats/index.js b/dist/cjs/plugins/replication-nats/index.js index f2eb856f4cb..75fc5bd48c6 100644 --- a/dist/cjs/plugins/replication-nats/index.js +++ b/dist/cjs/plugins/replication-nats/index.js @@ -43,7 +43,6 @@ Object.keys(_natsTypes).forEach(function (key) { }); }); var RxNatsReplicationState = exports.RxNatsReplicationState = /*#__PURE__*/function (_RxReplicationState) { - (0, _inheritsLoose2.default)(RxNatsReplicationState, _RxReplicationState); function RxNatsReplicationState(replicationIdentifier, collection, pull, push, live = true, retryTime = 1000 * 5, autoStart = true) { var _this; _this = _RxReplicationState.call(this, replicationIdentifier, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; @@ -56,6 +55,7 @@ var RxNatsReplicationState = exports.RxNatsReplicationState = /*#__PURE__*/funct _this.autoStart = autoStart; return _this; } + (0, _inheritsLoose2.default)(RxNatsReplicationState, _RxReplicationState); return RxNatsReplicationState; }(_index3.RxReplicationState); function replicateNats(options) { diff --git a/dist/cjs/plugins/replication-nats/index.js.map b/dist/cjs/plugins/replication-nats/index.js.map index b3ef84a46e2..6cd3e1b19a6 100644 --- a/dist/cjs/plugins/replication-nats/index.js.map +++ b/dist/cjs/plugins/replication-nats/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_index","require","_index2","_index3","_index4","_rxjs","_nats","_natsHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_replicationHelper","_natsTypes","RxNatsReplicationState","_RxReplicationState","_inheritsLoose2","default","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","RxReplicationState","replicateNats","options","waitForLeadership","primaryPath","schema","addRxPlugin","RxDBLeaderElectionPlugin","jc","JSONCodec","connectionStatePromise","nc","connect","connection","jetstreamClient","jetstream","jsm","jetstreamManager","streams","add","name","streamName","subjects","subjectPrefix","natsStream","pullStream$","Subject","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","cn","newCheckpoint","sequence","consumer","getConsumer","opt_start_seq","deliver_policy","DeliverPolicy","LastPerSubject","replay_policy","ReplayPolicy","Instant","fetchedMessages","fetch","max_messages","signal","close","useMessages","m","json","seq","ack","documents","checkpoint","ensureNotFalsy","modifier","stream$","asObservable","replicationPrimitivesPush","rows","conflicts","Promise","all","map","writeRow","docId","newDocumentState","remoteDocState","getNatsServerDocumentState","err","message","includes","assumedMasterState","conflictHandler","realMasterState","isEqual","pushDone","publish","encode","expect","lastSubjectSequence","undefined","newServerState","replicationState","error","next","newRxError","document","errorToPlainJson","awaitRetry","startBefore","start","bind","cancelBefore","cancel","lastSeq","lastDocState","getMessage","last_by_subj","newMessages","consume","docData","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-nats/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n errorToPlainJson\n} from '../../plugins/utils/index.ts';\n\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n NatsCheckpointType,\n NatsSyncOptions\n} from './nats-types.ts';\nimport { connect, DeliverPolicy, JSONCodec, ReplayPolicy } from 'nats';\nimport { getNatsServerDocumentState } from './nats-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './nats-types.ts';\nexport * from './nats-helper.ts';\n\n\nexport class RxNatsReplicationState extends RxReplicationState {\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\n\n\nexport function replicateNats(\n options: NatsSyncOptions\n): RxNatsReplicationState {\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n const primaryPath = collection.schema.primaryPath;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const jc = JSONCodec();\n\n\n const connectionStatePromise = (async () => {\n const nc = await connect(options.connection);\n const jetstreamClient = nc.jetstream();\n const jsm = await nc.jetstreamManager();\n await jsm.streams.add({\n name: options.streamName, subjects: [\n options.subjectPrefix + '.*'\n ]\n });\n const natsStream = await jetstreamClient.streams.get(options.streamName);\n return {\n nc,\n jetstreamClient,\n jsm,\n natsStream\n };\n })();\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: NatsCheckpointType | undefined,\n batchSize: number\n ) {\n const cn = await connectionStatePromise;\n const newCheckpoint: NatsCheckpointType = {\n sequence: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0\n };\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n deliver_policy: DeliverPolicy.LastPerSubject,\n replay_policy: ReplayPolicy.Instant\n });\n\n const fetchedMessages = await consumer.fetch({\n max_messages: batchSize\n });\n await (fetchedMessages as any).signal;\n await fetchedMessages.close();\n\n const useMessages: WithDeleted[] = [];\n for await (const m of fetchedMessages) {\n useMessages.push(m.json());\n newCheckpoint.sequence = m.seq;\n m.ack();\n }\n return {\n documents: useMessages,\n checkpoint: newCheckpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const cn = await connectionStatePromise;\n const conflicts: WithDeleted[] = [];\n await Promise.all(\n rows.map(async (writeRow) => {\n const docId = (writeRow.newDocumentState as any)[primaryPath];\n\n /**\n * first get the current state of the documents from the server\n * so that we have the sequence number for conflict detection.\n */\n let remoteDocState;\n try {\n remoteDocState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n } catch (err: Error | any) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n if (\n remoteDocState &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: remoteDocState.json(),\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(remoteDocState.json());\n } else {\n // no conflict (yet)\n let pushDone = false;\n while (!pushDone) {\n try {\n await cn.jetstreamClient.publish(\n options.subjectPrefix + '.' + docId,\n jc.encode(writeRow.newDocumentState),\n {\n expect: remoteDocState ? {\n streamName: options.streamName,\n lastSubjectSequence: remoteDocState.seq\n } : undefined\n }\n );\n pushDone = true;\n } catch (err: Error | any) {\n if (err.message.includes('wrong last sequence')) {\n // A write happened while we are doing our write -> handle conflict\n const newServerState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n conflicts.push(ensureNotFalsy(newServerState).json());\n pushDone = true;\n } else {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n document: writeRow.newDocumentState,\n error: errorToPlainJson(err)\n })\n );\n\n // -> retry after wait\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n }\n }\n }\n })\n );\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxNatsReplicationState(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = async () => {\n const cn = await connectionStatePromise;\n\n /**\n * First get the last sequence so that we can\n * laster only fetch 'newer' messages.\n */\n let lastSeq = 0;\n try {\n const lastDocState = await cn.natsStream.getMessage({\n last_by_subj: options.subjectPrefix + '.*'\n });\n lastSeq = lastDocState.seq;\n } catch (err: any | Error) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastSeq\n });\n const newMessages = await consumer.consume();\n (async () => {\n for await (const m of newMessages) {\n const docData: WithDeleted = m.json();\n pullStream$.next({\n documents: [docData],\n checkpoint: {\n sequence: m.seq\n }\n });\n m.ack();\n }\n })();\n replicationState.cancel = () => {\n newMessages.close();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAMA,IAAAC,OAAA,GAAAD,OAAA;AAQA,IAAAE,OAAA,GAAAF,OAAA;AAIA,IAAAG,OAAA,GAAAH,OAAA;AAMA,IAAAI,KAAA,GAAAJ,OAAA;AAKA,IAAAK,KAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AAIAO,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,WAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,WAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAHA,IAAAS,kBAAA,GAAAnB,OAAA;AAEA,IAAAoB,UAAA,GAAApB,OAAA;AAAAO,MAAA,CAAAC,IAAA,CAAAY,UAAA,EAAAX,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YA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A4B,EAACrG,OAAO,CAACC,iBAAiB,EAAEiF,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["_index","require","_index2","_index3","_index4","_rxjs","_nats","_natsHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_replicationHelper","_natsTypes","RxNatsReplicationState","_RxReplicationState","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","_inheritsLoose2","default","RxReplicationState","replicateNats","options","waitForLeadership","primaryPath","schema","addRxPlugin","RxDBLeaderElectionPlugin","jc","JSONCodec","connectionStatePromise","nc","connect","connection","jetstreamClient","jetstream","jsm","jetstreamManager","streams","add","name","streamName","subjects","subjectPrefix","natsStream","pullStream$","Subject","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","cn","newCheckpoint","sequence","consumer","getConsumer","opt_start_seq","deliver_policy","DeliverPolicy","LastPerSubject","replay_policy","ReplayPolicy","Instant","fetchedMessages","fetch","max_messages","signal","close","useMessages","m","json","seq","ack","documents","checkpoint","ensureNotFalsy","modifier","stream$","asObservable","replicationPrimitivesPush","rows","conflicts","Promise","all","map","writeRow","docId","newDocumentState","remoteDocState","getNatsServerDocumentState","err","message","includes","assumedMasterState","conflictHandler","realMasterState","isEqual","pushDone","publish","encode","expect","lastSubjectSequence","undefined","newServerState","replicationState","error","next","newRxError","document","errorToPlainJson","awaitRetry","startBefore","start","bind","cancelBefore","cancel","lastSeq","lastDocState","getMessage","last_by_subj","newMessages","consume","docData","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-nats/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n errorToPlainJson\n} from '../../plugins/utils/index.ts';\n\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n NatsCheckpointType,\n NatsSyncOptions\n} from './nats-types.ts';\nimport { connect, DeliverPolicy, JSONCodec, ReplayPolicy } from 'nats';\nimport { getNatsServerDocumentState } from './nats-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './nats-types.ts';\nexport * from './nats-helper.ts';\n\n\nexport class RxNatsReplicationState extends RxReplicationState {\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\n\n\nexport function replicateNats(\n options: NatsSyncOptions\n): RxNatsReplicationState {\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n const primaryPath = collection.schema.primaryPath;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const jc = JSONCodec();\n\n\n const connectionStatePromise = (async () => {\n const nc = await connect(options.connection);\n const jetstreamClient = nc.jetstream();\n const jsm = await nc.jetstreamManager();\n await jsm.streams.add({\n name: options.streamName, subjects: [\n options.subjectPrefix + '.*'\n ]\n });\n const natsStream = await jetstreamClient.streams.get(options.streamName);\n return {\n nc,\n jetstreamClient,\n jsm,\n natsStream\n };\n })();\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: NatsCheckpointType | undefined,\n batchSize: number\n ) {\n const cn = await connectionStatePromise;\n const newCheckpoint: NatsCheckpointType = {\n sequence: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0\n };\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n deliver_policy: DeliverPolicy.LastPerSubject,\n replay_policy: ReplayPolicy.Instant\n });\n\n const fetchedMessages = await consumer.fetch({\n max_messages: batchSize\n });\n await (fetchedMessages as any).signal;\n await fetchedMessages.close();\n\n const useMessages: WithDeleted[] = [];\n for await (const m of fetchedMessages) {\n useMessages.push(m.json());\n newCheckpoint.sequence = m.seq;\n m.ack();\n }\n return {\n documents: useMessages,\n checkpoint: newCheckpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const cn = await connectionStatePromise;\n const conflicts: WithDeleted[] = [];\n await Promise.all(\n rows.map(async (writeRow) => {\n const docId = (writeRow.newDocumentState as any)[primaryPath];\n\n /**\n * first get the current state of the documents from the server\n * so that we have the sequence number for conflict detection.\n */\n let remoteDocState;\n try {\n remoteDocState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n } catch (err: Error | any) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n if (\n remoteDocState &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: remoteDocState.json(),\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(remoteDocState.json());\n } else {\n // no conflict (yet)\n let pushDone = false;\n while (!pushDone) {\n try {\n await cn.jetstreamClient.publish(\n options.subjectPrefix + '.' + docId,\n jc.encode(writeRow.newDocumentState),\n {\n expect: remoteDocState ? {\n streamName: options.streamName,\n lastSubjectSequence: remoteDocState.seq\n } : undefined\n }\n );\n pushDone = true;\n } catch (err: Error | any) {\n if (err.message.includes('wrong last sequence')) {\n // A write happened while we are doing our write -> handle conflict\n const newServerState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n conflicts.push(ensureNotFalsy(newServerState).json());\n pushDone = true;\n } else {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n document: writeRow.newDocumentState,\n error: errorToPlainJson(err)\n })\n );\n\n // -> retry after wait\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n }\n }\n }\n })\n );\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxNatsReplicationState(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = async () => {\n const cn = await connectionStatePromise;\n\n /**\n * First get the last sequence so that we can\n * laster only fetch 'newer' messages.\n */\n let lastSeq = 0;\n try {\n const lastDocState = await cn.natsStream.getMessage({\n last_by_subj: options.subjectPrefix + '.*'\n });\n lastSeq = lastDocState.seq;\n } catch (err: any | Error) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastSeq\n });\n const newMessages = await consumer.consume();\n (async () => {\n for await (const m of newMessages) {\n const docData: WithDeleted = m.json();\n pullStream$.next({\n documents: [docData],\n checkpoint: {\n sequence: m.seq\n }\n });\n m.ack();\n }\n })();\n replicationState.cancel = () => {\n newMessages.close();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;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yE,OAAO,GAAGC,YAAY,CAAC9C,GAAG;MAC9B,CAAC,CAAC,OAAOmB,GAAgB,EAAE;QACvB,IAAI,CAACA,GAAG,CAACC,OAAO,CAACC,QAAQ,CAAC,kBAAkB,CAAC,EAAE;UAC3C,MAAMF,GAAG;QACb;MACJ;MAEA,IAAMpC,QAAQ,GAAG,MAAMH,EAAE,CAACP,UAAU,CAACW,WAAW,CAAC;QAC7CC,aAAa,EAAE4D;MACnB,CAAC,CAAC;MACF,IAAMI,WAAW,GAAG,MAAMlE,QAAQ,CAACmE,OAAO,CAAC,CAAC;MAC5C,CAAC,YAAY;QACT,WAAW,IAAMpD,CAAC,IAAImD,WAAW,EAAE;UAC/B,IAAME,OAA+B,GAAGrD,CAAC,CAACC,IAAI,CAAC,CAAC;UAChDzB,WAAW,CAAC6D,IAAI,CAAC;YACbjC,SAAS,EAAE,CAACiD,OAAO,CAAC;YACpBhD,UAAU,EAAE;cACRrB,QAAQ,EAAEgB,CAAC,CAACE;YAChB;UACJ,CAAC,CAAC;UACFF,CAAC,CAACG,GAAG,CAAC,CAAC;QACX;MACJ,CAAC,EAAE,CAAC;MACJgC,gBAAgB,CAACW,MAAM,GAAG,MAAM;QAC5BK,WAAW,CAACrD,KAAK,CAAC,CAAC;QACnB,OAAO+C,YAAY,CAAC,CAAC;MACzB,CAAC;MACD,OAAOH,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAY,oCAA4B,EAACrG,OAAO,CAACC,iBAAiB,EAAEiF,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/test-utils/humans-collection.js b/dist/cjs/plugins/test-utils/humans-collection.js index 1042c2e8dc9..3ed9dbe5dbf 100644 --- a/dist/cjs/plugins/test-utils/humans-collection.js +++ b/dist/cjs/plugins/test-utils/humans-collection.js @@ -26,7 +26,7 @@ var _config = require("./config.js"); var _assert = _interopRequireDefault(require("assert")); var _index = require("../../index.js"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } async function create(size = 20, collectionName = 'human', multiInstance = true, eventReduce = true, storage = (0, _config.getConfig)().storage.getStorage()) { var db = await (0, _index.createRxDatabase)({ name: (0, _index.randomCouchString)(10), diff --git a/dist/cjs/plugins/test-utils/humans-collection.js.map b/dist/cjs/plugins/test-utils/humans-collection.js.map index 3aa838a07b4..ab485d59f29 100644 --- a/dist/cjs/plugins/test-utils/humans-collection.js.map +++ b/dist/cjs/plugins/test-utils/humans-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"humans-collection.js","names":["_clone","_interopRequireDefault","require","schemas","_interopRequireWildcard","schemaObjects","_config","_assert","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","create","size","collectionName","multiInstance","eventReduce","storage","getConfig","getStorage","db","createRxDatabase","name","randomCouchString","ignoreDuplicate","localDocuments","collections","addCollections","schema","human","docsData","Array","fill","map","humanData","writeResult","bulkInsert","assert","deepStrictEqual","error","createBySchema","migrationStrategies","createAttachments","schemaJson","clone","attachments","createNoCompression","schemaJSON","keyCompression","createAgeIndex","amount","humana","humanAgeIndex","multipleOnSameDB","human2","docsData2","collection","collection2","createNested","nestedhuman","nestedHuman","nestedHumanData","createDeepNested","deepNestedHuman","deepNestedHumanData","createMultiInstance","password","undefined","hasMultiInstance","Error","createPrimary","primaryHuman","simpleHumanData","createHumanWithTimestamp","databaseName","humans","humanWithTimestamp","humanWithTimestampData","createMigrationCollection","addMigrationStrategies","autoMigrate","attachment","assign","doc","colName","cols","simpleHuman","Promise","all","insert","simpleHumanAge","then","putAttachment","destroy","db2","cols2","simpleHumanV3","createRelated","refHuman","doc1","refHumanData","doc2","bestFriend","createRelatedNested","refHumanNested","refHumanNestedData","foo","createIdAndAgeIndex","humanIdAndAgeIndex","humanWithIdAndAgeIndexDocumentType"],"sources":["../../../../src/plugins/test-utils/humans-collection.ts"],"sourcesContent":["import clone from 'clone';\nimport * as schemas from './schemas.ts';\nimport * as schemaObjects from './schema-objects.ts';\nimport { getConfig } from './config.ts';\nimport assert from 'assert';\n\nimport {\n createRxDatabase,\n RxJsonSchema,\n RxCollection,\n RxDatabase,\n randomCouchString,\n MigrationStrategies,\n RxAttachmentCreator,\n RxStorage\n} from '../../index.ts';\n\nimport { HumanDocumentType } from './schemas.ts';\n\nexport async function create(\n size: number = 20,\n collectionName: string = 'human',\n multiInstance: boolean = true,\n eventReduce: boolean = true,\n storage: RxStorage = getConfig().storage.getStorage()\n\n): Promise> {\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name: randomCouchString(10),\n storage,\n multiInstance,\n eventReduce,\n ignoreDuplicate: true,\n localDocuments: true\n });\n\n const collections = await db.addCollections({\n [collectionName]: {\n schema: schemas.human,\n localDocuments: true\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n const writeResult = await collections[collectionName].bulkInsert(docsData);\n assert.deepStrictEqual(writeResult.error, []);\n }\n return collections[collectionName];\n}\n\nexport async function createBySchema(\n schema: RxJsonSchema,\n name = 'human',\n storage = getConfig().storage.getStorage(),\n migrationStrategies?: MigrationStrategies\n): Promise> {\n const db = await createRxDatabase<{ [prop: string]: RxCollection; }>({\n name: randomCouchString(10),\n storage,\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n\n const collections = await db.addCollections({\n [name]: {\n schema,\n migrationStrategies\n }\n });\n\n return collections[name];\n}\n\nexport async function createAttachments(\n size = 20,\n name = 'human',\n multiInstance = true\n): Promise> {\n if (!name) {\n name = 'human';\n }\n const db = await createRxDatabase<{ [prop: string]: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n multiInstance,\n eventReduce: true,\n ignoreDuplicate: true\n });\n\n const schemaJson = clone(schemas.human);\n schemaJson.attachments = {};\n\n const collections = await db.addCollections({\n [name]: {\n schema: schemaJson\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections[name].bulkInsert(docsData);\n }\n\n return collections[name];\n}\n\nexport async function createNoCompression(\n size = 20,\n name = 'human'\n): Promise> {\n const db = await createRxDatabase<{ [prop: string]: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n const schemaJSON = clone(schemas.human);\n schemaJSON.keyCompression = false;\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n [name]: {\n schema: schemaJSON\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections[name].bulkInsert(docsData);\n }\n\n return collections[name];\n}\n\nexport async function createAgeIndex(\n amount = 20\n): Promise> {\n const db = await createRxDatabase<{ humana: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n humana: {\n schema: schemas.humanAgeIndex\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.humana.bulkInsert(docsData);\n }\n\n return collections.humana;\n}\n\nexport async function multipleOnSameDB(\n size = 10\n): Promise<{\n db: RxDatabase<{\n human: RxCollection;\n human2: RxCollection;\n }>;\n collection: RxCollection;\n collection2: RxCollection;\n}> {\n const db = await createRxDatabase<{\n human: RxCollection;\n human2: RxCollection;\n }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.human\n },\n human2: {\n schema: schemas.human\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.human.bulkInsert(docsData);\n\n const docsData2 = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.human2.bulkInsert(docsData2);\n }\n\n return {\n db,\n collection: collections.human,\n collection2: collections.human2\n };\n}\n\nexport async function createNested(\n amount = 5\n): Promise> {\n const db = await createRxDatabase<{ nestedhuman: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n nestedhuman: {\n schema: schemas.nestedHuman\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.nestedHumanData());\n await collections.nestedhuman.bulkInsert(docsData);\n }\n\n return collections.nestedhuman;\n}\n\nexport async function createDeepNested(\n amount = 5\n): Promise> {\n const db = await createRxDatabase<{ nestedhuman: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n nestedhuman: {\n schema: schemas.deepNestedHuman\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.deepNestedHumanData());\n await collections.nestedhuman.bulkInsert(docsData);\n }\n\n return collections.nestedhuman;\n}\n\nexport async function createMultiInstance(\n name: string,\n amount = 0,\n password = undefined,\n storage: RxStorage = getConfig().storage.getStorage()\n): Promise> {\n if (!getConfig().storage.hasMultiInstance) {\n throw new Error('createMultiInstance() cannot be called on a storage with hasMultiInstance:false');\n }\n\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage,\n password,\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true,\n localDocuments: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.human,\n localDocuments: true\n }\n });\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.human.bulkInsert(docsData);\n }\n\n return collections.human;\n}\n\nexport async function createPrimary(\n amount = 10,\n name = randomCouchString(10)\n): Promise> {\n\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.primaryHuman\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.simpleHumanData());\n await collections.human.bulkInsert(docsData);\n }\n\n return collections.human;\n}\n\nexport async function createHumanWithTimestamp(\n amount = 0,\n databaseName = randomCouchString(10),\n multiInstance = true,\n storage = getConfig().storage.getStorage()\n): Promise> {\n\n const db = await createRxDatabase<{ humans: RxCollection; }>({\n name: databaseName,\n storage,\n multiInstance,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n humans: {\n schema: schemas.humanWithTimestamp\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanWithTimestampData());\n await collections.humans.bulkInsert(docsData);\n }\n\n return collections.humans;\n}\n\nexport async function createMigrationCollection(\n amount = 0,\n addMigrationStrategies: MigrationStrategies = {},\n name = randomCouchString(10),\n autoMigrate = false,\n attachment?: RxAttachmentCreator\n): Promise> {\n\n const migrationStrategies: any = Object.assign(\n {\n 1: (doc: any) => doc,\n 2: (doc: any) => doc,\n 3: (doc: any) => doc\n },\n addMigrationStrategies\n );\n\n\n const colName = 'human';\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n const cols = await db.addCollections({\n [colName]: {\n schema: attachment !== undefined ? { ...schemas.simpleHuman, attachments: {} } : schemas.simpleHuman,\n autoMigrate: false\n }\n });\n\n await Promise.all(\n new Array(amount)\n .fill(0)\n .map(() => cols[colName].insert(schemaObjects.simpleHumanAge()).then(doc => {\n if (attachment !== undefined) {\n return doc.putAttachment(attachment);\n }\n }))\n );\n await db.destroy();\n\n const db2 = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n const cols2 = await db2.addCollections({\n [colName]: {\n schema: attachment !== undefined ? { ...schemas.simpleHumanV3, attachments: {} } : schemas.simpleHumanV3,\n autoMigrate,\n migrationStrategies\n }\n });\n\n return cols2[colName];\n}\n\nexport async function createRelated(\n name = randomCouchString(10)\n): Promise> {\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.refHuman\n }\n });\n\n const doc1 = schemaObjects.refHumanData();\n const doc2 = schemaObjects.refHumanData(doc1.name);\n doc1.bestFriend = doc2.name; // cross-relation\n\n await collections.human.insert(doc1);\n await collections.human.insert(doc2);\n\n return collections.human;\n}\n\nexport async function createRelatedNested(\n name = randomCouchString(10)\n): Promise> {\n\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.refHumanNested\n }\n });\n\n const doc1 = schemaObjects.refHumanNestedData();\n const doc2 = schemaObjects.refHumanNestedData(doc1.name);\n doc1.foo.bestFriend = doc2.name; // cross-relation\n\n await collections.human.insert(doc1);\n await collections.human.insert(doc2);\n\n return collections.human;\n}\n\nexport async function createIdAndAgeIndex(\n amount = 20\n): Promise> {\n const db = await createRxDatabase<{ humana: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n humana: {\n schema: schemas.humanIdAndAgeIndex\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanWithIdAndAgeIndexDocumentType());\n await collections.humana.bulkInsert(docsData);\n }\n\n return collections.humana;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAC,uBAAA,CAAAF,OAAA;AACA,IAAAG,aAAA,GAAAD,uBAAA,CAAAF,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK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CAAC,CAAC,CACPC,GAAG,CAAC,MAAM9C,aAAa,CAAC0H,kCAAkC,CAAC,CAAC,CAAC;IAClE,MAAMnF,WAAW,CAACyB,MAAM,CAACf,UAAU,CAACN,QAAQ,CAAC;EACjD;EAEA,OAAOJ,WAAW,CAACyB,MAAM;AAC7B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"humans-collection.js","names":["_clone","_interopRequireDefault","require","schemas","_interopRequireWildcard","schemaObjects","_config","_assert","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","create","size","collectionName","multiInstance","eventReduce","storage","getConfig","getStorage","db","createRxDatabase","name","randomCouchString","ignoreDuplicate","localDocuments","collections","addCollections","schema","human","docsData","Array","fill","map","humanData","writeResult","bulkInsert","assert","deepStrictEqual","error","createBySchema","migrationStrategies","createAttachments","schemaJson","clone","attachments","createNoCompression","schemaJSON","keyCompression","createAgeIndex","amount","humana","humanAgeIndex","multipleOnSameDB","human2","docsData2","collection","collection2","createNested","nestedhuman","nestedHuman","nestedHumanData","createDeepNested","deepNestedHuman","deepNestedHumanData","createMultiInstance","password","undefined","hasMultiInstance","Error","createPrimary","primaryHuman","simpleHumanData","createHumanWithTimestamp","databaseName","humans","humanWithTimestamp","humanWithTimestampData","createMigrationCollection","addMigrationStrategies","autoMigrate","attachment","assign","doc","colName","cols","simpleHuman","Promise","all","insert","simpleHumanAge","then","putAttachment","destroy","db2","cols2","simpleHumanV3","createRelated","refHuman","doc1","refHumanData","doc2","bestFriend","createRelatedNested","refHumanNested","refHumanNestedData","foo","createIdAndAgeIndex","humanIdAndAgeIndex","humanWithIdAndAgeIndexDocumentType"],"sources":["../../../../src/plugins/test-utils/humans-collection.ts"],"sourcesContent":["import clone from 'clone';\nimport * as schemas from './schemas.ts';\nimport * as schemaObjects from './schema-objects.ts';\nimport { getConfig } from './config.ts';\nimport assert from 'assert';\n\nimport {\n createRxDatabase,\n RxJsonSchema,\n RxCollection,\n RxDatabase,\n randomCouchString,\n MigrationStrategies,\n RxAttachmentCreator,\n RxStorage\n} from '../../index.ts';\n\nimport { HumanDocumentType } from './schemas.ts';\n\nexport async function create(\n size: number = 20,\n collectionName: string = 'human',\n multiInstance: boolean = true,\n eventReduce: boolean = true,\n storage: RxStorage = getConfig().storage.getStorage()\n\n): Promise> {\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name: randomCouchString(10),\n storage,\n multiInstance,\n eventReduce,\n ignoreDuplicate: true,\n localDocuments: true\n });\n\n const collections = await db.addCollections({\n [collectionName]: {\n schema: schemas.human,\n localDocuments: true\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n const writeResult = await collections[collectionName].bulkInsert(docsData);\n assert.deepStrictEqual(writeResult.error, []);\n }\n return collections[collectionName];\n}\n\nexport async function createBySchema(\n schema: RxJsonSchema,\n name = 'human',\n storage = getConfig().storage.getStorage(),\n migrationStrategies?: MigrationStrategies\n): Promise> {\n const db = await createRxDatabase<{ [prop: string]: RxCollection; }>({\n name: randomCouchString(10),\n storage,\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n\n const collections = await db.addCollections({\n [name]: {\n schema,\n migrationStrategies\n }\n });\n\n return collections[name];\n}\n\nexport async function createAttachments(\n size = 20,\n name = 'human',\n multiInstance = true\n): Promise> {\n if (!name) {\n name = 'human';\n }\n const db = await createRxDatabase<{ [prop: string]: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n multiInstance,\n eventReduce: true,\n ignoreDuplicate: true\n });\n\n const schemaJson = clone(schemas.human);\n schemaJson.attachments = {};\n\n const collections = await db.addCollections({\n [name]: {\n schema: schemaJson\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections[name].bulkInsert(docsData);\n }\n\n return collections[name];\n}\n\nexport async function createNoCompression(\n size = 20,\n name = 'human'\n): Promise> {\n const db = await createRxDatabase<{ [prop: string]: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n const schemaJSON = clone(schemas.human);\n schemaJSON.keyCompression = false;\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n [name]: {\n schema: schemaJSON\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections[name].bulkInsert(docsData);\n }\n\n return collections[name];\n}\n\nexport async function createAgeIndex(\n amount = 20\n): Promise> {\n const db = await createRxDatabase<{ humana: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n humana: {\n schema: schemas.humanAgeIndex\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.humana.bulkInsert(docsData);\n }\n\n return collections.humana;\n}\n\nexport async function multipleOnSameDB(\n size = 10\n): Promise<{\n db: RxDatabase<{\n human: RxCollection;\n human2: RxCollection;\n }>;\n collection: RxCollection;\n collection2: RxCollection;\n}> {\n const db = await createRxDatabase<{\n human: RxCollection;\n human2: RxCollection;\n }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.human\n },\n human2: {\n schema: schemas.human\n }\n });\n\n // insert data\n if (size > 0) {\n const docsData = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.human.bulkInsert(docsData);\n\n const docsData2 = new Array(size)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.human2.bulkInsert(docsData2);\n }\n\n return {\n db,\n collection: collections.human,\n collection2: collections.human2\n };\n}\n\nexport async function createNested(\n amount = 5\n): Promise> {\n const db = await createRxDatabase<{ nestedhuman: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n nestedhuman: {\n schema: schemas.nestedHuman\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.nestedHumanData());\n await collections.nestedhuman.bulkInsert(docsData);\n }\n\n return collections.nestedhuman;\n}\n\nexport async function createDeepNested(\n amount = 5\n): Promise> {\n const db = await createRxDatabase<{ nestedhuman: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n nestedhuman: {\n schema: schemas.deepNestedHuman\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.deepNestedHumanData());\n await collections.nestedhuman.bulkInsert(docsData);\n }\n\n return collections.nestedhuman;\n}\n\nexport async function createMultiInstance(\n name: string,\n amount = 0,\n password = undefined,\n storage: RxStorage = getConfig().storage.getStorage()\n): Promise> {\n if (!getConfig().storage.hasMultiInstance) {\n throw new Error('createMultiInstance() cannot be called on a storage with hasMultiInstance:false');\n }\n\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage,\n password,\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true,\n localDocuments: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.human,\n localDocuments: true\n }\n });\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanData());\n await collections.human.bulkInsert(docsData);\n }\n\n return collections.human;\n}\n\nexport async function createPrimary(\n amount = 10,\n name = randomCouchString(10)\n): Promise> {\n\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.primaryHuman\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.simpleHumanData());\n await collections.human.bulkInsert(docsData);\n }\n\n return collections.human;\n}\n\nexport async function createHumanWithTimestamp(\n amount = 0,\n databaseName = randomCouchString(10),\n multiInstance = true,\n storage = getConfig().storage.getStorage()\n): Promise> {\n\n const db = await createRxDatabase<{ humans: RxCollection; }>({\n name: databaseName,\n storage,\n multiInstance,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n humans: {\n schema: schemas.humanWithTimestamp\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanWithTimestampData());\n await collections.humans.bulkInsert(docsData);\n }\n\n return collections.humans;\n}\n\nexport async function createMigrationCollection(\n amount = 0,\n addMigrationStrategies: MigrationStrategies = {},\n name = randomCouchString(10),\n autoMigrate = false,\n attachment?: RxAttachmentCreator\n): Promise> {\n\n const migrationStrategies: any = Object.assign(\n {\n 1: (doc: any) => doc,\n 2: (doc: any) => doc,\n 3: (doc: any) => doc\n },\n addMigrationStrategies\n );\n\n\n const colName = 'human';\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n const cols = await db.addCollections({\n [colName]: {\n schema: attachment !== undefined ? { ...schemas.simpleHuman, attachments: {} } : schemas.simpleHuman,\n autoMigrate: false\n }\n });\n\n await Promise.all(\n new Array(amount)\n .fill(0)\n .map(() => cols[colName].insert(schemaObjects.simpleHumanAge()).then(doc => {\n if (attachment !== undefined) {\n return doc.putAttachment(attachment);\n }\n }))\n );\n await db.destroy();\n\n const db2 = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n const cols2 = await db2.addCollections({\n [colName]: {\n schema: attachment !== undefined ? { ...schemas.simpleHumanV3, attachments: {} } : schemas.simpleHumanV3,\n autoMigrate,\n migrationStrategies\n }\n });\n\n return cols2[colName];\n}\n\nexport async function createRelated(\n name = randomCouchString(10)\n): Promise> {\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.refHuman\n }\n });\n\n const doc1 = schemaObjects.refHumanData();\n const doc2 = schemaObjects.refHumanData(doc1.name);\n doc1.bestFriend = doc2.name; // cross-relation\n\n await collections.human.insert(doc1);\n await collections.human.insert(doc2);\n\n return collections.human;\n}\n\nexport async function createRelatedNested(\n name = randomCouchString(10)\n): Promise> {\n\n const db = await createRxDatabase<{ human: RxCollection; }>({\n name,\n storage: getConfig().storage.getStorage(),\n multiInstance: true,\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n human: {\n schema: schemas.refHumanNested\n }\n });\n\n const doc1 = schemaObjects.refHumanNestedData();\n const doc2 = schemaObjects.refHumanNestedData(doc1.name);\n doc1.foo.bestFriend = doc2.name; // cross-relation\n\n await collections.human.insert(doc1);\n await collections.human.insert(doc2);\n\n return collections.human;\n}\n\nexport async function createIdAndAgeIndex(\n amount = 20\n): Promise> {\n const db = await createRxDatabase<{ humana: RxCollection; }>({\n name: randomCouchString(10),\n storage: getConfig().storage.getStorage(),\n eventReduce: true,\n ignoreDuplicate: true\n });\n // setTimeout(() => db.destroy(), dbLifetime);\n const collections = await db.addCollections({\n humana: {\n schema: schemas.humanIdAndAgeIndex\n }\n });\n\n // insert data\n if (amount > 0) {\n const docsData = new Array(amount)\n .fill(0)\n .map(() => schemaObjects.humanWithIdAndAgeIndexDocumentType());\n await collections.humana.bulkInsert(docsData);\n }\n\n return collections.humana;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAC,uBAAA,CAAAF,OAAA;AACA,IAAAG,aAAA,GAAAD,uBAAA,CAAAF,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,OAAA,GAAAN,sBAAA,CAAAC,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AASwB,SAAAO,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAN,wBAAAM,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,OAAAC,cAAA,CAAAC,IAAA,CAAAhB,CAAA,EAAAc,CAAA,SAAAG,CAAA,GAAAP,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAG,CAAA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O,CAACE,UAAU,CAAC,CAAC;IACzCH,WAAW,EAAE,IAAI;IACjBQ,eAAe,EAAE;EACrB,CAAC,CAAC;EACF;EACA,IAAME,WAAW,GAAG,MAAMN,EAAE,CAACO,cAAc,CAAC;IACxCwB,MAAM,EAAE;MACJvB,MAAM,EAAE1C,OAAO,CAAC0H;IACpB;EACJ,CAAC,CAAC;;EAEF;EACA,IAAI1D,MAAM,GAAG,CAAC,EAAE;IACZ,IAAMpB,QAAQ,GAAG,IAAIC,KAAK,CAACmB,MAAM,CAAC,CAC7BlB,IAAI,CAAC,CAAC,CAAC,CACPC,GAAG,CAAC,MAAM7C,aAAa,CAACyH,kCAAkC,CAAC,CAAC,CAAC;IAClE,MAAMnF,WAAW,CAACyB,MAAM,CAACf,UAAU,CAACN,QAAQ,CAAC;EACjD;EAEA,OAAOJ,WAAW,CAACyB,MAAM;AAC7B","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/test-utils/index.js b/dist/cjs/plugins/test-utils/index.js index d98696ab152..51562c77932 100644 --- a/dist/cjs/plugins/test-utils/index.js +++ b/dist/cjs/plugins/test-utils/index.js @@ -94,7 +94,7 @@ Object.keys(schemasConst).forEach(function (key) { }); }); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * This plugins contains thing that are needed for testing * in RxDB related context. Mostly used in the unit tests and diff --git a/dist/cjs/plugins/test-utils/index.js.map b/dist/cjs/plugins/test-utils/index.js.map index 33861712f32..13f7c96f173 100644 --- a/dist/cjs/plugins/test-utils/index.js.map +++ b/dist/cjs/plugins/test-utils/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_config","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","humansCollectionConst","_interopRequireWildcard","_portManager","_revisions","_testUtil","schemaObjectsConst","schemasConst","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","n","__proto__","a","getOwnPropertyDescriptor","u","i","set","humansCollection","schemas","schemaObjects"],"sources":["../../../../src/plugins/test-utils/index.ts"],"sourcesContent":["/**\n * This plugins contains thing that are needed for testing\n * in RxDB related context. Mostly used in the unit tests and\n * also in the tests for the premium and the server repository.\n */\n\nexport * from './config.ts';\nexport * from './humans-collection.ts';\nexport * from './port-manager.ts';\nexport * from './revisions.ts';\nexport * from './test-util.ts';\n\nexport * from './schema-objects.ts';\nexport * from './schemas.ts';\n\nimport * as humansCollectionConst from './humans-collection.ts';\nexport const humansCollection = humansCollectionConst;\n\nimport * as schemasConst from './schemas.ts';\nexport const schemas = schemasConst;\nimport * as schemaObjectsConst from './schema-objects.ts';\nexport const schemaObjects = schemaObjectsConst;\n"],"mappings":";;;;;;;;;;;AAMA,IAAAA,OAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,OAAA,EAAAI,OAA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wBAAA,WAAAC,CAAA,IAAAX,CAAA,oBAAAW,CAAA,IAAA/B,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAc,CAAA,EAAAW,CAAA,SAAAC,CAAA,GAAAH,CAAA,GAAA7B,MAAA,CAAA8B,wBAAA,CAAAV,CAAA,EAAAW,CAAA,UAAAC,CAAA,KAAAA,CAAA,CAAArB,GAAA,IAAAqB,CAAA,CAAAC,GAAA,IAAAjC,MAAA,CAAAS,cAAA,CAAAkB,CAAA,EAAAI,CAAA,EAAAC,CAAA,IAAAL,CAAA,CAAAI,CAAA,IAAAX,CAAA,CAAAW,CAAA,YAAAJ,CAAA,CAAAF,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAU,GAAA,CAAAb,CAAA,EAAAO,CAAA,GAAAA,CAAA;AAb7B;AACA;AACA;AACA;AACA;;AAYO,IAAMO,gBAAgB,GAAA1B,OAAA,CAAA0B,gBAAA,GAAGtB,qBAAqB;AAG9C,IAAMuB,OAAO,GAAA3B,OAAA,CAAA2B,OAAA,GAAGjB,YAAY;AAE5B,IAAMkB,aAAa,GAAA5B,OAAA,CAAA4B,aAAA,GAAGnB,kBAAkB","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["_config","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","humansCollectionConst","_interopRequireWildcard","_portManager","_revisions","_testUtil","schemaObjectsConst","schemasConst","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","n","__proto__","a","getOwnPropertyDescriptor","u","i","set","humansCollection","schemas","schemaObjects"],"sources":["../../../../src/plugins/test-utils/index.ts"],"sourcesContent":["/**\n * This plugins contains thing that are needed for testing\n * in RxDB related context. Mostly used in the unit tests and\n * also in the tests for the premium and the server repository.\n */\n\nexport * from './config.ts';\nexport * from './humans-collection.ts';\nexport * from './port-manager.ts';\nexport * from './revisions.ts';\nexport * from './test-util.ts';\n\nexport * from './schema-objects.ts';\nexport * from './schemas.ts';\n\nimport * as humansCollectionConst from './humans-collection.ts';\nexport const humansCollection = humansCollectionConst;\n\nimport * as schemasConst from './schemas.ts';\nexport const schemas = schemasConst;\nimport * as schemaObjectsConst from './schema-objects.ts';\nexport const schemaObjects = schemaObjectsConst;\n"],"mappings":";;;;;;;;;;;AAMA,IAAAA,OAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,OAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAL,OAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAb,OAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,qBAAA,GAAAC,uBAAA,CAAAd,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAW,qBAAA,EAAAV,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAS,qBAAA,CAAAT,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,qBAAA,CAAAT,GAAA;IAAA;EAAA;AAAA;AACA,IAAAW,YAAA,GAAAf,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAa,YAAA,EAAAZ,OAAA,WAAAC,GAAA;EAAA,I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A,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAZ,GAAA,CAAAS,CAAA,OAAAO,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAA7B,MAAA,CAAAS,cAAA,IAAAT,MAAA,CAAA8B,wBAAA,WAAAC,CAAA,IAAAX,CAAA,oBAAAW,CAAA,OAAA1B,cAAA,CAAAC,IAAA,CAAAc,CAAA,EAAAW,CAAA,SAAAC,CAAA,GAAAH,CAAA,GAAA7B,MAAA,CAAA8B,wBAAA,CAAAV,CAAA,EAAAW,CAAA,UAAAC,CAAA,KAAAA,CAAA,CAAArB,GAAA,IAAAqB,CAAA,CAAAC,GAAA,IAAAjC,MAAA,CAAAS,cAAA,CAAAkB,CAAA,EAAAI,CAAA,EAAAC,CAAA,IAAAL,CAAA,CAAAI,CAAA,IAAAX,CAAA,CAAAW,CAAA,YAAAJ,CAAA,CAAAF,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAU,GAAA,CAAAb,CAAA,EAAAO,CAAA,GAAAA,CAAA;AAb7B;AACA;AACA;AACA;AACA;;AAYO,IAAMO,gBAAgB,GAAA1B,OAAA,CAAA0B,gBAAA,GAAGtB,qBAAqB;AAG9C,IAAMuB,OAAO,GAAA3B,OAAA,CAAA2B,OAAA,GAAGjB,YAAY;AAE5B,IAAMkB,aAAa,GAAA5B,OAAA,CAAA4B,aAAA,GAAGnB,kBAAkB","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/test-utils/port-manager.js b/dist/cjs/plugins/test-utils/port-manager.js index 7613f5ac1ed..eaa1fe73d08 100644 --- a/dist/cjs/plugins/test-utils/port-manager.js +++ b/dist/cjs/plugins/test-utils/port-manager.js @@ -7,7 +7,7 @@ exports.nextPort = nextPort; var _getPort = _interopRequireWildcard(require("get-port")); var _index = require("../utils/index.js"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * For easier debugging, we increase the port each time * to ensure that no port is reused in the tests. diff --git a/dist/cjs/plugins/test-utils/port-manager.js.map b/dist/cjs/plugins/test-utils/port-manager.js.map index 735b7692b3e..4372f68d762 100644 --- a/dist/cjs/plugins/test-utils/port-manager.js.map +++ b/dist/cjs/plugins/test-utils/port-manager.js.map @@ -1 +1 @@ -{"version":3,"file":"port-manager.js","names":["_getPort","_interopRequireWildcard","require","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","startPort","PORT_MAX","portQueue","PROMISE_RESOLVE_VOID","nextPort","then","port","getPort","makeRange","host"],"sources":["../../../../src/plugins/test-utils/port-manager.ts"],"sourcesContent":["import getPort, { makeRange } from 'get-port';\nimport { PROMISE_RESOLVE_VOID } from '../utils/index.ts';\n\n/**\n * For easier debugging, we increase the port each time\n * to ensure that no port is reused in the tests.\n */\nlet startPort = 18669;\n\nconst PORT_MAX = 65535;\nlet portQueue: Promise = PROMISE_RESOLVE_VOID as any;\n\n/**\n * Returns an unused port.\n * Used to ensure that different tests\n * do not accidentally use the same port.\n */\nexport function nextPort(): Promise {\n portQueue = portQueue.then(async () => {\n const port = await getPort({\n port: makeRange(startPort, PORT_MAX),\n host: '0.0.0.0',\n });\n startPort = port + 1;\n return port;\n });\n return portQueue;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,QAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAAyD,SAAAE,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAJ,wBAAAI,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAjB,CAAA,EAAAc,CAAA,SAAAI,CAAA,GAAAR,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAI,CAAA,KAAAA,CAAA,CAAAX,GAAA,IAAAW,CAAA,CAAAC,GAAA,IAAAR,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAI,CAAA,IAAAV,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAgB,GAAA,CAAAnB,CAAA,EAAAQ,CAAA,GAAAA,CAAA;AAEzD;AACA;AACA;AACA;AACA,IAAIY,SAAS,GAAG,KAAK;AAErB,IAAMC,QAAQ,GAAG,KAAK;AACtB,IAAIC,SAA0B,GAAGC,2BAA2B;;AAE5D;AACA;AACA;AACA;AACA;AACO,SAASC,QAAQA,CAAA,EAAoB;EACxCF,SAAS,GAAGA,SAAS,CAACG,IAAI,CAAC,YAAY;IACnC,IAAMC,IAAI,GAAG,MAAM,IAAAC,gBAAO,EAAC;MACvBD,IAAI,EAAE,IAAAE,kBAAS,EAACR,SAAS,EAAEC,QAAQ,CAAC;MACpCQ,IAAI,EAAE;IACV,CAAC,CAAC;IACFT,SAAS,GAAGM,IAAI,GAAG,CAAC;IACpB,OAAOA,IAAI;EACf,CAAC,CAAC;EACF,OAAOJ,SAAS;AACpB","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"port-manager.js","names":["_getPort","_interopRequireWildcard","require","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","startPort","PORT_MAX","portQueue","PROMISE_RESOLVE_VOID","nextPort","then","port","getPort","makeRange","host"],"sources":["../../../../src/plugins/test-utils/port-manager.ts"],"sourcesContent":["import getPort, { makeRange } from 'get-port';\nimport { PROMISE_RESOLVE_VOID } from '../utils/index.ts';\n\n/**\n * For easier debugging, we increase the port each time\n * to ensure that no port is reused in the tests.\n */\nlet startPort = 18669;\n\nconst PORT_MAX = 65535;\nlet portQueue: Promise = PROMISE_RESOLVE_VOID as any;\n\n/**\n * Returns an unused port.\n * Used to ensure that different tests\n * do not accidentally use the same port.\n */\nexport function nextPort(): Promise {\n portQueue = portQueue.then(async () => {\n const port = await getPort({\n port: makeRange(startPort, PORT_MAX),\n host: '0.0.0.0',\n });\n startPort = port + 1;\n return port;\n });\n return portQueue;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,QAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAAyD,SAAAE,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAJ,wBAAAI,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,OAAAC,cAAA,CAAAC,IAAA,CAAAhB,CAAA,EAAAc,CAAA,SAAAG,CAAA,GAAAP,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAG,CAAA,KAAAA,CAAA,CAAAV,GAAA,IAAAU,CAAA,CAAAC,GAAA,IAAAP,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAG,CAAA,IAAAT,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAe,GAAA,CAAAlB,CAAA,EAAAQ,CAAA,GAAAA,CAAA;AAEzD;AACA;AACA;AACA;AACA,IAAIW,SAAS,GAAG,KAAK;AAErB,IAAMC,QAAQ,GAAG,KAAK;AACtB,IAAIC,SAA0B,GAAGC,2BAA2B;;AAE5D;AACA;AACA;AACA;AACA;AACO,SAASC,QAAQA,CAAA,EAAoB;EACxCF,SAAS,GAAGA,SAAS,CAACG,IAAI,CAAC,YAAY;IACnC,IAAMC,IAAI,GAAG,MAAM,IAAAC,gBAAO,EAAC;MACvBD,IAAI,EAAE,IAAAE,kBAAS,EAACR,SAAS,EAAEC,QAAQ,CAAC;MACpCQ,IAAI,EAAE;IACV,CAAC,CAAC;IACFT,SAAS,GAAGM,IAAI,GAAG,CAAC;IACpB,OAAOA,IAAI;EACf,CAAC,CAAC;EACF,OAAOJ,SAAS;AACpB","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/test-utils/schema-objects.js b/dist/cjs/plugins/test-utils/schema-objects.js index 44551747bb4..fef9d0b4699 100644 --- a/dist/cjs/plugins/test-utils/schema-objects.js +++ b/dist/cjs/plugins/test-utils/schema-objects.js @@ -34,7 +34,7 @@ var _asyncTestUtil = require("async-test-util"); var schemas = _interopRequireWildcard(require("./schemas.js")); var _index = require("../utils/index.js"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * this file contains objects which match the schemas in schemas.js */ diff --git a/dist/cjs/plugins/test-utils/schema-objects.js.map b/dist/cjs/plugins/test-utils/schema-objects.js.map index d8e1356b002..a58edd8abb2 100644 --- a/dist/cjs/plugins/test-utils/schema-objects.js.map +++ b/dist/cjs/plugins/test-utils/schema-objects.js.map @@ -1 +1 @@ -{"version":3,"file":"schema-objects.js","names":["_faker","require","_asyncTestUtil","schemas","_interopRequireWildcard","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","TEST_DATA_CHARSET","exports","TEST_DATA_CHARSET_LAST_SORTED","ensureNotFalsy","lastOfArray","split","sort","randomStringWithSpecialChars","length","randomString","humanData","passportId","age","randomNumber","firstName","faker","person","lastName","simpleHumanData","simpleHumanV3Data","partial","defaultObj","assign","simpleHumanAge","humanWithSubOther","other","NoIndexHuman","nestedHumanData","mainSkill","name","level","deepNestedHumanData","attack","good","count","bigHumanDocumentType","dnaHash","heroArrayData","skills","Array","fill","map","damage","simpleHeroArray","encryptedHumanData","secret","encryptedObjectHumanData","subname","encryptedDeepHumanDocumentType","firstLevelPassword","secretData","pw","deepSecret","darkhole","nestedSecret","compoundIndexData","passportCountry","compoundIndexNoStringData","nostringIndex","refHumanData","bestFriend","refHumanNestedData","foo","humanWithTimestampData","givenData","ret","id","updatedAt","Date","now","averageSchemaForFieldLength","averageSchema","averageSchemaData","properties","maxLength","var1","var2","maximum","deep","deep1","deep2","deeper","deepNr","list","pointData","x","number","int","y","humanWithIdAndAgeIndexDocumentType","humanWithCompositePrimary","info"],"sources":["../../../../src/plugins/test-utils/schema-objects.ts"],"sourcesContent":["/**\n * this file contains objects which match the schemas in schemas.js\n */\n\nimport { faker } from '@faker-js/faker';\n\nimport {\n randomNumber,\n randomString\n} from 'async-test-util';\nimport { HumanDocumentType } from './schemas.ts';\nimport * as schemas from './schemas.ts';\nimport { ensureNotFalsy, lastOfArray } from '../utils/index.ts';\n\n/**\n * Some storages had problems with umlauts and other special chars.\n * So we add these to all test strings.\n * TODO add emojis\n */\nexport const TEST_DATA_CHARSET = '0987654321ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzäöüÖÄßÜ[]{}\\'';\nexport const TEST_DATA_CHARSET_LAST_SORTED = ensureNotFalsy(lastOfArray(TEST_DATA_CHARSET.split('').sort()));\n// const someEmojis = '😊💩👵🍌';\nexport function randomStringWithSpecialChars(length: number) {\n return randomString(length, TEST_DATA_CHARSET);\n}\n\n\nexport interface SimpleHumanDocumentType {\n passportId: string;\n firstName: string;\n lastName: string;\n}\n\nexport function humanData(\n passportId: string = randomStringWithSpecialChars(12),\n age: number = randomNumber(10, 50),\n firstName: string = faker.person.firstName()\n): HumanDocumentType {\n return {\n passportId: passportId,\n firstName,\n lastName: faker.person.lastName(),\n age\n };\n}\n\nexport function simpleHumanData(): SimpleHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n lastName: faker.person.lastName()\n };\n}\n\nexport interface SimpleHumanV3DocumentType {\n passportId: string;\n age: number;\n oneOptional?: string;\n}\nexport function simpleHumanV3Data(partial: Partial = {}): SimpleHumanV3DocumentType {\n const defaultObj = {\n passportId: randomStringWithSpecialChars(12),\n age: randomNumber(10, 50)\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface SimpleHumanAgeDocumentType {\n passportId: string;\n age: string;\n}\nexport function simpleHumanAge(partial: Partial = {}): SimpleHumanAgeDocumentType {\n const defaultObj = {\n passportId: randomStringWithSpecialChars(12),\n age: randomNumber(10, 50) + ''\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface HumanWithSubOtherDocumentType {\n passportId: string;\n other: {\n age: number;\n };\n}\nexport function humanWithSubOther(): HumanWithSubOtherDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n other: {\n age: randomNumber(10, 50)\n }\n };\n}\n\nexport interface NoIndexHumanDocumentType {\n firstName: string;\n lastName: string;\n}\nexport function NoIndexHuman(): NoIndexHumanDocumentType {\n return {\n firstName: faker.person.firstName(),\n lastName: faker.person.lastName()\n };\n}\n\nexport interface NestedHumanDocumentType {\n passportId: string;\n firstName: string;\n mainSkill: {\n name: string;\n level: number;\n };\n}\nexport function nestedHumanData(partial: Partial = {}): NestedHumanDocumentType {\n const defaultObj = {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n mainSkill: {\n name: randomStringWithSpecialChars(6),\n level: 5\n }\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface DeepNestedHumanDocumentType {\n passportId: string;\n mainSkill: {\n name: string;\n attack: {\n good: boolean;\n count: number;\n };\n };\n}\nexport function deepNestedHumanData(): DeepNestedHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n mainSkill: {\n name: randomStringWithSpecialChars(6),\n attack: {\n good: false,\n count: 5\n }\n }\n };\n}\n\nexport interface BigHumanDocumentType {\n passportId: string;\n dnaHash: string;\n firstName: string;\n lastName: string;\n age: number;\n}\nexport function bigHumanDocumentType(): BigHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n dnaHash: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n lastName: faker.person.lastName(),\n age: randomNumber(10, 50)\n };\n}\n\nexport interface HeroArrayDocumentType {\n name: string;\n skills: {\n name: string;\n damage: number;\n }[];\n}\nexport function heroArrayData(): HeroArrayDocumentType {\n return {\n name: randomStringWithSpecialChars(6),\n skills: new Array(3).fill(0).map(() => {\n return {\n name: randomStringWithSpecialChars(6),\n damage: randomNumber(10, 50)\n };\n })\n };\n}\n\nexport interface SimpleHeroArrayDocumentType {\n name: string;\n skills: string[];\n}\nexport function simpleHeroArray(partial: Partial = {}): SimpleHeroArrayDocumentType {\n const defaultObj = {\n name: randomStringWithSpecialChars(6),\n skills: new Array(3).fill(0).map(() => randomStringWithSpecialChars(6))\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface EncryptedHumanDocumentType {\n passportId: string;\n firstName: string;\n secret: string;\n}\nexport function encryptedHumanData(secret = randomStringWithSpecialChars(12)): EncryptedHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n secret\n };\n}\n\nexport interface EncryptedObjectHumanDocumentType {\n passportId: string;\n firstName: string;\n secret: {\n name: string;\n subname: string;\n };\n}\nexport function encryptedObjectHumanData(): EncryptedObjectHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n secret: {\n name: randomStringWithSpecialChars(12),\n subname: randomStringWithSpecialChars(12)\n }\n };\n}\n\nexport interface EncryptedDeepHumanDocumentType {\n passportId: string;\n firstName: string;\n firstLevelPassword: string;\n secretData: {\n pw: string;\n };\n deepSecret: {\n darkhole: {\n pw: string;\n };\n };\n nestedSecret: {\n darkhole: {\n pw: string;\n };\n };\n}\nexport function encryptedDeepHumanDocumentType(): EncryptedDeepHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n firstLevelPassword: randomStringWithSpecialChars(12),\n secretData: {\n pw: randomStringWithSpecialChars(12)\n },\n deepSecret: {\n darkhole: {\n pw: randomStringWithSpecialChars(12)\n }\n },\n nestedSecret: {\n darkhole: {\n pw: randomStringWithSpecialChars(12)\n }\n }\n };\n}\n\nexport interface CompoundIndexDocumentType {\n passportId: string;\n passportCountry: string;\n age: number;\n}\nexport function compoundIndexData(): CompoundIndexDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n passportCountry: randomStringWithSpecialChars(12),\n age: randomNumber(10, 50)\n };\n}\n\nexport interface CompoundIndexNoStringDocumentType {\n passportId: string;\n passportCountry: { [prop: string]: string; };\n age: number;\n}\nexport function compoundIndexNoStringData(): CompoundIndexNoStringDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n passportCountry: { [randomStringWithSpecialChars(12)]: randomStringWithSpecialChars(12) },\n age: randomNumber(10, 50)\n };\n}\n\nexport interface NostringIndexDocumentType {\n passportId: {};\n firstName: string;\n}\nexport function nostringIndex(): NostringIndexDocumentType {\n return {\n passportId: {},\n firstName: faker.person.firstName()\n };\n}\n\nexport interface RefHumanDocumentType {\n name: string;\n bestFriend: string;\n}\nexport function refHumanData(bestFriend?: string): RefHumanDocumentType {\n return {\n name: randomStringWithSpecialChars(12),\n bestFriend\n } as any;\n}\n\nexport interface RefHumanNestedDocumentType {\n name: string;\n foo: {\n bestFriend: string;\n };\n}\nexport function refHumanNestedData(bestFriend?: string): RefHumanNestedDocumentType {\n return {\n name: randomStringWithSpecialChars(12),\n foo: {\n bestFriend\n } as any\n };\n}\n\nexport interface HumanWithTimestampDocumentType {\n id: string;\n name: string;\n age: number;\n updatedAt: number;\n deletedAt?: number;\n}\nexport function humanWithTimestampData(givenData: Partial = {}): HumanWithTimestampDocumentType {\n let ret = {\n id: randomStringWithSpecialChars(12),\n name: faker.person.firstName(),\n age: randomNumber(1, 100),\n // use some time in the past week\n updatedAt: Date.now()\n };\n ret = Object.assign({}, ret, givenData);\n return ret;\n}\n\nexport interface AverageSchemaDocumentType {\n id: string;\n var1: string;\n var2: number;\n deep: {\n deep1: string;\n deep2: string;\n deeper: {\n deepNr: number;\n };\n };\n list: {\n deep1: string;\n deep2: string;\n }[];\n}\n\n\nconst averageSchemaForFieldLength = schemas.averageSchema() as any;\nexport function averageSchemaData(\n partial: Partial = {}\n): AverageSchemaDocumentType {\n return Object.assign(\n {},\n {\n id: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.id.maxLength)),\n var1: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.var1.maxLength)),\n var2: randomNumber(100, ensureNotFalsy(averageSchemaForFieldLength.properties.var2.maximum)),\n deep: {\n deep1: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.deep.properties.deep1.maxLength)),\n deep2: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.deep.properties.deep2.maxLength)),\n deeper: {\n deepNr: randomNumber(0, 10)\n }\n },\n list: new Array(5).fill(0).map(() => ({\n deep1: randomStringWithSpecialChars(5),\n deep2: randomStringWithSpecialChars(8)\n }))\n },\n partial\n );\n}\n\nexport interface PointDocumentType {\n id: string;\n x: number;\n y: number;\n}\nexport function pointData(): PointDocumentType {\n return {\n id: randomStringWithSpecialChars(12),\n x: faker.number.int(),\n y: faker.number.int()\n };\n}\n\nexport interface HumanWithIdAndAgeIndexDocumentType {\n id: string;\n name: string;\n age: number;\n}\nexport function humanWithIdAndAgeIndexDocumentType(\n age: number = randomNumber(1, 100)\n): HumanWithIdAndAgeIndexDocumentType {\n return {\n id: randomStringWithSpecialChars(12),\n name: faker.person.firstName(),\n age\n };\n}\n\nexport type HumanWithCompositePrimary = {\n // optional because it might be created by RxDB and not known before\n id?: string;\n firstName: string;\n lastName: string;\n info: {\n age: number;\n };\n};\nexport function humanWithCompositePrimary(partial: Partial = {}): HumanWithCompositePrimary {\n const defaultObj = {\n firstName: faker.person.firstName(),\n lastName: faker.person.last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EAAEtE,YAAK,CAACuE,MAAM,CAACC,GAAG,CAAC,CAAC;IACrBC,CAAC,EAAEzE,YAAK,CAACuE,MAAM,CAACC,GAAG,CAAC;EACxB,CAAC;AACL;AAOO,SAASE,kCAAkCA,CAC9C7E,GAAW,GAAG,IAAAC,2BAAY,EAAC,CAAC,EAAE,GAAG,CAAC,EACA;EAClC,OAAO;IACHqD,EAAE,EAAE3D,4BAA4B,CAAC,EAAE,CAAC;IACpCsB,IAAI,EAAEd,YAAK,CAACC,MAAM,CAACF,SAAS,CAAC,CAAC;IAC9BF;EACJ,CAAC;AACL;AAWO,SAAS8E,yBAAyBA,CAACtE,OAA2C,GAAG,CAAC,CAAC,EAA6B;EACnH,IAAMC,UAAU,GAAG;IACfP,SAAS,EAAEC,YAAK,CAACC,MAAM,CAACF,SAAS,CAAC,CAAC;IACnCG,QAAQ,EAAEF,YAAK,CAACC,MAAM,CAACC,QAAQ,CAAC,CAAC;IACjC0E,IAAI,EAAE;MACF/E,GAAG,EAAE,IAAAC,2BAAY,EAAC,EAAE,EAAE,EAAE;IAC5B;EACJ,CAAC;EACD,OAAOtB,MAAM,CAAC+B,MAAM,CAChBD,UAAU,EACVD,OACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"schema-objects.js","names":["_faker","require","_asyncTestUtil","schemas","_interopRequireWildcard","_index","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","TEST_DATA_CHARSET","exports","TEST_DATA_CHARSET_LAST_SORTED","ensureNotFalsy","lastOfArray","split","sort","randomStringWithSpecialChars","length","randomString","humanData","passportId","age","randomNumber","firstName","faker","person","lastName","simpleHumanData","simpleHumanV3Data","partial","defaultObj","assign","simpleHumanAge","humanWithSubOther","other","NoIndexHuman","nestedHumanData","mainSkill","name","level","deepNestedHumanData","attack","good","count","bigHumanDocumentType","dnaHash","heroArrayData","skills","Array","fill","map","damage","simpleHeroArray","encryptedHumanData","secret","encryptedObjectHumanData","subname","encryptedDeepHumanDocumentType","firstLevelPassword","secretData","pw","deepSecret","darkhole","nestedSecret","compoundIndexData","passportCountry","compoundIndexNoStringData","nostringIndex","refHumanData","bestFriend","refHumanNestedData","foo","humanWithTimestampData","givenData","ret","id","updatedAt","Date","now","averageSchemaForFieldLength","averageSchema","averageSchemaData","properties","maxLength","var1","var2","maximum","deep","deep1","deep2","deeper","deepNr","list","pointData","x","number","int","y","humanWithIdAndAgeIndexDocumentType","humanWithCompositePrimary","info"],"sources":["../../../../src/plugins/test-utils/schema-objects.ts"],"sourcesContent":["/**\n * this file contains objects which match the schemas in schemas.js\n */\n\nimport { faker } from '@faker-js/faker';\n\nimport {\n randomNumber,\n randomString\n} from 'async-test-util';\nimport { HumanDocumentType } from './schemas.ts';\nimport * as schemas from './schemas.ts';\nimport { ensureNotFalsy, lastOfArray } from '../utils/index.ts';\n\n/**\n * Some storages had problems with umlauts and other special chars.\n * So we add these to all test strings.\n * TODO add emojis\n */\nexport const TEST_DATA_CHARSET = '0987654321ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzäöüÖÄßÜ[]{}\\'';\nexport const TEST_DATA_CHARSET_LAST_SORTED = ensureNotFalsy(lastOfArray(TEST_DATA_CHARSET.split('').sort()));\n// const someEmojis = '😊💩👵🍌';\nexport function randomStringWithSpecialChars(length: number) {\n return randomString(length, TEST_DATA_CHARSET);\n}\n\n\nexport interface SimpleHumanDocumentType {\n passportId: string;\n firstName: string;\n lastName: string;\n}\n\nexport function humanData(\n passportId: string = randomStringWithSpecialChars(12),\n age: number = randomNumber(10, 50),\n firstName: string = faker.person.firstName()\n): HumanDocumentType {\n return {\n passportId: passportId,\n firstName,\n lastName: faker.person.lastName(),\n age\n };\n}\n\nexport function simpleHumanData(): SimpleHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n lastName: faker.person.lastName()\n };\n}\n\nexport interface SimpleHumanV3DocumentType {\n passportId: string;\n age: number;\n oneOptional?: string;\n}\nexport function simpleHumanV3Data(partial: Partial = {}): SimpleHumanV3DocumentType {\n const defaultObj = {\n passportId: randomStringWithSpecialChars(12),\n age: randomNumber(10, 50)\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface SimpleHumanAgeDocumentType {\n passportId: string;\n age: string;\n}\nexport function simpleHumanAge(partial: Partial = {}): SimpleHumanAgeDocumentType {\n const defaultObj = {\n passportId: randomStringWithSpecialChars(12),\n age: randomNumber(10, 50) + ''\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface HumanWithSubOtherDocumentType {\n passportId: string;\n other: {\n age: number;\n };\n}\nexport function humanWithSubOther(): HumanWithSubOtherDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n other: {\n age: randomNumber(10, 50)\n }\n };\n}\n\nexport interface NoIndexHumanDocumentType {\n firstName: string;\n lastName: string;\n}\nexport function NoIndexHuman(): NoIndexHumanDocumentType {\n return {\n firstName: faker.person.firstName(),\n lastName: faker.person.lastName()\n };\n}\n\nexport interface NestedHumanDocumentType {\n passportId: string;\n firstName: string;\n mainSkill: {\n name: string;\n level: number;\n };\n}\nexport function nestedHumanData(partial: Partial = {}): NestedHumanDocumentType {\n const defaultObj = {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n mainSkill: {\n name: randomStringWithSpecialChars(6),\n level: 5\n }\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface DeepNestedHumanDocumentType {\n passportId: string;\n mainSkill: {\n name: string;\n attack: {\n good: boolean;\n count: number;\n };\n };\n}\nexport function deepNestedHumanData(): DeepNestedHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n mainSkill: {\n name: randomStringWithSpecialChars(6),\n attack: {\n good: false,\n count: 5\n }\n }\n };\n}\n\nexport interface BigHumanDocumentType {\n passportId: string;\n dnaHash: string;\n firstName: string;\n lastName: string;\n age: number;\n}\nexport function bigHumanDocumentType(): BigHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n dnaHash: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n lastName: faker.person.lastName(),\n age: randomNumber(10, 50)\n };\n}\n\nexport interface HeroArrayDocumentType {\n name: string;\n skills: {\n name: string;\n damage: number;\n }[];\n}\nexport function heroArrayData(): HeroArrayDocumentType {\n return {\n name: randomStringWithSpecialChars(6),\n skills: new Array(3).fill(0).map(() => {\n return {\n name: randomStringWithSpecialChars(6),\n damage: randomNumber(10, 50)\n };\n })\n };\n}\n\nexport interface SimpleHeroArrayDocumentType {\n name: string;\n skills: string[];\n}\nexport function simpleHeroArray(partial: Partial = {}): SimpleHeroArrayDocumentType {\n const defaultObj = {\n name: randomStringWithSpecialChars(6),\n skills: new Array(3).fill(0).map(() => randomStringWithSpecialChars(6))\n };\n return Object.assign(\n defaultObj,\n partial\n );\n}\n\nexport interface EncryptedHumanDocumentType {\n passportId: string;\n firstName: string;\n secret: string;\n}\nexport function encryptedHumanData(secret = randomStringWithSpecialChars(12)): EncryptedHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n secret\n };\n}\n\nexport interface EncryptedObjectHumanDocumentType {\n passportId: string;\n firstName: string;\n secret: {\n name: string;\n subname: string;\n };\n}\nexport function encryptedObjectHumanData(): EncryptedObjectHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n secret: {\n name: randomStringWithSpecialChars(12),\n subname: randomStringWithSpecialChars(12)\n }\n };\n}\n\nexport interface EncryptedDeepHumanDocumentType {\n passportId: string;\n firstName: string;\n firstLevelPassword: string;\n secretData: {\n pw: string;\n };\n deepSecret: {\n darkhole: {\n pw: string;\n };\n };\n nestedSecret: {\n darkhole: {\n pw: string;\n };\n };\n}\nexport function encryptedDeepHumanDocumentType(): EncryptedDeepHumanDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n firstName: faker.person.firstName(),\n firstLevelPassword: randomStringWithSpecialChars(12),\n secretData: {\n pw: randomStringWithSpecialChars(12)\n },\n deepSecret: {\n darkhole: {\n pw: randomStringWithSpecialChars(12)\n }\n },\n nestedSecret: {\n darkhole: {\n pw: randomStringWithSpecialChars(12)\n }\n }\n };\n}\n\nexport interface CompoundIndexDocumentType {\n passportId: string;\n passportCountry: string;\n age: number;\n}\nexport function compoundIndexData(): CompoundIndexDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n passportCountry: randomStringWithSpecialChars(12),\n age: randomNumber(10, 50)\n };\n}\n\nexport interface CompoundIndexNoStringDocumentType {\n passportId: string;\n passportCountry: { [prop: string]: string; };\n age: number;\n}\nexport function compoundIndexNoStringData(): CompoundIndexNoStringDocumentType {\n return {\n passportId: randomStringWithSpecialChars(12),\n passportCountry: { [randomStringWithSpecialChars(12)]: randomStringWithSpecialChars(12) },\n age: randomNumber(10, 50)\n };\n}\n\nexport interface NostringIndexDocumentType {\n passportId: {};\n firstName: string;\n}\nexport function nostringIndex(): NostringIndexDocumentType {\n return {\n passportId: {},\n firstName: faker.person.firstName()\n };\n}\n\nexport interface RefHumanDocumentType {\n name: string;\n bestFriend: string;\n}\nexport function refHumanData(bestFriend?: string): RefHumanDocumentType {\n return {\n name: randomStringWithSpecialChars(12),\n bestFriend\n } as any;\n}\n\nexport interface RefHumanNestedDocumentType {\n name: string;\n foo: {\n bestFriend: string;\n };\n}\nexport function refHumanNestedData(bestFriend?: string): RefHumanNestedDocumentType {\n return {\n name: randomStringWithSpecialChars(12),\n foo: {\n bestFriend\n } as any\n };\n}\n\nexport interface HumanWithTimestampDocumentType {\n id: string;\n name: string;\n age: number;\n updatedAt: number;\n deletedAt?: number;\n}\nexport function humanWithTimestampData(givenData: Partial = {}): HumanWithTimestampDocumentType {\n let ret = {\n id: randomStringWithSpecialChars(12),\n name: faker.person.firstName(),\n age: randomNumber(1, 100),\n // use some time in the past week\n updatedAt: Date.now()\n };\n ret = Object.assign({}, ret, givenData);\n return ret;\n}\n\nexport interface AverageSchemaDocumentType {\n id: string;\n var1: string;\n var2: number;\n deep: {\n deep1: string;\n deep2: string;\n deeper: {\n deepNr: number;\n };\n };\n list: {\n deep1: string;\n deep2: string;\n }[];\n}\n\n\nconst averageSchemaForFieldLength = schemas.averageSchema() as any;\nexport function averageSchemaData(\n partial: Partial = {}\n): AverageSchemaDocumentType {\n return Object.assign(\n {},\n {\n id: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.id.maxLength)),\n var1: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.var1.maxLength)),\n var2: randomNumber(100, ensureNotFalsy(averageSchemaForFieldLength.properties.var2.maximum)),\n deep: {\n deep1: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.deep.properties.deep1.maxLength)),\n deep2: randomStringWithSpecialChars(ensureNotFalsy(averageSchemaForFieldLength.properties.deep.properties.deep2.maxLength)),\n deeper: {\n deepNr: randomNumber(0, 10)\n }\n },\n list: new Array(5).fill(0).map(() => ({\n deep1: randomStringWithSpecialChars(5),\n deep2: randomStringWithSpecialChars(8)\n }))\n },\n partial\n );\n}\n\nexport interface PointDocumentType {\n id: string;\n x: number;\n y: number;\n}\nexport function pointData(): PointDocumentType {\n return {\n id: randomStringWithSpecialChars(12),\n x: faker.number.int(),\n y: faker.number.int()\n };\n}\n\nexport interface HumanWithIdAndAgeIndexDocumentType {\n id: string;\n name: string;\n age: number;\n}\nexport function humanWithIdAndAgeIndexDocumentType(\n age: number = randomNumber(1, 100)\n): HumanWithIdAndAgeIndexDocumentType {\n return {\n id: randomStringWithSpecialChars(12),\n name: faker.person.firstName(),\n age\n };\n}\n\nexport type HumanWithCompositePrimary = {\n // optional because it might be created by RxDB and not known before\n id?: string;\n firstName: string;\n lastName: string;\n info: {\n age: number;\n };\n};\nexport function humanWithCompositePrimary(partial: Partial = {}): HumanWithCompositePrimary {\n const defaultObj = {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CAAC,EAAEtE,YAAK,CAACuE,MAAM,CAACC,GAAG,CAAC,CAAC;IACrBC,CAAC,EAAEzE,YAAK,CAACuE,MAAM,CAACC,GAAG,CAAC;EACxB,CAAC;AACL;AAOO,SAASE,kCAAkCA,CAC9C7E,GAAW,GAAG,IAAAC,2BAAY,EAAC,CAAC,EAAE,GAAG,CAAC,EACA;EAClC,OAAO;IACHqD,EAAE,EAAE3D,4BAA4B,CAAC,EAAE,CAAC;IACpCsB,IAAI,EAAEd,YAAK,CAACC,MAAM,CAACF,SAAS,CAAC,CAAC;IAC9BF;EACJ,CAAC;AACL;AAWO,SAAS8E,yBAAyBA,CAACtE,OAA2C,GAAG,CAAC,CAAC,EAA6B;EACnH,IAAMC,UAAU,GAAG;IACfP,SAAS,EAAEC,YAAK,CAACC,MAAM,CAACF,SAAS,CAAC,CAAC;IACnCG,QAAQ,EAAEF,YAAK,CAACC,MAAM,CAACC,QAAQ,CAAC,CAAC;IACjC0E,IAAI,EAAE;MACF/E,GAAG,EAAE,IAAAC,2BAAY,EAAC,EAAE,EAAE,EAAE;IAC5B;EACJ,CAAC;EACD,OAAOrB,MAAM,CAAC8B,MAAM,CAChBD,UAAU,EACVD,OACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/rx-collection.js b/dist/cjs/rx-collection.js index 2bbe1f50ca1..d5db26dfe8a 100644 --- a/dist/cjs/rx-collection.js +++ b/dist/cjs/rx-collection.js @@ -526,7 +526,7 @@ var RxCollectionBase = exports.RxCollectionBase = /*#__PURE__*/function () { await this.destroy(); await (0, _rxCollectionHelper.removeCollectionStorages)(this.database.storage, this.database.internalStore, this.database.token, this.database.name, this.name, this.database.password, this.database.hashFunction); }; - (0, _createClass2.default)(RxCollectionBase, [{ + return (0, _createClass2.default)(RxCollectionBase, [{ key: "insert$", get: function () { return this.$.pipe((0, _rxjs.filter)(cE => cE.operation === 'INSERT')); @@ -556,7 +556,6 @@ var RxCollectionBase = exports.RxCollectionBase = /*#__PURE__*/function () { return this; } }]); - return RxCollectionBase; }(); /** * adds the hook-functions to the collections prototype diff --git a/dist/cjs/rx-collection.js.map b/dist/cjs/rx-collection.js.map index cdcd4e4cc43..f6e2356d404 100644 --- a/dist/cjs/rx-collection.js.map +++ b/dist/cjs/rx-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection.js","names":["_rxjs","require","_index","_rxCollectionHelper","_rxQuery","_rxError","_docCache","_queryCache","_changeEventBuffer","_hooks","_rxDocumentPrototypeMerge","_rxStorageHelper","_index2","_incrementalWrite","_rxDocument","_overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","exports","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","defaultCacheReplacementPolicy","statics","conflictHandler","defaultConflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","createQueryCache","$","checkpoint$","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","getWrappedStorageInstance","jsonSchema","IncrementalWriteQueue","primaryPath","newData","oldData","beforeDocumentUpdateWrite","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","filter","changeEventBulk","collectionName","mergeMap","events","map","checkpoint","createChangeEventBuffer","DocumentCache","cE","isLocal","docData","createNewRxDocument","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","storageChangeEventToRxChangeEvent","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","cleanup","_minimumDeletedTime","pluginMissing","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","useDocs","useDocData","fillObjectDataBeforeInsert","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","mapDocumentsDataToCacheDocs","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","successIds","d","getFromMapOrThrow","bulkUpsert","insertData","useJsonByDocId","useJson","newRxError","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","isArray","newRxTypeError","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","password","hashFunction","_createClass2","default","operation","collection","colProto","Object","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","overwritable","isDevMode","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration-schema');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration-schema');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n const mangoQuery: MangoQuery = {\n selector: {\n [this.schema.primaryPath]: {\n $in: ids.slice(0)\n }\n } as any\n };\n const query = createRxQuery('findByIds', mangoQuery, this as any);\n return query as any;\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAMA,IAAAC,MAAA,GAAAD,OAAA;AAUA,IAAAE,mBAAA,GAAAF,OAAA;AAKA,IAAAG,QAAA,GAAAH,OAAA;AAIA,IAAAI,QAAA,GAAAJ,OAAA;AAOA,IAAAK,SAAA,GAAAL,OAAA;AAGA,IAAAM,WAAA,GAAAN,OAAA;AAKA,IAAAO,kBAAA,GAAAP,OAAA;AAIA,IAAAQ,MAAA,GAAAR,OAAA;AA6CA,IAAAS,yBAAA,GAAAT,OAAA;AAGA,IAAAU,gBAAA,GAAAV,OAAA;AAMA,IAAAW,OAAA,GAAAX,OAAA;AACA,IAAAY,iBAAA,GAAAZ,OAAA;AACA,IAAAa,WAAA,GAAAb,OAAA;AACA,IAAAc,aAAA,GAAAd,OAAA;AAEA,IAAMe,UAAU,GAAG,CAAC,KAAK,EAAE,MAAM,CAAU;AAE3C,IAAMC,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAU;AAElE,IAAIC,YAAY,GAAG,KAAK;AAAC,IAEZC,gBAAgB,GAAAC,OAAA,CAAAD,gBAAA;EASzB;AACJ;AACA;;EAKI,SAAAA,iBACWE,QAAq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;QACJ;MACJ,CAAC,CAAC;MACF,OAAOsN,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAIC4B,KAAK,CAAC1G,GAAG,IAAI;MACV,OAAOrI,eAAe,CAACqM,KAAK,CAAC,CAAC,CACzBrI,IAAI,CAAC,MAAM6B,OAAO,CAACmJ,MAAM,CAAC3G,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAAS4G,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlQ,gBAAgB;AAC1C","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["_rxjs","require","_index","_rxCollectionHelper","_rxQuery","_rxError","_docCache","_queryCache","_changeEventBuffer","_hooks","_rxDocumentPrototypeMerge","_rxStorageHelper","_index2","_incrementalWrite","_rxDocument","_overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","exports","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","defaultCacheReplacementPolicy","statics","conflictHandler","defaultConflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","createQueryCache","$","checkpoint$","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","getWrappedStorageInstance","jsonSchema","IncrementalWriteQueue","primaryPath","newData","oldData","beforeDocumentUpdateWrite","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","filter","changeEventBulk","collectionName","mergeMap","events","map","checkpoint","createChangeEventBuffer","DocumentCache","cE","isLocal","docData","createNewRxDocument","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","storageChangeEventToRxChangeEvent","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","cleanup","_minimumDeletedTime","pluginMissing","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","useDocs","useDocData","fillObjectDataBeforeInsert","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","mapDocumentsDataToCacheDocs","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","successIds","d","getFromMapOrThrow","bulkUpsert","insertData","useJsonByDocId","useJson","newRxError","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","isArray","newRxTypeError","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","password","hashFunction","_createClass2","default","operation","collection","colProto","Object","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","overwritable","isDevMode","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration-schema');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration-schema');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n const mangoQuery: MangoQuery = {\n selector: {\n [this.schema.primaryPath]: {\n $in: ids.slice(0)\n }\n } as any\n };\n const query = createRxQuery('findByIds', mangoQuery, this as any);\n return query as any;\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAMA,IAAAC,MAAA,GAAAD,OAAA;AAUA,IAAAE,mBAAA,GAAAF,OAAA;AAKA,IAAAG,QAAA,GAAAH,OAAA;AAIA,IAAAI,QAAA,GAAAJ,OAAA;AAOA,IAAAK,SAAA,GAAAL,OAAA;AAGA,IAAAM,WAAA,GAAAN,OAAA;AAKA,IAAAO,kBAAA,GAAAP,OAAA;AAIA,IAAAQ,MAAA,GAAAR,OAAA;AA6CA,IAAAS,yBAAA,GAAAT,OAAA;AAGA,IAAAU,gBAAA,GAAAV,OAAA;AAMA,IAAAW,OAAA,GAAAX,OAAA;AACA,IAAAY,iBAAA,GAAAZ,OAAA;AACA,IAAAa,WAAA,GAAAb,OAAA;AACA,IAAAc,aAAA,GAAAd,OAAA;AAEA,IAAMe,UAAU,GAAG,CAAC,KAAK,EAAE,MAAM,CAAU;AAE3C,IAAMC,UAAU,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,UAAU;QACV2B,OAAO,EAAE;UACL3P,IAAI;UACJC,MAAM;UACNY,eAAe;UACfV,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtBqO,cAAc;UACdnO;QACJ;MACJ,CAAC,CAAC;MACF,OAAOsN,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAIC4B,KAAK,CAAC1G,GAAG,IAAI;MACV,OAAOrI,eAAe,CAACqM,KAAK,CAAC,CAAC,CACzBrI,IAAI,CAAC,MAAM6B,OAAO,CAACmJ,MAAM,CAAC3G,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAAS4G,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlQ,gBAAgB;AAC1C","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/rx-database.js b/dist/cjs/rx-database.js index b7092883a99..cfd94de4aa3 100644 --- a/dist/cjs/rx-database.js +++ b/dist/cjs/rx-database.js @@ -385,7 +385,7 @@ var RxDatabaseBase = exports.RxDatabaseBase = /*#__PURE__*/function () { _proto.remove = function remove() { return this.destroy().then(() => removeRxDatabase(this.name, this.storage, this.password)); }; - (0, _createClass2.default)(RxDatabaseBase, [{ + return (0, _createClass2.default)(RxDatabaseBase, [{ key: "$", get: function () { return this.observable$; @@ -396,7 +396,6 @@ var RxDatabaseBase = exports.RxDatabaseBase = /*#__PURE__*/function () { return this; } }]); - return RxDatabaseBase; }(); /** * checks if an instance with same name and storage already exists diff --git a/dist/cjs/rx-database.js.map b/dist/cjs/rx-database.js.map index e32b2c005ea..030a274102e 100644 --- a/dist/cjs/rx-database.js.map +++ b/dist/cjs/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["_customIdleQueue","require","_index","_rxError","_rxSchema","_hooks","_rxjs","_operators","_rxCollection","_rxStorageHelper","_obliviousSet","_rxDatabaseInternalStore","_rxCollectionHelper","_overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","exports","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","reactivity","idleQueue","IdleQueue","rxdbVersion","RXDB_VERSION","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","states","eventBulks$","Subject","observable$","pipe","mergeMap","changeEventBulk","events","storageToken","PROMISE_RESOLVE_FALSE","storageTokenDocument","emittedEventBulkIds","ObliviousSet","getWrappedStorageInstance","asRxDatabase","INTERNAL_STORE_SCHEMA","ensureStorageTokenDocumentExists","catch","err","push","then","doc","data","_proto","prototype","getReactivityFactory","newRxError","database","$emit","has","id","add","next","removeCollectionDoc","schema","getSingleDocument","getPrimaryKeyOfInternalDocument","_collectionNamePrimary","INTERNAL_CONTEXT_COLLECTION","writeDoc","flatCloneDocWithMeta","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","addState","_name","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","runAsyncPluginHooks","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass2","default","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","INTERNAL_STORAGE_NAME","devMode","overwritable","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashSha256","randomCouchString","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","getAllCollectionDocuments","collectionNames","forEach","removedCollectionNames","Array","from","removeCollectionStorages","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise,\n RxState\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\nimport type { RxReactivityFactory } from './types/plugins/reactivity.d.ts';\n\n/**\n * stores the used database names+storage names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n Reactivity = unknown\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean,\n public readonly reactivity?: RxReactivityFactory\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public getReactivityFactory(): RxReactivityFactory {\n if (!this.reactivity) {\n throw newRxError('DB14', { database: this.name });\n }\n return this.reactivity;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Because having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public states: { [name: string]: RxState; } = {};\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n addState(_name?: string): Promise> {\n throw pluginMissing('state');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration-schema');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stuff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.storage.name + '|' + this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage, this.password));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions,\n Reactivity\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and storage already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string,\n storage: RxStorage\n) {\n const key = storage.name + '|' + name;\n if (!USED_DATABASE_NAMES.has(key)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n storage: storage.name,\n link: 'https://rxdb.info/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password,\n devMode: overwritable.isDevMode()\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any,\n Reactivity = unknown\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = true,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256,\n reactivity\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n> {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name, storage);\n }\n USED_DATABASE_NAMES.add(storage.name + '|' + name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(storage.name + '|' + name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount,\n reactivity\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage,\n password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName,\n password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAAA,gBAAA,GAAAC,OAAA;AA+BA,IAAAC,MAAA,GAAAD,OAAA;AAWA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,SAAA,GAAAH,OAAA;AAIA,IAAAI,MAAA,GAAAJ,OAAA;AAIA,IAAAK,KAAA,GAAAL,OAAA;AAKA,IAAAM,UAAA,GAAAN,OAAA;AAGA,IAAAO,aAAA,GAAAP,OAAA;AAGA,IAAAQ,gBAAA,GAAAR,OAAA;AAQA,IAAAS,aAAA,GAAAT,OAAA;AACA,IAAAU,wBAAA,GAAAV,OAAA;AAQA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AACG,OAAO,CAAC9H,GAAG,IAAI6H,eAAe,CAACnH,GAAG,CAACV,GAAG,CAACC,IAAI,CAAC7C,IAAI,CAAC,CAAC;EACjE,IAAM2K,sBAAgC,GAAGC,KAAK,CAACC,IAAI,CAACJ,eAAe,CAAC;EAEpE,MAAM/F,OAAO,CAACC,GAAG,CACbgG,sBAAsB,CAAC7F,GAAG,CAACE,cAAc,IAAI,IAAA8F,4CAAwB,EACjE5K,OAAO,EACPoK,0BAA0B,EAC1Bf,qBAAqB,EACrBC,YAAY,EACZxE,cAAc,EACd5E,QACJ,CAAC,CACL,CAAC;EAED,MAAM,IAAAqI,0BAAmB,EAAC,sBAAsB,EAAE;IAC9Ce,YAAY;IACZtJ;EACJ,CAAC,CAAC;EAEF,MAAMoK,0BAA0B,CAACtB,MAAM,CAAC,CAAC;EACzC,OAAO2B,sBAAsB;AACjC;AAEO,SAASI,YAAYA,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYlL,cAAc;AACxC;AAEO,SAASmL,OAAOA,CAAA,EAAW;EAC9B,OAAOpL,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeqL,iCAAiCA,CACnDhI,QAAoB,EACJ;EAChB,IAAMiI,QAAQ,GAAG,MAAMjI,QAAQ,CAACjB,oBAAoB;EACpD,OAAOkJ,QAAQ,CAACtI,IAAI,CAACuI,aAAa,KAAKlI,QAAQ,CAACjD,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeuG,qBAAqBA,CACvC4D,UAA8C,EAChD;EACE,MAAMA,UAAU,CAACrI,YAAY;EAC7B,IAAIqI,UAAU,CAACjJ,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMiJ,UAAU,CAACjJ,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-database.js","names":["_customIdleQueue","require","_index","_rxError","_rxSchema","_hooks","_rxjs","_operators","_rxCollection","_rxStorageHelper","_obliviousSet","_rxDatabaseInternalStore","_rxCollectionHelper","_overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","exports","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","reactivity","idleQueue","IdleQueue","rxdbVersion","RXDB_VERSION","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","states","eventBulks$","Subject","observable$","pipe","mergeMap","changeEventBulk","events","storageToken","PROMISE_RESOLVE_FALSE","storageTokenDocument","emittedEventBulkIds","ObliviousSet","getWrappedStorageInstance","asRxDatabase","INTERNAL_STORE_SCHEMA","ensureStorageTokenDocumentExists","catch","err","push","then","doc","data","_proto","prototype","getReactivityFactory","newRxError","database","$emit","has","id","add","next","removeCollectionDoc","schema","getSingleDocument","getPrimaryKeyOfInternalDocument","_collectionNamePrimary","INTERNAL_CONTEXT_COLLECTION","writeDoc","flatCloneDocWithMeta","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","addState","_name","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","runAsyncPluginHooks","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass2","default","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","INTERNAL_STORAGE_NAME","devMode","overwritable","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashSha256","randomCouchString","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","getAllCollectionDocuments","collectionNames","forEach","removedCollectionNames","Array","from","removeCollectionStorages","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise,\n RxState\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\nimport type { RxReactivityFactory } from './types/plugins/reactivity.d.ts';\n\n/**\n * stores the used database names+storage names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n Reactivity = unknown\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean,\n public readonly reactivity?: RxReactivityFactory\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public getReactivityFactory(): RxReactivityFactory {\n if (!this.reactivity) {\n throw newRxError('DB14', { database: this.name });\n }\n return this.reactivity;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Because having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public states: { [name: string]: RxState; } = {};\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n addState(_name?: string): Promise> {\n throw pluginMissing('state');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration-schema');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stuff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.storage.name + '|' + this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage, this.password));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions,\n Reactivity\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and storage already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string,\n storage: RxStorage\n) {\n const key = storage.name + '|' + name;\n if (!USED_DATABASE_NAMES.has(key)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n storage: storage.name,\n link: 'https://rxdb.info/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password,\n devMode: overwritable.isDevMode()\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any,\n Reactivity = unknown\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = true,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256,\n reactivity\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n> {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name, storage);\n }\n USED_DATABASE_NAMES.add(storage.name + '|' + name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(storage.name + '|' + name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount,\n reactivity\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage,\n password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName,\n password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAAA,gBAAA,GAAAC,OAAA;AA+BA,IAAAC,MAAA,GAAAD,OAAA;AAWA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,SAAA,GAAAH,OAAA;AAIA,IAAAI,MAAA,GAAAJ,OAAA;AAIA,IAAAK,KAAA,GAAAL,OAAA;AAKA,IAAAM,UAAA,GAAAN,OAAA;AAGA,IAAAO,aAAA,GAAAP,OAAA;AAGA,IAAAQ,gBAAA,GAAAR,OAAA;AAQA,IAAAS,aAA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.js index 732af31b6ec..fc81f11fe66 100644 --- a/dist/cjs/rx-error.js +++ b/dist/cjs/rx-error.js @@ -44,7 +44,6 @@ function messageForError(message, code, parameters) { return 'RxError (' + code + '):' + '\n' + message + '\n' + parametersToString(parameters); } var RxError = exports.RxError = /*#__PURE__*/function (_Error) { - (0, _inheritsLoose2.default)(RxError, _Error); // always true, use this to detect if its an rxdb-error function RxError(code, message, parameters = {}) { @@ -57,11 +56,12 @@ var RxError = exports.RxError = /*#__PURE__*/function (_Error) { _this.rxdb = true; // tag them as internal return _this; } + (0, _inheritsLoose2.default)(RxError, _Error); var _proto = RxError.prototype; _proto.toString = function toString() { return this.message; }; - (0, _createClass2.default)(RxError, [{ + return (0, _createClass2.default)(RxError, [{ key: "name", get: function () { return 'RxError (' + this.code + ')'; @@ -72,10 +72,8 @@ var RxError = exports.RxError = /*#__PURE__*/function (_Error) { return false; } }]); - return RxError; }( /*#__PURE__*/(0, _wrapNativeSuper2.default)(Error)); var RxTypeError = exports.RxTypeError = /*#__PURE__*/function (_TypeError) { - (0, _inheritsLoose2.default)(RxTypeError, _TypeError); // always true, use this to detect if its an rxdb-error function RxTypeError(code, message, parameters = {}) { @@ -88,11 +86,12 @@ var RxTypeError = exports.RxTypeError = /*#__PURE__*/function (_TypeError) { _this2.rxdb = true; // tag them as internal return _this2; } + (0, _inheritsLoose2.default)(RxTypeError, _TypeError); var _proto2 = RxTypeError.prototype; _proto2.toString = function toString() { return this.message; }; - (0, _createClass2.default)(RxTypeError, [{ + return (0, _createClass2.default)(RxTypeError, [{ key: "name", get: function () { return 'RxTypeError (' + this.code + ')'; @@ -103,7 +102,6 @@ var RxTypeError = exports.RxTypeError = /*#__PURE__*/function (_TypeError) { return true; } }]); - return RxTypeError; }( /*#__PURE__*/(0, _wrapNativeSuper2.default)(TypeError)); function newRxError(code, parameters) { return new RxError(code, _overwritable.overwritable.tunnelErrorMessage(code), parameters); diff --git a/dist/cjs/rx-error.js.map b/dist/cjs/rx-error.js.map index c8d476b9ef1..6d4f7e45680 100644 --- a/dist/cjs/rx-error.js.map +++ b/dist/cjs/rx-error.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.js","names":["_overwritable","require","parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","err","JSON","stringify","getOwnPropertyNames","_k","v","undefined","e","join","messageForError","message","code","RxError","exports","_Error","_inheritsLoose2","default","_this","mes","call","rxdb","_proto","prototype","toString","_createClass2","key","get","_wrapNativeSuper2","Error","RxTypeError","_TypeError","_this2","_proto2","TypeError","newRxError","overwritable","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","status","STORAGE_WRITE_ERROR_CODE_TO_MESSAGE","rxStorageWriteErrorToRxError","name","document","documentId","writeError"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable.ts';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageWriteError,\n RxStorageWriteErrorConflict\n} from './types/index.d.ts';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n if (k === 'errors') {\n paramStr = parameters[k].map((err: any) => JSON.stringify(err, Object.getOwnPropertyNames(err)));\n } else {\n paramStr = JSON.stringify(parameters[k], function (_k, v) {\n return v === undefined ? null : v;\n }, 2);\n }\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err?: RxStorageWriteError | any\n): RxStorageWriteErrorConflict | false {\n if (\n err &&\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n\n\nconst STORAGE_WRITE_ERROR_CODE_TO_MESSAGE: { [k: number]: string; } = {\n 409: 'document write conflict',\n 422: 'schema validation error',\n 510: 'attachment data missing'\n};\n\nexport function rxStorageWriteErrorToRxError(err: RxStorageWriteError): RxError {\n return newRxError('COL20', {\n name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status],\n document: err.documentId,\n writeError: err\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA,IAAAA,aAAA,GAAAC,OAAA;AAJA;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AAO,KAAK;EAChB;AACJ;AAGA,IAAMwC,mCAA6D,GAAG;EAClE,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE;AACT,CAAC;AAEM,SAASC,4BAA4BA,CAACzC,GAA6B,EAAW;EACjF,OAAOkC,UAAU,CAAC,OAAO,EAAE;IACvBQ,IAAI,EAAEF,mCAAmC,CAACxC,GAAG,CAACuC,MAAM,CAAC;IACrDI,QAAQ,EAAE3C,GAAG,CAAC4C,UAAU;IACxBC,UAAU,EAAE7C;EAChB,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-error.js","names":["_overwritable","require","parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","err","JSON","stringify","getOwnPropertyNames","_k","v","undefined","e","join","messageForError","message","code","RxError","exports","_Error","_this","mes","call","rxdb","_inheritsLoose2","default","_proto","prototype","toString","_createClass2","key","get","_wrapNativeSuper2","Error","RxTypeError","_TypeError","_this2","_proto2","TypeError","newRxError","overwritable","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","status","STORAGE_WRITE_ERROR_CODE_TO_MESSAGE","rxStorageWriteErrorToRxError","name","document","documentId","writeError"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable.ts';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageWriteError,\n RxStorageWriteErrorConflict\n} from './types/index.d.ts';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n if (k === 'errors') {\n paramStr = parameters[k].map((err: any) => JSON.stringify(err, Object.getOwnPropertyNames(err)));\n } else {\n paramStr = JSON.stringify(parameters[k], function (_k, v) {\n return v === undefined ? null : v;\n }, 2);\n }\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err?: RxStorageWriteError | any\n): RxStorageWriteErrorConflict | false {\n if (\n err &&\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n\n\nconst STORAGE_WRITE_ERROR_CODE_TO_MESSAGE: { [k: number]: string; } = {\n 409: 'document write conflict',\n 422: 'schema validation error',\n 510: 'attachment data missing'\n};\n\nexport function rxStorageWriteErrorToRxError(err: RxStorageWriteError): RxError {\n return newRxError('COL20', {\n name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status],\n document: err.documentId,\n writeError: err\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA,IAAAA,aAAA,GAAAC,OAAA;AAJA;AACA;AACA;;AAUA;AACA;AACA;AACA,SAASC,kBAAkBA,CAACC,UAAe,EAAU;EACjD,IAAIC,GAAG,GAAG,EAAE;EACZ,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CAACI,MAAM,KAAK,CAAC,EACpC,OAAOH,GAAG;EACdA,GAAG,IAAI,uBAAuB;EAC9BA,GAAG,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CACzBK,GAAG,CAACC,CAAC,IAAI;IACN,IAAIC,QAAQ,GAAG,iBAAiB;IAChC,IAAI;MACA,IAAID,CAAC,KAAK,QAAQ,EAAE;QAChBC,QAAQ,GAAGP,UAAU,CAACM,CAAC,CAAC,CAACD,GAAG,CAAEG,GAAQ,IAAKC,IAAI,CAACC,SAAS,CAACF,GAAG,EAAEN,MAAM,CAACS,mBAAmB,CAACH,GAAG,CAAC,CAAC,CAAC;MACpG,CAAC,MAAM;QACHD,QAAQ,GAAGE,IAAI,CAACC,SAAS,CAACV,UAAU,CAACM,CAAC,CAAC,EAAE,UAAUM,EAAE,EAAEC,CAAC,EAAE;UACtD,OAAOA,CAAC,KAAKC,SAAS,GAAG,IAAI,GAAGD,CAAC;QACrC,CAAC,EAAE,CAAC,CAAC;MACT;IACJ,CAAC,CAAC,OAAOE,CAAC,EAAE,CAAE;IACd,OAAOT,CAAC,GAAG,GAAG,GAAGC,QAAQ;EAC7B,CAAC,CAAC,CACDS,IAAI,CAAC,IAAI,CAAC;EACff,GAAG,IAAI,GA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qC,WAAW,CAClBlB,IAAI,EACJwB,0BAAY,CAACC,kBAAkB,CAACzB,IAAI,CAAC,EACrCnB,UACJ,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACO,SAAS8C,wBAAwBA,CACpCtC,GAA0C,EACI;EAC9C,IACIA,GAAG,IACHA,GAAG,CAACuC,MAAM,KAAK,GAAG,EACpB;IACE,OAAOvC,GAAG;EACd,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ;AAGA,IAAMwC,mCAA6D,GAAG;EAClE,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE;AACT,CAAC;AAEM,SAASC,4BAA4BA,CAACzC,GAA6B,EAAW;EACjF,OAAOkC,UAAU,CAAC,OAAO,EAAE;IACvBQ,IAAI,EAAEF,mCAAmC,CAACxC,GAAG,CAACuC,MAAM,CAAC;IACrDI,QAAQ,EAAE3C,GAAG,CAAC4C,UAAU;IACxBC,UAAU,EAAE7C;EAChB,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/rx-query-single-result.js b/dist/cjs/rx-query-single-result.js index 7228f3a8a94..40a088fc813 100644 --- a/dist/cjs/rx-query-single-result.js +++ b/dist/cjs/rx-query-single-result.js @@ -39,7 +39,7 @@ var RxQuerySingleResult = exports.RxQuerySingleResult = /*#__PURE__*/function () * to ensure we do not store the same data twice and fill up the memory. * @overwrites itself with the actual value */ - (0, _createClass2.default)(RxQuerySingleResult, [{ + return (0, _createClass2.default)(RxQuerySingleResult, [{ key: "docsData", get: function () { return (0, _index.overwriteGetterForCaching)(this, 'docsData', this.documents.map(d => d._data)); @@ -67,6 +67,5 @@ var RxQuerySingleResult = exports.RxQuerySingleResult = /*#__PURE__*/function () return (0, _index.overwriteGetterForCaching)(this, 'docsMap', map); } }]); - return RxQuerySingleResult; }(); //# sourceMappingURL=rx-query-single-result.js.map \ No newline at end of file diff --git a/dist/cjs/rx-query-single-result.js.map b/dist/cjs/rx-query-single-result.js.map index 810be50e2e8..cedfe3a30af 100644 --- a/dist/cjs/rx-query-single-result.js.map +++ b/dist/cjs/rx-query-single-result.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query-single-result.js","names":["_docCache","require","_index","RxQuerySingleResult","exports","collection","docsDataFromStorageInstance","count","time","now","documents","mapDocumentsDataToCacheDocs","_createClass2","default","key","get","overwriteGetterForCaching","map","d","_data","Map","forEach","set","primary","i","length","doc"],"sources":["../../src/rx-query-single-result.ts"],"sourcesContent":["import { mapDocumentsDataToCacheDocs } from './doc-cache.ts';\nimport { now, overwriteGetterForCaching } from './plugins/utils/index.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\n\n/**\n * RxDB needs the query results in multiple formats.\n * Sometimes as a Map or an array with only the documentData.\n * For better performance we work with this class\n * that initializes stuff lazily so that\n * we can directly work with the query results after RxQuery.exec()\n */\nexport class RxQuerySingleResult{\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n public readonly time = now();\n public readonly documents: RxDocument[];\n constructor(\n public readonly collection: RxCollection,\n // only used internally, do not use outside, use this.docsData instead\n docsDataFromStorageInstance: RxDocumentData[],\n // can be overwritten for count-queries\n public readonly count: number,\n ) {\n this.documents = mapDocumentsDataToCacheDocs(this.collection._docCache, docsDataFromStorageInstance);\n }\n\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n * @overwrites itself with the actual value\n */\n get docsData(): RxDocumentData[] {\n return overwriteGetterForCaching(\n this,\n 'docsData',\n this.documents.map(d => d._data)\n );\n }\n\n\n // A key->document map, used in the event reduce optimization.\n get docsDataMap(): Map> {\n const map = new Map>();\n this.documents.forEach(d => {\n map.set(d.primary, d._data);\n });\n return overwriteGetterForCaching(\n this,\n 'docsDataMap',\n map\n );\n }\n\n get docsMap(): Map> {\n const map = new Map>();\n const documents = this.documents;\n for (let i = 0; i < documents.length; i++) {\n const doc = documents[i];\n map.set(doc.primary, doc);\n }\n return overwriteGetterForCaching(\n this,\n 'docsMap',\n map\n );\n }\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,SAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,IAOaE,mBAAmB,GAAAC,OAAA,CAAAD,mBAAA;EAC5B;AACJ;AACA;AACA;AACA;;EAGI,SAAAA,oBACoBE,UAAmC;EACnD;EACAC,2BAAwD;EACxD;EACgBC,KAAa,EAC/B;IAAA,KARcC,IAAI,GAAG,IAAAC,UAAG,EAAC,CAAC;IAAA,KAGRJ,UAAmC,GAAnCA,UAAmC;IAAA,KAInCE,KAAa,GAAbA,KAAa;IAE7B,IAAI,CAACG,SAAS,GAAG,IAAAC,qCAA2B,EAAiB,IAAI,CAACN,UAAU,CAACL,SAAS,EAAEM,2BAA2B,CAAC;EACxH;;EAGA;AACJ;AACA;AACA;AACA;AACA;EALI,IAAAM,aAAA,CAAAC,OAAA,EAAAV,mBAAA;IAAAW,GAAA;IAAAC,GAAA,EAMA,SAAAA,CAAA,EAA4C;MACxC,OAAO,IAAAC,gCAAyB,EAC5B,IAAI,EACJ,UAAU,EACV,IAAI,CAACN,SAAS,CAACO,GAAG,CAACC,CAAC,IAAIA,CAAC,CAACC,KAAK,CACnC,CAAC;IACL;;IAGA;EAAA;IAAAL,GAAA;IAAAC,GAAA,EACA,SAAAA,CAAA,EAA0D;MACtD,IAAME,GAAG,GAAG,IAAIG,GAAG,CAAoC,CAAC;MACxD,IAAI,CAACV,SAAS,CAACW,OAAO,CAACH,CAAC,IAAI;QACxBD,GAAG,CAACK,GAAG,CAACJ,CAAC,CAACK,OAAO,EAAEL,CAAC,CAACC,KAAK,CAAC;MAC/B,CAAC,CAAC;MACF,OAAO,IAAAH,gCAAyB,EAC5B,IAAI,EACJ,aAAa,EACbC,GACJ,CAAC;IACL;EAAC;IAAAH,GAAA;IAAAC,GAAA,EAED,SAAAA,CAAA,EAAkD;MAC9C,IAAME,GAAG,GAAG,IAAIG,GAAG,CAAgC,CAAC;MACpD,IAAMV,SAAS,GAAG,IAAI,CAACA,SAAS;MAChC,KAAK,IAAIc,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGd,SAAS,CAACe,MAAM,EAAED,CAAC,EAAE,EAAE;QACvC,IAAME,GAAG,GAAGhB,SAAS,CAACc,CAAC,CAAC;QACxBP,GAAG,CAACK,GAAG,CAACI,GAAG,CAACH,OAAO,EAAEG,GAAG,CAAC;MAC7B;MACA,OAAO,IAAAV,gCAAyB,EAC5B,IAAI,EACJ,SAAS,EACTC,GACJ,CAAC;IACL;EAAC;EAAA,OAAAd,mBAAA;AAAA","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-query-single-result.js","names":["_docCache","require","_index","RxQuerySingleResult","exports","collection","docsDataFromStorageInstance","count","time","now","documents","mapDocumentsDataToCacheDocs","_createClass2","default","key","get","overwriteGetterForCaching","map","d","_data","Map","forEach","set","primary","i","length","doc"],"sources":["../../src/rx-query-single-result.ts"],"sourcesContent":["import { mapDocumentsDataToCacheDocs } from './doc-cache.ts';\nimport { now, overwriteGetterForCaching } from './plugins/utils/index.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\n\n/**\n * RxDB needs the query results in multiple formats.\n * Sometimes as a Map or an array with only the documentData.\n * For better performance we work with this class\n * that initializes stuff lazily so that\n * we can directly work with the query results after RxQuery.exec()\n */\nexport class RxQuerySingleResult{\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n public readonly time = now();\n public readonly documents: RxDocument[];\n constructor(\n public readonly collection: RxCollection,\n // only used internally, do not use outside, use this.docsData instead\n docsDataFromStorageInstance: RxDocumentData[],\n // can be overwritten for count-queries\n public readonly count: number,\n ) {\n this.documents = mapDocumentsDataToCacheDocs(this.collection._docCache, docsDataFromStorageInstance);\n }\n\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n * @overwrites itself with the actual value\n */\n get docsData(): RxDocumentData[] {\n return overwriteGetterForCaching(\n this,\n 'docsData',\n this.documents.map(d => d._data)\n );\n }\n\n\n // A key->document map, used in the event reduce optimization.\n get docsDataMap(): Map> {\n const map = new Map>();\n this.documents.forEach(d => {\n map.set(d.primary, d._data);\n });\n return overwriteGetterForCaching(\n this,\n 'docsDataMap',\n map\n );\n }\n\n get docsMap(): Map> {\n const map = new Map>();\n const documents = this.documents;\n for (let i = 0; i < documents.length; i++) {\n const doc = documents[i];\n map.set(doc.primary, doc);\n }\n return overwriteGetterForCaching(\n this,\n 'docsMap',\n map\n );\n }\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,SAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,IAOaE,mBAAmB,GAAAC,OAAA,CAAAD,mBAAA;EAC5B;AACJ;AACA;AACA;AACA;;EAGI,SAAAA,oBACoBE,UAAmC;EACnD;EACAC,2BAAwD;EACxD;EACgBC,KAAa,EAC/B;IAAA,KARcC,IAAI,GAAG,IAAAC,UAAG,EAAC,CAAC;IAAA,KAGRJ,UAAmC,GAAnCA,UAAmC;IAAA,KAInCE,KAAa,GAAbA,KAAa;IAE7B,IAAI,CAACG,SAAS,GAAG,IAAAC,qCAA2B,EAAiB,IAAI,CAACN,UAAU,CAACL,SAAS,EAAEM,2BAA2B,CAAC;EACxH;;EAGA;AACJ;AACA;AACA;AACA;AACA;EALI,WAAAM,aAAA,CAAAC,OAAA,EAAAV,mBAAA;IAAAW,GAAA;IAAAC,GAAA,EAMA,SAAAA,CAAA,EAA4C;MACxC,OAAO,IAAAC,gCAAyB,EAC5B,IAAI,EACJ,UAAU,EACV,IAAI,CAACN,SAAS,CAACO,GAAG,CAACC,CAAC,IAAIA,CAAC,CAACC,KAAK,CACnC,CAAC;IACL;;IAGA;EAAA;IAAAL,GAAA;IAAAC,GAAA,EACA,SAAAA,CAAA,EAA0D;MACtD,IAAME,GAAG,GAAG,IAAIG,GAAG,CAAoC,CAAC;MACxD,IAAI,CAACV,SAAS,CAACW,OAAO,CAACH,CAAC,IAAI;QACxBD,GAAG,CAACK,GAAG,CAACJ,CAAC,CAACK,OAAO,EAAEL,CAAC,CAACC,KAAK,CAAC;MAC/B,CAAC,CAAC;MACF,OAAO,IAAAH,gCAAyB,EAC5B,IAAI,EACJ,aAAa,EACbC,GACJ,CAAC;IACL;EAAC;IAAAH,GAAA;IAAAC,GAAA,EAED,SAAAA,CAAA,EAAkD;MAC9C,IAAME,GAAG,GAAG,IAAIG,GAAG,CAAgC,CAAC;MACpD,IAAMV,SAAS,GAAG,IAAI,CAACA,SAAS;MAChC,KAAK,IAAIc,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGd,SAAS,CAACe,MAAM,EAAED,CAAC,EAAE,EAAE;QACvC,IAAME,GAAG,GAAGhB,SAAS,CAACc,CAAC,CAAC;QACxBP,GAAG,CAACK,GAAG,CAACI,GAAG,CAACH,OAAO,EAAEG,GAAG,CAAC;MAC7B;MACA,OAAO,IAAAV,gCAAyB,EAC5B,IAAI,EACJ,SAAS,EACTC,GACJ,CAAC;IACL;EAAC;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/rx-query.js b/dist/cjs/rx-query.js index a31a9595ebf..16cad634b13 100644 --- a/dist/cjs/rx-query.js +++ b/dist/cjs/rx-query.js @@ -266,7 +266,7 @@ var RxQueryBase = exports.RxQueryBase = /*#__PURE__*/function () { _proto.limit = function limit(_amount) { throw (0, _index.pluginMissing)('query-builder'); }; - (0, _createClass2.default)(RxQueryBase, [{ + return (0, _createClass2.default)(RxQueryBase, [{ key: "$", get: function () { if (!this._$) { @@ -352,7 +352,6 @@ var RxQueryBase = exports.RxQueryBase = /*#__PURE__*/function () { return this; } }]); - return RxQueryBase; }(); function _getDefaultQuery() { return { diff --git a/dist/cjs/rx-query.js.map b/dist/cjs/rx-query.js.map index bd3f92354c5..be96c757a0a 100644 --- a/dist/cjs/rx-query.js.map +++ b/dist/cjs/rx-query.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.js","names":["_rxjs","require","_operators","_index","_rxError","_hooks","_eventReduce","_queryCache","_rxQueryHelper","_rxQuerySingleResult","_queryPlanner","_queryCount","newQueryID","RxQueryBase","exports","op","mangoQuery","collection","other","id","_execOverDatabaseCount","_creationTime","now","_lastEnsureEqual","uncached","refCount$","BehaviorSubject","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","PROMISE_RESOLVE_FALSE","_getDefaultQuery","isFindOneByIdQuery","schema","primaryPath","_proto","prototype","_setResultData","newResultData","RxQuerySingleResult","Map","Array","from","values","newQueryResult","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","count","mode","database","allowSlowCount","newRxError","queryObj","ids","ensureNotFalsy","selector","$in","ret","mustBeQueried","forEach","docData","_docCache","getLatestDocumentDataIfExists","_deleted","doc","getCachedRxDocument","set","push","docs","findDocumentsById","primary","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","firstValueFrom","$","toString","stringObj","sortObject","value","JSON","stringify","hookInput","rxQuery","normalizeMangoQuery","jsonSchema","$eq","index","unshift","runPluginHooks","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","map","update","_updateObj","pluginMissing","where","_queryObj","sort","_params","skip","_amount","limit","_createClass2","default","key","get","_$","results$","pipe","filter","changeEvent","isLocal","startWith","mergeMap","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","distinctUntilChanged","prev","curr","time","useResult","documents","docsMap","slice","merge","reactivity","getReactivityFactory","fromObservable","undefined","normalizedQuery","overwriteGetterForCaching","getQueryMatcher","tunnelQueryCache","getByQuery","createRxQuery","triggerCacheReplacement","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","calculateNewResults","runFullQueryAgain","changed","newResults","areRxDocumentArraysEqual","docsData","resolve","mutateableQuery","queryPlan","getQueryPlan","docIds","docId","docsFromStorage","appendToArray","fromStorageList","queryResult","Object","keys","find","r","isRxQuery","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual,\n appendToArray\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData,\n QueryMatcher,\n RxJsonSchema,\n FilledMangoQuery\n} from './types/index.d.ts';\nimport { calculateNewResults } from './event-reduce.ts';\nimport { triggerCacheReplacement } from './query-cache.ts';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper.ts';\nimport { RxQuerySingleResult } from './rx-query-single-result.ts';\nimport { getQueryPlan } from './query-planner.ts';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n RxQueryResult,\n OrmMethods = {},\n Reactivity = unknown,\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string | string[];\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: RxQuerySingleResult | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly>,\n public collection: RxCollection,\n // used by some plugins\n public other: any = {}\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.documents.length === 0 ? null : useResult.documents[0];\n } else if (this.op === 'findByIds') {\n return useResult.docsMap;\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.documents.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n get $$(): Reactivity {\n const reactivity = this.collection.database.getReactivityFactory();\n return reactivity.fromObservable(\n this.$,\n undefined\n );\n }\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from the storage\n */\n _setResultData(newResultData: RxDocumentData[] | number | Map>): void {\n if (typeof newResultData === 'number') {\n this._result = new RxQuerySingleResult(\n this.collection,\n [],\n newResultData\n );\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const newQueryResult = new RxQuerySingleResult(\n this.collection,\n newResultData,\n newResultData.length\n );\n this._result = newQueryResult;\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n async _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n const result = await this.collection.storageInstance.count(preparedQuery);\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n }\n\n if (this.op === 'findByIds') {\n const ids: string[] = ensureNotFalsy(this.mangoQuery.selector as any)[this.collection.schema.primaryPath].$in;\n const ret = new Map>();\n const mustBeQueried: string[] = [];\n // first try to fill from docCache\n ids.forEach(id => {\n const docData = this.collection._docCache.getLatestDocumentDataIfExists(id);\n if (docData) {\n if (!docData._deleted) {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(id, doc);\n }\n } else {\n mustBeQueried.push(id);\n }\n });\n // everything which was not in docCache must be fetched from the storage\n if (mustBeQueried.length > 0) {\n const docs = await this.collection.storageInstance.findDocumentsById(mustBeQueried, false);\n docs.forEach(docData => {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret as any;\n }\n\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this as any)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n const normalizedQuery = normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n );\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n getQueryMatcher(\n schema,\n normalizedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n )\n };\n (hookInput.mangoQuery.selector as any)._deleted = { $eq: false };\n if (hookInput.mangoQuery.index) {\n hookInput.mangoQuery.index.unshift('_deleted');\n }\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery as any\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n return this\n .exec()\n .then(docs => {\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n });\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection,\n other?: any\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection,\n other\n });\n\n let ret = new RxQueryBase(op, queryObj, collection, other);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n\n /**\n * The RxStorage is defined to always first emit events and then return\n * on bulkWrite() calls. So here we have to use the counter AFTER the execOverDatabase()\n * has been run, not the one from before.\n */\n rxQuery._latestChangeEvent = rxQuery.collection._changeEventBuffer.counter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\nexport function prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n): PreparedQuery {\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensure findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n if (Array.isArray(rxQuery.isFindOneByIdQuery)) {\n let docIds = rxQuery.isFindOneByIdQuery;\n docIds = docIds.filter(docId => {\n // first try to fill from docCache\n const docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (docData) {\n if (!docData._deleted) {\n docs.push(docData);\n }\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n if (docIds.length > 0) {\n const docsFromStorage = await collection.storageInstance.findDocumentsById(docIds, false);\n appendToArray(docs, docsFromStorage);\n }\n } else {\n const docId = rxQuery.isFindOneByIdQuery;\n\n // first try to fill from docCache\n let docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (!docData) {\n // otherwise get from storage\n const fromStorageList = await collection.storageInstance.findDocumentsById([docId], false);\n if (fromStorageList[0]) {\n docData = fromStorageList[0];\n }\n }\n if (docData && !docData._deleted) {\n docs.push(docData);\n }\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string | string[] {\n // must have exactly one operator which must be $eq || $in\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n const value: any = query.selector[primaryPath];\n if (typeof value === 'string') {\n return value;\n } else if (\n Object.keys(value).length === 1 &&\n typeof value.$eq === 'string'\n ) {\n return value.$eq;\n }\n\n // same with $in string arrays\n if (\n Object.keys(value).length === 1 &&\n Array.isArray(value.$eq) &&\n // must only contain strings\n !(value.$eq as any[]).find(r => typeof r !== 'string')\n ) {\n return value.$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isRxQuery(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAMA,IAAAC,UAAA,GAAAD,OAAA;AAQA,IAAAE,MAAA,GAAAF,OAAA;AAWA,IAAAG,QAAA,GAAAH,OAAA;AAGA,IAAAI,MAAA,GAAAJ,OAAA;AAmBA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AACA,IAAAO,cAAA,GAAAP,OAAA;AACA,IAAAQ,oBAAA,GAAAR,OAAA;AACA,IAAAS,aAAA,GAAAT,OAAA;AAEA,IAAIU,WAAW,GAAG,C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AACC,IAAI,CAAC3G,KAAK,CAACtB,QAAQ,CAAC,CAACd,MAAM,KAAK,CAAC,IACxCoC,KAAK,CAACtB,QAAQ,CAACzB,WAAW,CAAC,EAC7B;IACE,IAAMsD,KAAU,GAAGP,KAAK,CAACtB,QAAQ,CAACzB,WAAW,CAAC;IAC9C,IAAI,OAAOsD,KAAK,KAAK,QAAQ,EAAE;MAC3B,OAAOA,KAAK;IAChB,CAAC,MAAM,IACHmG,MAAM,CAACC,IAAI,CAACpG,KAAK,CAAC,CAAC3C,MAAM,KAAK,CAAC,IAC/B,OAAO2C,KAAK,CAACO,GAAG,KAAK,QAAQ,EAC/B;MACE,OAAOP,KAAK,CAACO,GAAG;IACpB;;IAEA;IACA,IACI4F,MAAM,CAACC,IAAI,CAACpG,KAAK,CAAC,CAAC3C,MAAM,KAAK,CAAC,IAC/BJ,KAAK,CAAC8D,OAAO,CAACf,KAAK,CAACO,GAAG,CAAC;IACxB;IACA,CAAEP,KAAK,CAACO,GAAG,CAAW8F,IAAI,CAACC,CAAC,IAAI,OAAOA,CAAC,KAAK,QAAQ,CAAC,EACxD;MACE,OAAOtG,KAAK,CAACO,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIO,SAASgG,SAASA,CAACC,GAAQ,EAAW;EACzC,OAAOA,GAAG,YAAYrL,WAAW;AACrC","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-query.js","names":["_rxjs","require","_operators","_index","_rxError","_hooks","_eventReduce","_queryCache","_rxQueryHelper","_rxQuerySingleResult","_queryPlanner","_queryCount","newQueryID","RxQueryBase","exports","op","mangoQuery","collection","other","id","_execOverDatabaseCount","_creationTime","now","_lastEnsureEqual","uncached","refCount$","BehaviorSubject","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","PROMISE_RESOLVE_FALSE","_getDefaultQuery","isFindOneByIdQuery","schema","primaryPath","_proto","prototype","_setResultData","newResultData","RxQuerySingleResult","Map","Array","from","values","newQueryResult","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","count","mode","database","allowSlowCount","newRxError","queryObj","ids","ensureNotFalsy","selector","$in","ret","mustBeQueried","forEach","docData","_docCache","getLatestDocumentDataIfExists","_deleted","doc","getCachedRxDocument","set","push","docs","findDocumentsById","primary","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","firstValueFrom","$","toString","stringObj","sortObject","value","JSON","stringify","hookInput","rxQuery","normalizeMangoQuery","jsonSchema","$eq","index","unshift","runPluginHooks","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","map","update","_updateObj","pluginMissing","where","_queryObj","sort","_params","skip","_amount","limit","_createClass2","default","key","get","_$","results$","pipe","filter","changeEvent","isLocal","startWith","mergeMap","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","distinctUntilChanged","prev","curr","time","useResult","documents","docsMap","slice","merge","reactivity","getReactivityFactory","fromObservable","undefined","normalizedQuery","overwriteGetterForCaching","getQueryMatcher","tunnelQueryCache","getByQuery","createRxQuery","triggerCacheReplacement","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","calculateNewResults","runFullQueryAgain","changed","newResults","areRxDocumentArraysEqual","docsData","resolve","mutateableQuery","queryPlan","getQueryPlan","docIds","docId","docsFromStorage","appendToArray","fromStorageList","queryResult","Object","keys","find","r","isRxQuery","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual,\n appendToArray\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData,\n QueryMatcher,\n RxJsonSchema,\n FilledMangoQuery\n} from './types/index.d.ts';\nimport { calculateNewResults } from './event-reduce.ts';\nimport { triggerCacheReplacement } from './query-cache.ts';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper.ts';\nimport { RxQuerySingleResult } from './rx-query-single-result.ts';\nimport { getQueryPlan } from './query-planner.ts';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n RxQueryResult,\n OrmMethods = {},\n Reactivity = unknown,\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string | string[];\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: RxQuerySingleResult | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly>,\n public collection: RxCollection,\n // used by some plugins\n public other: any = {}\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.documents.length === 0 ? null : useResult.documents[0];\n } else if (this.op === 'findByIds') {\n return useResult.docsMap;\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.documents.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n get $$(): Reactivity {\n const reactivity = this.collection.database.getReactivityFactory();\n return reactivity.fromObservable(\n this.$,\n undefined\n );\n }\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from the storage\n */\n _setResultData(newResultData: RxDocumentData[] | number | Map>): void {\n if (typeof newResultData === 'number') {\n this._result = new RxQuerySingleResult(\n this.collection,\n [],\n newResultData\n );\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const newQueryResult = new RxQuerySingleResult(\n this.collection,\n newResultData,\n newResultData.length\n );\n this._result = newQueryResult;\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n async _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n const result = await this.collection.storageInstance.count(preparedQuery);\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n }\n\n if (this.op === 'findByIds') {\n const ids: string[] = ensureNotFalsy(this.mangoQuery.selector as any)[this.collection.schema.primaryPath].$in;\n const ret = new Map>();\n const mustBeQueried: string[] = [];\n // first try to fill from docCache\n ids.forEach(id => {\n const docData = this.collection._docCache.getLatestDocumentDataIfExists(id);\n if (docData) {\n if (!docData._deleted) {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(id, doc);\n }\n } else {\n mustBeQueried.push(id);\n }\n });\n // everything which was not in docCache must be fetched from the storage\n if (mustBeQueried.length > 0) {\n const docs = await this.collection.storageInstance.findDocumentsById(mustBeQueried, false);\n docs.forEach(docData => {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret as any;\n }\n\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this as any)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n const normalizedQuery = normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n );\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n getQueryMatcher(\n schema,\n normalizedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n )\n };\n (hookInput.mangoQuery.selector as any)._deleted = { $eq: false };\n if (hookInput.mangoQuery.index) {\n hookInput.mangoQuery.index.unshift('_deleted');\n }\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery as any\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n return this\n .exec()\n .then(docs => {\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n });\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection,\n other?: any\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection,\n other\n });\n\n let ret = new RxQueryBase(op, queryObj, collection, other);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n\n /**\n * The RxStorage is defined to always first emit events and then return\n * on bulkWrite() calls. So here we have to use the counter AFTER the execOverDatabase()\n * has been run, not the one from before.\n */\n rxQuery._latestChangeEvent = rxQuery.collection._changeEventBuffer.counter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\nexport function prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n): PreparedQuery {\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensure findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n if (Array.isArray(rxQuery.isFindOneByIdQuery)) {\n let docIds = rxQuery.isFindOneByIdQuery;\n docIds = docIds.filter(docId => {\n // first try to fill from docCache\n const docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (docData) {\n if (!docData._deleted) {\n docs.push(docData);\n }\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n if (docIds.length > 0) {\n const docsFromStorage = await collection.storageInstance.findDocumentsById(docIds, false);\n appendToArray(docs, docsFromStorage);\n }\n } else {\n const docId = rxQuery.isFindOneByIdQuery;\n\n // first try to fill from docCache\n let docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (!docData) {\n // otherwise get from storage\n const fromStorageList = await collection.storageInstance.findDocumentsById([docId], false);\n if (fromStorageList[0]) {\n docData = fromStorageList[0];\n }\n }\n if (docData && !docData._deleted) {\n docs.push(docData);\n }\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string | string[] {\n // must have exactly one operator which must be $eq || $in\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n const value: any = query.selector[primaryPath];\n if (typeof value === 'string') {\n return value;\n } else if (\n Object.keys(value).length === 1 &&\n typeof value.$eq === 'string'\n ) {\n return value.$eq;\n }\n\n // same with $in string arrays\n if (\n Object.keys(value).length === 1 &&\n Array.isArray(value.$eq) &&\n // must only contain strings\n !(value.$eq as any[]).find(r => typeof r !== 'string')\n ) {\n return value.$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isRxQuery(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAMA,IAAAC,UAAA,GAAAD,OAAA;AAQA,IAAAE,MAAA,GAAAF,OAAA;AAWA,IAAAG,QAAA,GAAAH,OAAA;AAGA,IAAAI,MAAA,GAAAJ,OAAA;AAmBA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AACA,IAAAO,cAAA,GAAAP,OAAA;AACA,IAAAQ,oBAAA,GAAAR,OAAA;AACA,IAAAS,aAAA,GAAAT,OAAA;AAEA,IAAIU,WAAW,GAAG,CAAC;AACnB,IAAMC,UAAU,GAAG,SAAAA,CAAA,EAAoB;EACnC,OAAO,EAAED,WAAW;AACxB,CAAC;AAAC,IAEWE,WAAW,GAAAC,OAAA,CAAAD,WAAA;EASpB;AACJ;AACA;;EAII;;EAKA;;EAMA;AACJ;AACA;AACA;;EAII,SAAAA,YACWE,EAAa,EACbC,UAA2C,EAC3CC,UAAmC;EAC1C;EACOC,KAAU,GAAG,CAAC,CAAC,EACxB;IAAA,KAhCKC,EAAE,GAAWP,UAAU,CAAC,CAAC;IAAA,KAKzBQ,sBAAsB,GAAW,CAAC;IAAA,KAClCC,aAAa,GAAG,IAAAC,UAAG,EAAC,CAAC;IAAA,KAGrBC,gBAAgB,GAAG,CAAC;IAAA,KAEpBC,QAAQ,GAAG,KAAK;IAAA,KAGhBC,SAAS,GAAG,IAAIC,qBAAe,CAAC,IAAI,CAAC;IAAA,KASrC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,CAAC;IACxB;IACA,CAAEP,KAAK,CAACO,GAAG,CAAW8F,IAAI,CAACC,CAAC,IAAI,OAAOA,CAAC,KAAK,QAAQ,CAAC,EACxD;MACE,OAAOtG,KAAK,CAACO,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIO,SAASgG,SAASA,CAACC,GAAQ,EAAW;EACzC,OAAOA,GAAG,YAAYrL,WAAW;AACrC","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/rx-schema.js b/dist/cjs/rx-schema.js index de223f7e11b..a7705873a6e 100644 --- a/dist/cjs/rx-schema.js +++ b/dist/cjs/rx-schema.js @@ -106,7 +106,7 @@ var RxSchema = exports.RxSchema = /*#__PURE__*/function () { _proto.getPrimaryOfDocumentData = function getPrimaryOfDocumentData(documentData) { return (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(this.jsonSchema, documentData); }; - (0, _createClass2.default)(RxSchema, [{ + return (0, _createClass2.default)(RxSchema, [{ key: "version", get: function () { return this.jsonSchema.version; @@ -131,7 +131,6 @@ var RxSchema = exports.RxSchema = /*#__PURE__*/function () { return (0, _index.overwriteGetterForCaching)(this, 'hash', this.hashFunction(JSON.stringify(this.jsonSchema))); } }]); - return RxSchema; }(); function getIndexes(jsonSchema) { return (jsonSchema.indexes || []).map(index => (0, _index.isMaybeReadonlyArray)(index) ? index : [index]); diff --git a/dist/cjs/rx-schema.js.map b/dist/cjs/rx-schema.js.map index 5652ab79a66..b2b5611c95e 100644 --- a/dist/cjs/rx-schema.js.map +++ b/dist/cjs/rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema.js","names":["_index","require","_rxError","_hooks","_rxSchemaHelper","_overwritable","RxSchema","exports","jsonSchema","hashFunction","indexes","getIndexes","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","finalFields","getFinalFields","_proto","prototype","validateChange","dataBefore","dataAfter","forEach","fieldName","deepEqual","newRxError","schema","getDocumentPrototype","proto","pathProperties","getSchemaByObjectPath","Object","keys","key","fullPath","__defineGetter__","get","undefined","ret","defineProperty","get$","enumerable","configurable","get$$","populate","overwriteGetterForCaching","getPrimaryOfDocumentData","documentData","getComposedPrimaryKeyOfDocumentData","_createClass2","default","version","values","entries","properties","filter","v","hasOwnProperty","call","k","JSON","stringify","map","index","isMaybeReadonlyArray","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","runPluginHooks","useJsonSchema","fillWithDefaultSettings","normalizeRxJsonSchema","overwritable","deepFreezeWhenDevMode","isRxSchema","obj","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import {\n overwriteGetterForCaching,\n isMaybeReadonlyArray,\n deepEqual\n} from './plugins/utils/index.ts';\nimport {\n newRxError,\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\n\nimport type {\n DeepMutable,\n DeepReadonly,\n HashFunction,\n MaybeReadonly,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types/index.d.ts';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath,\n normalizeRxJsonSchema\n} from './rx-schema-helper.ts';\nimport { overwritable } from './overwritable.ts';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>,\n public readonly hashFunction: HashFunction\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => Object.prototype.hasOwnProperty.call(v, 'default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n *\n * TODO this should be a pure function that\n * caches the hash in a WeakMap.\n */\n public get hash(): Promise {\n return overwriteGetterForCaching(\n this,\n 'hash',\n this.hashFunction(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto: any = {};\n\n /**\n * On the top level, we know all keys\n * and therefore do not have to create a new Proxy object\n * for each document. Instead we define the getter in the prototype once.\n */\n const pathProperties = getSchemaByObjectPath(\n this.jsonSchema,\n ''\n );\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = key;\n\n // getter - value\n proto.__defineGetter__(\n key,\n function (this: RxDocument) {\n if (!this.get || typeof this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(proto, key + '$', {\n get: function () {\n return this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - reactivity$$\n Object.defineProperty(proto, key + '$$', {\n get: function () {\n return this.get$$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(proto, key + '_', {\n get: function () {\n return this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n });\n\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n hashFunction: HashFunction,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema, hashFunction);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isRxSchema(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAKA,IAAAC,QAAA,GAAAD,OAAA;AAGA,IAAAE,MAAA,GAAAF,OAAA;AAcA,IAAAG,eAAA,GAAAH,OAAA;AAQA,IAAAI,aAAA,GAAAJ,OAAA;AAAiD,IAEpCK,QAAQ,GAAAC,OAAA,CAAAD,QAAA;EAKjB,SAAAA,SACoBE,UAAmD,EACnDC,YAA0B,EAC5C;IAAA,KAFkBD,UAAmD,GAAnDA,UAAmD;IAAA,KACnDC,YAA0B,GAA1BA,YAA0B;IAE1C,IAAI,CAAC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AAC,CACPN,GAAG,CAAC,MAAMI,CAAC,EAAE,CAAC;AACvB;AAEO,SAASG,cAAcA,CAC1B7D,UAA2B,EAC3BC,YAA0B,EAC1B6D,iBAAiB,GAAG,IAAI,EACb;EACX,IAAIA,iBAAiB,EAAE;IACnB,IAAAC,qBAAc,EAAC,mBAAmB,EAAE/D,UAAU,CAAC;EACnD;EAEA,IAAIgE,aAAa,GAAG,IAAAC,uCAAuB,EAACjE,UAAU,CAAC;EACvDgE,aAAa,GAAG,IAAAE,qCAAqB,EAACF,aAAa,CAAC;EACpDG,0BAAY,CAACC,qBAAqB,CAACJ,aAAa,CAAC;EAEjD,IAAM9C,MAAM,GAAG,IAAIpB,QAAQ,CAACkE,aAAa,EAAE/D,YAAY,CAAC;EACxD,IAAA8D,qBAAc,EAAC,gBAAgB,EAAE7C,MAAM,CAAC;EACxC,OAAOA,MAAM;AACjB;AAEO,SAASmD,UAAUA,CAACC,GAAQ,EAAW;EAC1C,OAAOA,GAAG,YAAYxE,QAAQ;AAClC;;AAEA;AACA;AACA;AACA;AACO,SAASyE,mBAAmBA,CAA4CrD,MAAS,EAAkB;EACtG,OAAOA,MAAM;AACjB","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-schema.js","names":["_index","require","_rxError","_hooks","_rxSchemaHelper","_overwritable","RxSchema","exports","jsonSchema","hashFunction","indexes","getIndexes","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","finalFields","getFinalFields","_proto","prototype","validateChange","dataBefore","dataAfter","forEach","fieldName","deepEqual","newRxError","schema","getDocumentPrototype","proto","pathProperties","getSchemaByObjectPath","Object","keys","key","fullPath","__defineGetter__","get","undefined","ret","defineProperty","get$","enumerable","configurable","get$$","populate","overwriteGetterForCaching","getPrimaryOfDocumentData","documentData","getComposedPrimaryKeyOfDocumentData","_createClass2","default","version","values","entries","properties","filter","v","hasOwnProperty","call","k","JSON","stringify","map","index","isMaybeReadonlyArray","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","runPluginHooks","useJsonSchema","fillWithDefaultSettings","normalizeRxJsonSchema","overwritable","deepFreezeWhenDevMode","isRxSchema","obj","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import {\n overwriteGetterForCaching,\n isMaybeReadonlyArray,\n deepEqual\n} from './plugins/utils/index.ts';\nimport {\n newRxError,\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\n\nimport type {\n DeepMutable,\n DeepReadonly,\n HashFunction,\n MaybeReadonly,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types/index.d.ts';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath,\n normalizeRxJsonSchema\n} from './rx-schema-helper.ts';\nimport { overwritable } from './overwritable.ts';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>,\n public readonly hashFunction: HashFunction\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => Object.prototype.hasOwnProperty.call(v, 'default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n *\n * TODO this should be a pure function that\n * caches the hash in a WeakMap.\n */\n public get hash(): Promise {\n return overwriteGetterForCaching(\n this,\n 'hash',\n this.hashFunction(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto: any = {};\n\n /**\n * On the top level, we know all keys\n * and therefore do not have to create a new Proxy object\n * for each document. Instead we define the getter in the prototype once.\n */\n const pathProperties = getSchemaByObjectPath(\n this.jsonSchema,\n ''\n );\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = key;\n\n // getter - value\n proto.__defineGetter__(\n key,\n function (this: RxDocument) {\n if (!this.get || typeof this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(proto, key + '$', {\n get: function () {\n return this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - reactivity$$\n Object.defineProperty(proto, key + '$$', {\n get: function () {\n return this.get$$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(proto, key + '_', {\n get: function () {\n return this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n });\n\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n hashFunction: HashFunction,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema, hashFunction);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isRxSchema(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAKA,IAAAC,QAAA,GAAAD,OAAA;AAGA,IAAAE,MAAA,GAAAF,OAAA;AAcA,IAAAG,eAAA,GAAAH,OAAA;AAQA,IAAAI,aAAA,GAAAJ,OAAA;AAAiD,IAEpCK,QAAQ,GAAAC,OAAA,CAAAD,QAAA;EAKjB,SAAAA,SACoBE,UAAmD,EACnDC,YAA0B,EAC5C;IAAA,KAFkBD,UAAmD,GAAnDA,UAAmD;IAAA,KACnDC,YAA0B,GAA1BA,YAA0B;IAE1C,IAAI,CAACC,OAAO,GAAGC,UAAU,CAAC,IAAI,CAACH,UAAU,CAAC;;IAE1C;IACA,IAAI,CAACI,WAAW,GAAG,IAAAC,2CAA2B,EAAC,IAAI,CAACL,UAAU,CAACM,UAAU,CAAC;IAE1E,IAAI,CAACC,WAAW,GAAG,IAAAC,8BAAc,EAAC,IAAI,CAACR,UAAU,CAAC;EACtD;EAAC,IAAA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AC,uCAAuB,EAACjE,UAAU,CAAC;EACvDgE,aAAa,GAAG,IAAAE,qCAAqB,EAACF,aAAa,CAAC;EACpDG,0BAAY,CAACC,qBAAqB,CAACJ,aAAa,CAAC;EAEjD,IAAM9C,MAAM,GAAG,IAAIpB,QAAQ,CAACkE,aAAa,EAAE/D,YAAY,CAAC;EACxD,IAAA8D,qBAAc,EAAC,gBAAgB,EAAE7C,MAAM,CAAC;EACxC,OAAOA,MAAM;AACjB;AAEO,SAASmD,UAAUA,CAACC,GAAQ,EAAW;EAC1C,OAAOA,GAAG,YAAYxE,QAAQ;AAClC;;AAEA;AACA;AACA;AACA;AACO,SAASyE,mBAAmBA,CAA4CrD,MAAS,EAAkB;EACtG,OAAOA,MAAM;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/doc-cache.js b/dist/esm/doc-cache.js index 690ded16728..0d3f06aad7d 100644 --- a/dist/esm/doc-cache.js +++ b/dist/esm/doc-cache.js @@ -86,14 +86,13 @@ export var DocumentCache = /*#__PURE__*/function () { return cacheItem.last; } }; - _createClass(DocumentCache, [{ + return _createClass(DocumentCache, [{ key: "getCachedRxDocument", get: function () { var fn = getCachedRxDocumentMonad(this); return overwriteGetterForCaching(this, 'getCachedRxDocument', fn); } }]); - return DocumentCache; }(); /** diff --git a/dist/esm/doc-cache.js.map b/dist/esm/doc-cache.js.map index d79456f7e16..9194d40a462 100644 --- a/dist/esm/doc-cache.js.map +++ b/dist/esm/doc-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"doc-cache.js","names":["getFromMapOrCreate","getFromMapOrThrow","getHeightOfRevision","overwriteGetterForCaching","requestIdlePromiseNoQueue","overwritable","getDocumentDataOfRxChangeEvent","DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","byRev","delete","revisionHeight","size","undefined","registerIdleTasks","subscribe","changeEvent","documentId","documentData","last","_proto","prototype","getLatestDocumentData","getLatestDocumentDataIfExists","_createClass","key","fn","getCachedRxDocumentMonad","docCache","deepFreezeWhenDevMode","docData","_rev","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","set","createWeakRefWithFallback","push","registerIdlePromise","then","tasks","length","forEach","doc","register","primary","revision","mapDocumentsDataToCacheDocs","docsData","getCachedRxDocument","documents","i","HAS_WEAK_REF","WeakRef","createWeakRef","createWeakRefFallback","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types/index.d.ts';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision,\n overwriteGetterForCaching,\n requestIdlePromiseNoQueue\n} from './plugins/utils/index.ts';\nimport {\n overwritable\n} from './overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event.ts';\nimport { Observable } from 'rxjs';\n\ndeclare type CacheItem = {\n /**\n * Store the different document states of time\n * based on their revision height.\n * We store WeakRefs so that we can later clean up\n * document states that are no longer needed.\n */\n byRev: Map>>;\n\n /**\n * Store the latest known document state.\n * As long as any state of the document is in the cache,\n * we observe the changestream and update the latestDoc accordingly.\n * This makes it easier to optimize performance on other parts\n * because for each known document we can always get the current state\n * in the storage.\n * Also it makes it possible to call RxDocument.latest() in a non-async way\n * to retrieve the latest document state or to observe$ some property.\n *\n * To not prevent the whole cacheItem from being garbage collected,\n * we store only the document data here, but not the RxDocument.\n */\n last: RxDocumentData;\n};\n\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\ndeclare type FinalizationRegistryValue = {\n docId: string;\n revisionHeight: number;\n};\n\n/**\n * The DocumentCache stores RxDocument objects\n * by their primary key and revision.\n * This is useful on client side applications where\n * it is not known how much memory can be used, so\n * we de-duplicate RxDocument states to save memory.\n * To not fill up the memory with old document states, the DocumentCache\n * only contains weak references to the RxDocuments themself.\n * @link https://caniuse.com/?search=weakref\n */\nexport class DocumentCache {\n public cacheItemByDocId = new Map>();\n\n /**\n * Some JavaScript runtimes like QuickJS,\n * so not have a FinalizationRegistry or WeakRef.\n * Therefore we need a workaround which might waste a lot of memory,\n * but at least works.\n */\n public readonly registry?: FinalizationRegistry = typeof FinalizationRegistry === 'function' ?\n new FinalizationRegistry(docMeta => {\n const docId = docMeta.docId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n cacheItem.byRev.delete(docMeta.revisionHeight);\n if (cacheItem.byRev.size === 0) {\n /**\n * No state of the document is cached anymore,\n * so we can clean up.\n */\n this.cacheItemByDocId.delete(docId);\n }\n }\n }) :\n undefined;\n\n /**\n * Calling registry.register(() has shown to have\n * really bad performance. So we add the cached documents\n * lazily.\n */\n public registerIdlePromise?: Promise;\n public registerIdleTasks: RxDocument[] = [];\n\n constructor(\n public readonly primaryPath: string,\n public readonly changes$: Observable>,\n /**\n * A method that can create a RxDocument by the given document data.\n */\n public documentCreator: (docData: RxDocumentData) => RxDocument\n ) {\n changes$.subscribe(changeEvent => {\n const docId = changeEvent.documentId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n const documentData = getDocumentDataOfRxChangeEvent(changeEvent);\n cacheItem.last = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n * @overwrites itself with the actual function\n * because this is @performance relevant.\n * It is called on each document row for each write and read.\n */\n get getCachedRxDocument(): (docData: RxDocumentData) => RxDocument {\n const fn = getCachedRxDocumentMonad(this);\n return overwriteGetterForCaching(\n this,\n 'getCachedRxDocument',\n fn\n );\n }\n\n /**\n * Throws if not exists\n */\n public getLatestDocumentData(docId: string): RxDocumentData {\n const cacheItem = getFromMapOrThrow(this.cacheItemByDocId, docId);\n return cacheItem.last;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.last;\n }\n }\n}\n\n/**\n * This function is called very very often.\n * This is likely the most important function for RxDB overall performance\n */\nfunction getCachedRxDocumentMonad(\n docCache: DocumentCache\n): (docData: RxDocumentData) => RxDocument {\n const primaryPath = docCache.primaryPath;\n const cacheItemByDocId = docCache.cacheItemByDocId;\n const registry = docCache.registry;\n const deepFreezeWhenDevMode = overwritable.deepFreezeWhenDevMode;\n const documentCreator = docCache.documentCreator;\n const fn: (docData: RxDocumentData) => RxDocument = (docData: RxDocumentData) => {\n const docId: string = (docData as any)[primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const byRev = cacheItem.byRev;\n const cachedRxDocumentWeakRef: WeakRef> | undefined = byRev.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = documentCreator(docData) as RxDocument;\n byRev.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n if (registry) {\n docCache.registerIdleTasks.push(cachedRxDocument);\n if (!docCache.registerIdlePromise) {\n docCache.registerIdlePromise = requestIdlePromiseNoQueue().then(() => {\n docCache.registerIdlePromise = undefined;\n const tasks = docCache.registerIdleTasks;\n if (tasks.length === 0) {\n return;\n }\n docCache.registerIdleTasks = [];\n tasks.forEach(doc => {\n registry.register(doc, {\n docId: doc.primary,\n revisionHeight: getHeightOfRevision(doc.revision)\n });\n });\n });\n }\n }\n }\n return cachedRxDocument;\n };\n return fn;\n}\n\nexport function mapDocumentsDataToCacheDocs(\n docCache: DocumentCache,\n docsData: RxDocumentData[]\n) {\n const getCachedRxDocument = docCache.getCachedRxDocument;\n const documents: RxDocument[] = [];\n for (let i = 0; i < docsData.length; i++) {\n const docData = docsData[i];\n const doc = getCachedRxDocument(docData);\n documents.push(doc);\n }\n return documents;\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n byRev: new Map(),\n last: docData\n };\n}\n\n\n\n\n/**\n * Fallback for JavaScript runtimes that do not support WeakRef.\n * The fallback will keep the items in cache forever,\n * but at least works.\n */\nconst HAS_WEAK_REF = typeof WeakRef === 'function';\nconst createWeakRefWithFallback = HAS_WEAK_REF ? createWeakRef : createWeakRefFallback;\nfunction createWeakRef(obj: T): WeakRef {\n return new WeakRef(obj) as any;\n}\nfunction createWeakRefFallback(obj: T): WeakRef {\n return {\n deref() {\n return obj;\n }\n } as any;\n}\n"],"mappings":";AAKA,SACIA,kBAAkB,EAClBC,iBAAiB,EACjBC,mBAAmB,EACnBC,yBAAyB,EACzBC,yBAAyB,QACtB,0BAA0B;AACjC,SACIC,YAAY,QACT,mBAAmB;AAC1B,SAASC,8BAA8B,QAAQ,sBAAsB;;AA6BrE;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,aAAa;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI;AACJ;AACA;AACA;AACA;;EAII,SAAAA,cACoBC,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA,KAxCKC,gBAAgB,GAAG,IAAIC,GAAG,CAA2C,CAAC;IAAA,KAQ7DC,QAAQ,GAAqD,OAAOC,oBAAoB,KAAK,UAAU,GACnH,IAAIA,oBAAoB,CAA4BC,OAAO,IAAI;MAC3D,IAAMC,KAAK,GAAGD,OAAO,CAACC,KAAK;MAC3B,IAAMC,SAAS,GAAG,IAAI,CAACN,gBAAgB,CAACO,GAAG,CAACF,KAAK,CAAC;MAClD,IAAIC,SAAS,EAAE;QACXA,SAAS,CAACE,KAAK,CAACC,MAAM,CAACL,OAAO,CAACM,cAAc,CAAC;QAC9C,IAAIJ,SAAS,CAACE,KAAK,CAACG,IAAI,KAAK,CAAC,EAAE;UAC5B;AACpB;AACA;AACA;UACoB,IAAI,CAACX,gBAAgB,CAACS,MAAM,CAACJ,KAAK,CAAC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yBAAyB,GAAGgB,YAAY,GAAGE,aAAa,GAAGC,qBAAqB;AACtF,SAASD,aAAaA,CAAmBE,GAAM,EAAc;EACzD,OAAO,IAAIH,OAAO,CAACG,GAAG,CAAC;AAC3B;AACA,SAASD,qBAAqBA,CAAmBC,GAAM,EAAc;EACjE,OAAO;IACHtB,KAAKA,CAAA,EAAG;MACJ,OAAOsB,GAAG;IACd;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"doc-cache.js","names":["getFromMapOrCreate","getFromMapOrThrow","getHeightOfRevision","overwriteGetterForCaching","requestIdlePromiseNoQueue","overwritable","getDocumentDataOfRxChangeEvent","DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","byRev","delete","revisionHeight","size","undefined","registerIdleTasks","subscribe","changeEvent","documentId","documentData","last","_proto","prototype","getLatestDocumentData","getLatestDocumentDataIfExists","_createClass","key","fn","getCachedRxDocumentMonad","docCache","deepFreezeWhenDevMode","docData","_rev","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","set","createWeakRefWithFallback","push","registerIdlePromise","then","tasks","length","forEach","doc","register","primary","revision","mapDocumentsDataToCacheDocs","docsData","getCachedRxDocument","documents","i","HAS_WEAK_REF","WeakRef","createWeakRef","createWeakRefFallback","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types/index.d.ts';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision,\n overwriteGetterForCaching,\n requestIdlePromiseNoQueue\n} from './plugins/utils/index.ts';\nimport {\n overwritable\n} from './overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event.ts';\nimport { Observable } from 'rxjs';\n\ndeclare type CacheItem = {\n /**\n * Store the different document states of time\n * based on their revision height.\n * We store WeakRefs so that we can later clean up\n * document states that are no longer needed.\n */\n byRev: Map>>;\n\n /**\n * Store the latest known document state.\n * As long as any state of the document is in the cache,\n * we observe the changestream and update the latestDoc accordingly.\n * This makes it easier to optimize performance on other parts\n * because for each known document we can always get the current state\n * in the storage.\n * Also it makes it possible to call RxDocument.latest() in a non-async way\n * to retrieve the latest document state or to observe$ some property.\n *\n * To not prevent the whole cacheItem from being garbage collected,\n * we store only the document data here, but not the RxDocument.\n */\n last: RxDocumentData;\n};\n\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\ndeclare type FinalizationRegistryValue = {\n docId: string;\n revisionHeight: number;\n};\n\n/**\n * The DocumentCache stores RxDocument objects\n * by their primary key and revision.\n * This is useful on client side applications where\n * it is not known how much memory can be used, so\n * we de-duplicate RxDocument states to save memory.\n * To not fill up the memory with old document states, the DocumentCache\n * only contains weak references to the RxDocuments themself.\n * @link https://caniuse.com/?search=weakref\n */\nexport class DocumentCache {\n public cacheItemByDocId = new Map>();\n\n /**\n * Some JavaScript runtimes like QuickJS,\n * so not have a FinalizationRegistry or WeakRef.\n * Therefore we need a workaround which might waste a lot of memory,\n * but at least works.\n */\n public readonly registry?: FinalizationRegistry = typeof FinalizationRegistry === 'function' ?\n new FinalizationRegistry(docMeta => {\n const docId = docMeta.docId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n cacheItem.byRev.delete(docMeta.revisionHeight);\n if (cacheItem.byRev.size === 0) {\n /**\n * No state of the document is cached anymore,\n * so we can clean up.\n */\n this.cacheItemByDocId.delete(docId);\n }\n }\n }) :\n undefined;\n\n /**\n * Calling registry.register(() has shown to have\n * really bad performance. So we add the cached documents\n * lazily.\n */\n public registerIdlePromise?: Promise;\n public registerIdleTasks: RxDocument[] = [];\n\n constructor(\n public readonly primaryPath: string,\n public readonly changes$: Observable>,\n /**\n * A method that can create a RxDocument by the given document data.\n */\n public documentCreator: (docData: RxDocumentData) => RxDocument\n ) {\n changes$.subscribe(changeEvent => {\n const docId = changeEvent.documentId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n const documentData = getDocumentDataOfRxChangeEvent(changeEvent);\n cacheItem.last = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n * @overwrites itself with the actual function\n * because this is @performance relevant.\n * It is called on each document row for each write and read.\n */\n get getCachedRxDocument(): (docData: RxDocumentData) => RxDocument {\n const fn = getCachedRxDocumentMonad(this);\n return overwriteGetterForCaching(\n this,\n 'getCachedRxDocument',\n fn\n );\n }\n\n /**\n * Throws if not exists\n */\n public getLatestDocumentData(docId: string): RxDocumentData {\n const cacheItem = getFromMapOrThrow(this.cacheItemByDocId, docId);\n return cacheItem.last;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.last;\n }\n }\n}\n\n/**\n * This function is called very very often.\n * This is likely the most important function for RxDB overall performance\n */\nfunction getCachedRxDocumentMonad(\n docCache: DocumentCache\n): (docData: RxDocumentData) => RxDocument {\n const primaryPath = docCache.primaryPath;\n const cacheItemByDocId = docCache.cacheItemByDocId;\n const registry = docCache.registry;\n const deepFreezeWhenDevMode = overwritable.deepFreezeWhenDevMode;\n const documentCreator = docCache.documentCreator;\n const fn: (docData: RxDocumentData) => RxDocument = (docData: RxDocumentData) => {\n const docId: string = (docData as any)[primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const byRev = cacheItem.byRev;\n const cachedRxDocumentWeakRef: WeakRef> | undefined = byRev.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = documentCreator(docData) as RxDocument;\n byRev.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n if (registry) {\n docCache.registerIdleTasks.push(cachedRxDocument);\n if (!docCache.registerIdlePromise) {\n docCache.registerIdlePromise = requestIdlePromiseNoQueue().then(() => {\n docCache.registerIdlePromise = undefined;\n const tasks = docCache.registerIdleTasks;\n if (tasks.length === 0) {\n return;\n }\n docCache.registerIdleTasks = [];\n tasks.forEach(doc => {\n registry.register(doc, {\n docId: doc.primary,\n revisionHeight: getHeightOfRevision(doc.revision)\n });\n });\n });\n }\n }\n }\n return cachedRxDocument;\n };\n return fn;\n}\n\nexport function mapDocumentsDataToCacheDocs(\n docCache: DocumentCache,\n docsData: RxDocumentData[]\n) {\n const getCachedRxDocument = docCache.getCachedRxDocument;\n const documents: RxDocument[] = [];\n for (let i = 0; i < docsData.length; i++) {\n const docData = docsData[i];\n const doc = getCachedRxDocument(docData);\n documents.push(doc);\n }\n return documents;\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n byRev: new Map(),\n last: docData\n };\n}\n\n\n\n\n/**\n * Fallback for JavaScript runtimes that do not support WeakRef.\n * The fallback will keep the items in cache forever,\n * but at least works.\n */\nconst HAS_WEAK_REF = typeof WeakRef === 'function';\nconst createWeakRefWithFallback = HAS_WEAK_REF ? createWeakRef : createWeakRefFallback;\nfunction createWeakRef(obj: T): WeakRef {\n return new WeakRef(obj) as any;\n}\nfunction createWeakRefFallback(obj: T): WeakRef {\n return {\n deref() {\n return obj;\n }\n } as any;\n}\n"],"mappings":";AAKA,SACIA,kBAAkB,EAClBC,iBAAiB,EACjBC,mBAAmB,EACnBC,yBAAyB,EACzBC,yBAAyB,QACtB,0BAA0B;AACjC,SACIC,YAAY,QACT,mBAAmB;AAC1B,SAASC,8BAA8B,QAAQ,sBAAsB;;AA6BrE;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,aAAa;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI;AACJ;AACA;AACA;AACA;;E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,QAAQ,CAACsB,mBAAmB;EACxD,IAAMC,SAA8C,GAAG,EAAE;EACzD,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,QAAQ,CAACP,MAAM,EAAEU,CAAC,EAAE,EAAE;IACtC,IAAMtB,QAAO,GAAGmB,QAAQ,CAACG,CAAC,CAAC;IAC3B,IAAMR,GAAG,GAAGM,mBAAmB,CAACpB,QAAO,CAAC;IACxCqB,SAAS,CAACb,IAAI,CAACM,GAAG,CAAC;EACvB;EACA,OAAOO,SAAS;AACpB;AAGA,SAASnB,eAAeA,CAAwBF,OAAkC,EAAoC;EAClH,OAAO;IACHrB,KAAK,EAAE,IAAIP,GAAG,CAAC,CAAC;IAChBiB,IAAI,EAAEW;EACV,CAAC;AACL;;AAKA;AACA;AACA;AACA;AACA;AACA,IAAMuB,YAAY,GAAG,OAAOC,OAAO,KAAK,UAAU;AAClD,IAAMjB,yBAAyB,GAAGgB,YAAY,GAAGE,aAAa,GAAGC,qBAAqB;AACtF,SAASD,aAAaA,CAAmBE,GAAM,EAAc;EACzD,OAAO,IAAIH,OAAO,CAACG,GAAG,CAAC;AAC3B;AACA,SAASD,qBAAqBA,CAAmBC,GAAM,EAAc;EACjE,OAAO;IACHtB,KAAKA,CAAA,EAAG;MACJ,OAAOsB,GAAG;IACd;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/local-documents/rx-local-document.js b/dist/esm/plugins/local-documents/rx-local-document.js index 7c235232ba3..1e64546e889 100644 --- a/dist/esm/plugins/local-documents/rx-local-document.js +++ b/dist/esm/plugins/local-documents/rx-local-document.js @@ -10,7 +10,6 @@ import { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from "./ import { isRxDatabase } from "../../rx-database.js"; var RxDocumentParent = createRxDocumentConstructor(); var RxLocalDocumentClass = /*#__PURE__*/function (_RxDocumentParent) { - _inheritsLoose(RxLocalDocumentClass, _RxDocumentParent); function RxLocalDocumentClass(id, jsonData, parent) { var _this2; _this2 = _RxDocumentParent.call(this, null, jsonData) || this; @@ -18,6 +17,7 @@ var RxLocalDocumentClass = /*#__PURE__*/function (_RxDocumentParent) { _this2.parent = parent; return _this2; } + _inheritsLoose(RxLocalDocumentClass, _RxDocumentParent); return RxLocalDocumentClass; }(RxDocumentParent); var RxLocalDocumentPrototype = { diff --git a/dist/esm/plugins/local-documents/rx-local-document.js.map b/dist/esm/plugins/local-documents/rx-local-document.js.map index 5552269b240..0d68dcc8244 100644 --- a/dist/esm/plugins/local-documents/rx-local-document.js.map +++ b/dist/esm/plugins/local-documents/rx-local-document.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-local-document.js","names":["distinctUntilChanged","filter","map","shareReplay","startWith","overwritable","getDocumentDataOfRxChangeEvent","basePrototype","createRxDocumentConstructor","newRxError","newRxTypeError","writeSingle","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","getFromMapOrThrow","getProperty","RXJS_SHARE_REPLAY_DEFAULTS","getLocalDocStateByParent","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","isRxDatabase","RxDocumentParent","RxLocalDocumentClass","_RxDocumentParent","_inheritsLoose","id","jsonData","parent","_this2","call","RxLocalDocumentPrototype","isLocal","allAttachments$","document","primaryPath","primary","$","_this","state","pipe","changeEvent","documentId","docCache","getLatestDocumentData","prev","curr","_rev","docData","getCachedRxDocument","$$","db","getRxDatabaseFromLocalDocument","reactivity","getReactivityFactory","fromObservable","getLatest","_data","deleted$$","deleted$","deleted","latestDocData","get","objPath","undefined","valueObj","deepFreezeWhenDevMode","get$","isDevMode","includes","localDocument","data","get$$","incrementalModify","mutationFunction","incrementalWriteQueue","addWrite","then","result","incrementalPatch","patch","Object","entries","forEach","k","v","_saveData","newData","oldData","storageInstance","bulkWrite","previous","res","docResult","success","error","remove","writeData","_deleted","_meta","_attachments","writeResult","INIT_DONE","_init","docBaseProto","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","setPrototypeOf","prototype","doc","database"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs';\nimport { overwritable } from '../../overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from '../../rx-change-event.ts';\nimport {\n basePrototype,\n createRxDocumentConstructor\n} from '../../rx-document.ts';\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error.ts';\nimport { writeSingle } from '../../rx-storage-helper.ts';\nimport type {\n LocalDocumentModifyFunction,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types/index.d.ts';\nimport {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromMapOrThrow,\n getProperty,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from './local-documents-helper.ts';\nimport { isRxDatabase } from '../../rx-database.ts';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $(): Observable> {\n const _this: RxLocalDocumentClass = this as any;\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n return _this.parent.$.pipe(\n filter(changeEvent => changeEvent.documentId === this.primary),\n filter(changeEvent => changeEvent.isLocal),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(state.docCache.getLatestDocumentData(this.primary)),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n map(docData => state.docCache.getCachedRxDocument(docData)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n ) as Observable;\n },\n get $$(): any {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.$,\n _this.getLatest()._data\n );\n },\n get deleted$$() {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.deleted$,\n _this.getLatest().deleted\n );\n },\n getLatest(this: RxLocalDocument): RxLocalDocument {\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n const latestDocData = state.docCache.getLatestDocumentData(this.primary);\n return state.docCache.getCachedRxDocument(latestDocData) as any;\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = getProperty(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (overwritable.isDevMode()) {\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n }\n return this.$\n .pipe(\n map(localDocument => localDocument._data),\n map(data => getProperty(data, objPath)),\n distinctUntilChanged()\n );\n },\n get$$(this: RxDocument, objPath: string) {\n const db = getRxDatabaseFromLocalDocument(this as any);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n this.get$(objPath),\n this.getLatest().get(objPath)\n );\n },\n async incrementalModify(\n this: RxLocalDocument,\n mutationFunction: LocalDocumentModifyFunction\n ) {\n const state = await getLocalDocStateByParent(this.parent);\n\n return state.incrementalWriteQueue.addWrite(\n this._data as any,\n async (docData) => {\n docData.data = await mutationFunction(docData.data, this);\n return docData;\n }\n ).then(result => state.docCache.getCachedRxDocument(result as any));\n },\n incrementalPatch(patch: Partial) {\n return this.incrementalModify((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._data;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[0];\n if (!docResult) {\n throw res.error[0];\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: RxLocalDocument): Promise> {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this._data.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then((writeResult) => state.docCache.getCachedRxDocument(writeResult) as any);\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n data: RxDocumentData>,\n parent: any\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(data.id, data, parent);\n Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype);\n newDoc.prototype = RxLocalDocumentPrototype;\n return newDoc as any;\n}\n\n\nexport function getRxDatabaseFromLocalDocument(doc: RxLocalDocument | RxLocalDocumentClass) {\n const parent = doc.parent;\n if (isRxDatabase(parent)) {\n return parent;\n } else {\n return (parent as RxCollection).database;\n }\n}\n"],"mappings":";AACA,SACIA,oBAAoB,EACpBC,MAAM,EACNC,GAAG,EACHC,WAAW,EACXC,SAAS,QACN,MAAM;AACb,SAASC,YAAY,QAAQ,uBAAuB;AACpD,SAASC,8BAA8B,QAAQ,0BAA0B;AACzE,SACIC,aAAa,EACbC,2BAA2B,QACxB,sBAAsB;AAC7B,SACIC,UAAU,EACVC,cAAc,QACX,mBAAmB;AAC1B,SAASC,WAAW,QAAQ,4BAA4B;AAWxD,SACIC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,EACjBC,WAAW,EACXC,0BAA0B,QACvB,8BAA8B;AACrC,SAASC,wBAAwB,EAAEC,kCAAkC,QAAQ,6BAA6B;AAC1G,SAASC,YAAY,QAAQ,sBAAsB;AAEnD,IAAMC,gBAAgB,GAAGb,2BAA2B,CAAC,CAAQ;AAAC,IAExDc,oBAAoB,0BAAAC,iBAAA;EAAAC,cAAA,CAAAF,oBAAA,EAAAC,iBAAA;EACtB,SAAAD,qBACoBG,EAAU,EAC1BC,QAAiB,EACDC,MAAiC,EACnD;IAAA,IAAAC,MAAA;IACEA,MAAA,GAAAL,iBAAA,CAAAM,IAAA,OAAM,IAAI,EAAEH,QAAQ,CAAC;IAACE,MAAA,CAJNH,E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AAI5B,CAAS,IAAK,MAAM;IACxC,MAAM1E,UAAU,CAAC,KAAK,EAAE;MACpBuG,YAAY,EAAE7B;IAClB,CAAC,CAAC;EACN,CAAC;EACD,CACI,UAAU,EACV,QAAQ,EACR,eAAe,EACf,eAAe,EACf,gBAAgB,CACnB,CAACD,OAAO,CAAEC,CAAS,IAAKrD,wBAAwB,CAACqD,CAAC,CAAC,GAAG4B,cAAc,CAAC5B,CAAC,CAAC,CAAC;AAC7E,CAAC;AAID,OAAO,SAAS8B,qBAAqBA,CACjC3C,IAAkD,EAClD3C,MAAW,EACa;EACxB2E,KAAK,CAAC,CAAC;EACP,IAAMY,MAAM,GAAG,IAAI5F,oBAAoB,CAACgD,IAAI,CAAC7C,EAAE,EAAE6C,IAAI,EAAE3C,MAAM,CAAC;EAC9DqD,MAAM,CAACmC,cAAc,CAACD,MAAM,EAAEpF,wBAAwB,CAAC;EACvDoF,MAAM,CAACE,SAAS,GAAGtF,wBAAwB;EAC3C,OAAOoF,MAAM;AACjB;AAGA,OAAO,SAAS/D,8BAA8BA,CAACkE,GAAgD,EAAE;EAC7F,IAAM1F,MAAM,GAAG0F,GAAG,CAAC1F,MAAM;EACzB,IAAIP,YAAY,CAACO,MAAM,CAAC,EAAE;IACtB,OAAOA,MAAM;EACjB,CAAC,MAAM;IACH,OAAQA,MAAM,CAAkB2F,QAAQ;EAC5C;AACJ","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-local-document.js","names":["distinctUntilChanged","filter","map","shareReplay","startWith","overwritable","getDocumentDataOfRxChangeEvent","basePrototype","createRxDocumentConstructor","newRxError","newRxTypeError","writeSingle","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","getFromMapOrThrow","getProperty","RXJS_SHARE_REPLAY_DEFAULTS","getLocalDocStateByParent","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","isRxDatabase","RxDocumentParent","RxLocalDocumentClass","_RxDocumentParent","id","jsonData","parent","_this2","call","_inheritsLoose","RxLocalDocumentPrototype","isLocal","allAttachments$","document","primaryPath","primary","$","_this","state","pipe","changeEvent","documentId","docCache","getLatestDocumentData","prev","curr","_rev","docData","getCachedRxDocument","$$","db","getRxDatabaseFromLocalDocument","reactivity","getReactivityFactory","fromObservable","getLatest","_data","deleted$$","deleted$","deleted","latestDocData","get","objPath","undefined","valueObj","deepFreezeWhenDevMode","get$","isDevMode","includes","localDocument","data","get$$","incrementalModify","mutationFunction","incrementalWriteQueue","addWrite","then","result","incrementalPatch","patch","Object","entries","forEach","k","v","_saveData","newData","oldData","storageInstance","bulkWrite","previous","res","docResult","success","error","remove","writeData","_deleted","_meta","_attachments","writeResult","INIT_DONE","_init","docBaseProto","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","setPrototypeOf","prototype","doc","database"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs';\nimport { overwritable } from '../../overwritable.ts';\nimport { getDocumentDataOfRxChangeEvent } from '../../rx-change-event.ts';\nimport {\n basePrototype,\n createRxDocumentConstructor\n} from '../../rx-document.ts';\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error.ts';\nimport { writeSingle } from '../../rx-storage-helper.ts';\nimport type {\n LocalDocumentModifyFunction,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types/index.d.ts';\nimport {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromMapOrThrow,\n getProperty,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from './local-documents-helper.ts';\nimport { isRxDatabase } from '../../rx-database.ts';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $(): Observable> {\n const _this: RxLocalDocumentClass = this as any;\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n return _this.parent.$.pipe(\n filter(changeEvent => changeEvent.documentId === this.primary),\n filter(changeEvent => changeEvent.isLocal),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(state.docCache.getLatestDocumentData(this.primary)),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n map(docData => state.docCache.getCachedRxDocument(docData)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n ) as Observable;\n },\n get $$(): any {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.$,\n _this.getLatest()._data\n );\n },\n get deleted$$() {\n const _this: RxLocalDocumentClass = this as any;\n const db = getRxDatabaseFromLocalDocument(_this);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n _this.deleted$,\n _this.getLatest().deleted\n );\n },\n getLatest(this: RxLocalDocument): RxLocalDocument {\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n const latestDocData = state.docCache.getLatestDocumentData(this.primary);\n return state.docCache.getCachedRxDocument(latestDocData) as any;\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = getProperty(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (overwritable.isDevMode()) {\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n }\n return this.$\n .pipe(\n map(localDocument => localDocument._data),\n map(data => getProperty(data, objPath)),\n distinctUntilChanged()\n );\n },\n get$$(this: RxDocument, objPath: string) {\n const db = getRxDatabaseFromLocalDocument(this as any);\n const reactivity = db.getReactivityFactory();\n return reactivity.fromObservable(\n this.get$(objPath),\n this.getLatest().get(objPath)\n );\n },\n async incrementalModify(\n this: RxLocalDocument,\n mutationFunction: LocalDocumentModifyFunction\n ) {\n const state = await getLocalDocStateByParent(this.parent);\n\n return state.incrementalWriteQueue.addWrite(\n this._data as any,\n async (docData) => {\n docData.data = await mutationFunction(docData.data, this);\n return docData;\n }\n ).then(result => state.docCache.getCachedRxDocument(result as any));\n },\n incrementalPatch(patch: Partial) {\n return this.incrementalModify((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._data;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[0];\n if (!docResult) {\n throw res.error[0];\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: RxLocalDocument): Promise> {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this._data.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then((writeResult) => state.docCache.getCachedRxDocument(writeResult) as any);\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n data: RxDocumentData>,\n parent: any\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(data.id, data, parent);\n Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype);\n newDoc.prototype = RxLocalDocumentPrototype;\n return newDoc as any;\n}\n\n\nexport function getRxDatabaseFromLocalDocument(doc: RxLocalDocument | RxLocalDocumentClass) {\n const parent = doc.parent;\n if (isRxDatabase(parent)) {\n return parent;\n } else {\n return (parent as RxCollection).database;\n }\n}\n"],"mappings":";AACA,SACIA,oBAAoB,EACpBC,MAAM,EACNC,GAAG,EACHC,WAAW,EACXC,SAAS,QACN,MAAM;AACb,SAASC,YAAY,QAAQ,uBAAuB;AACpD,SAASC,8BAA8B,QAAQ,0BAA0B;AACzE,SACIC,aAAa,EACbC,2BAA2B,QACxB,sBAAsB;AAC7B,SACIC,UAAU,EACVC,cAAc,QACX,mBAAmB;AAC1B,SAASC,WAAW,QAAQ,4BAA4B;AAWxD,SACIC,SAAS,EACTC,kBA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AC,EAAE;IACtB,OAAOA,MAAM;EACjB,CAAC,MAAM;IACH,OAAQA,MAAM,CAAkB4F,QAAQ;EAC5C;AACJ","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/replication-couchdb/index.js b/dist/esm/plugins/replication-couchdb/index.js index 22aab80f400..83f8d9ee930 100644 --- a/dist/esm/plugins/replication-couchdb/index.js +++ b/dist/esm/plugins/replication-couchdb/index.js @@ -12,7 +12,6 @@ import { awaitRetry } from "../replication/replication-helper.js"; export * from "./couchdb-helper.js"; export * from "./couchdb-types.js"; export var RxCouchDBReplicationState = /*#__PURE__*/function (_RxReplicationState) { - _inheritsLoose(RxCouchDBReplicationState, _RxReplicationState); function RxCouchDBReplicationState(url, fetch, replicationIdentifier, collection, pull, push, live = true, retryTime = 1000 * 5, autoStart = true) { var _this; _this = _RxReplicationState.call(this, replicationIdentifier, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; @@ -27,6 +26,7 @@ export var RxCouchDBReplicationState = /*#__PURE__*/function (_RxReplicationStat _this.autoStart = autoStart; return _this; } + _inheritsLoose(RxCouchDBReplicationState, _RxReplicationState); return RxCouchDBReplicationState; }(RxReplicationState); export function replicateCouchDB(options) { diff --git a/dist/esm/plugins/replication-couchdb/index.js.map b/dist/esm/plugins/replication-couchdb/index.js.map index 64746c3d1c1..163ea0554ab 100644 --- a/dist/esm/plugins/replication-couchdb/index.js.map +++ b/dist/esm/plugins/replication-couchdb/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ensureNotFalsy","errorToPlainJson","flatClone","getFromMapOrThrow","now","promiseWait","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","newRxError","Subject","couchDBDocToRxDocData","mergeUrlQueryParams","couchSwapPrimaryToId","getDefaultFetch","awaitRetry","RxCouchDBReplicationState","_RxReplicationState","_inheritsLoose","url","fetch","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","call","replicateCouchDB","options","conflictHandler","primaryPath","schema","endsWith","args","name","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","response","replicationState","jsonResponse","json","results","documents","map","row","doc","checkpoint","last_seq","modifier","stream$","asObservable","initialCheckpoint","replicationPrimitivesPush","rows","conflicts","pushRowsById","Map","forEach","id","newDocumentState","set","docsByIdResponse","method","headers","body","JSON","stringify","keys","deleted","docsByIdRows","nonConflictRows","remoteRevById","Promise","all","key","realMasterState","pushRow","conflictHandlerResult","assumedMasterState","isEqual","_rev","docs","docId","sendDoc","has","responseJson","conflictAgainIds","writeResultRow","isConflict","error","ok","length","getConflictDocsUrl","conflictResponse","conflictResponseJson","conflictAgainRow","startBefore","start","bind","lastRequestStartTime","isStopped","err","subjects","next"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * This plugin can be used to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrThrow,\n now,\n promiseWait\n} from '../../plugins/utils/index.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n CouchdbChangesResult,\n CouchBulkDocResultRow,\n CouchAllDocsResponse,\n RxConflictHandler\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDB\n} from './couchdb-types.ts';\nimport {\n couchDBDocToRxDocData,\n mergeUrlQueryParams,\n couchSwapPrimaryToId,\n getDefaultFetch\n} from './couchdb-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './couchdb-helper.ts';\nexport * from './couchdb-types.ts';\n\nexport class RxCouchDBReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateCouchDB(\n options: SyncOptionsCouchDB\n) {\n const collection = options.collection;\n const conflictHandler: RxConflictHandler = collection.conflictHandler;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const primaryPath = options.collection.schema.primaryPath;\n\n if (!options.url.endsWith('/')) {\n throw newRxError('RC_COUCHDB_1', {\n args: {\n collection: options.collection.name,\n url: options.url\n }\n });\n }\n\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: CouchdbChangesResult = await response.json();\n if (!jsonResponse.results) {\n throw newRxError('RC_COUCHDB_2', {\n args: { jsonResponse }\n });\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable(),\n initialCheckpoint: options.pull.initialCheckpoint\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const conflicts: WithDeleted[] = [];\n const pushRowsById = new Map>();\n rows.forEach(row => {\n const id = (row.newDocumentState as any)[primaryPath];\n pushRowsById.set(id, row);\n });\n\n /**\n * First get the current master state from the remote\n * to check for conflicts\n */\n const docsByIdResponse = await replicationState.fetch(\n options.url + '_all_docs?' + mergeUrlQueryParams({}),\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify({\n keys: rows.map(row => (row.newDocumentState as any)[primaryPath]),\n include_docs: true,\n deleted: 'ok'\n })\n }\n );\n const docsByIdRows: CouchAllDocsResponse = await docsByIdResponse.json();\n const nonConflictRows: typeof rows = [];\n const remoteRevById = new Map();\n await Promise.all(\n docsByIdRows.rows.map(async (row) => {\n if (!row.doc) {\n nonConflictRows.push(getFromMapOrThrow(pushRowsById, row.key));\n return;\n }\n const realMasterState: WithDeleted = couchDBDocToRxDocData(primaryPath, row.doc);\n const pushRow = getFromMapOrThrow(pushRowsById, row.id);\n const conflictHandlerResult = await conflictHandler({\n realMasterState,\n newDocumentState: pushRow.assumedMasterState\n }, 'couchdb-push-1');\n if (conflictHandlerResult.isEqual) {\n remoteRevById.set(row.id, row.doc._rev);\n nonConflictRows.push(pushRow);\n } else {\n conflicts.push(realMasterState);\n }\n })\n );\n\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: nonConflictRows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n const sendDoc = flatClone(row.newDocumentState);\n if (remoteRevById.has(docId)) {\n (sendDoc as any)._rev = getFromMapOrThrow(remoteRevById, docId);\n }\n return couchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: CouchBulkDocResultRow[] = await response.json();\n\n // get conflicting writes\n const conflictAgainIds: string[] = [];\n responseJson.forEach(writeResultRow => {\n const isConflict = writeResultRow.error === 'conflict';\n if (!writeResultRow.ok && !isConflict) {\n throw newRxError('SNH', { args: { writeResultRow } });\n }\n if (isConflict) {\n conflictAgainIds.push(writeResultRow.id);\n }\n });\n\n if (conflictAgainIds.length === 0) {\n return conflicts;\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflictAgainIds)\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: CouchAllDocsResponse = await conflictResponse.json();\n conflictResponseJson.rows.forEach(conflictAgainRow => {\n conflicts.push(couchDBDocToRxDocData(collection.schema.primaryPath, conflictAgainRow.doc));\n });\n\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier,\n initialCheckpoint: options.push.initialCheckpoint\n };\n }\n\n const replicationState = new RxCouchDBReplicationState(\n options.url,\n options.fetch ? options.fetch : getDefaultFetch(),\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n let lastRequestStartTime = now();\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: CouchdbChangesResult;\n try {\n lastRequestStartTime = now();\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err: any) {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n args: { url },\n error: errorToPlainJson(err)\n })\n );\n\n if (lastRequestStartTime < (now() - replicationState.retryTime)) {\n /**\n * Last request start was long ago,\n * so we directly retry.\n * This mostly happens on timeouts\n * which are normal behavior for long polling requests.\n */\n await promiseWait(0);\n } else {\n // await next tick here otherwise we could go in to a 100% CPU blocking cycle.\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA;AACA;AACA;AACA,SACIA,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,iBAAiB,EACjBC,GAAG,EACHC,WAAW,QACR,8BAA8B;AAErC,SAASC,wBAAwB,QAAQ,6BAA6B;AAYtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;AAChC,SACIC,WAAW,EACXC,UAAU,QAEP,gBAAgB;AAEvB,SAASC,OAAO,QAAQ,MAAM;AAM9B,SACIC,qBAAqB,EACrBC,mBAAmB,EACnBC,oBAAoB,EACpBC,eAAe,QACZ,qBAAqB;AAC5B,SAASC,UAAU,QAAQ,sCAAsC;AAEjE,cAAc,qBAAqB;AACnC,cAAc,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AE;gBAAEjB,GAAG,EAAHA;cAAI,CAAC;cACbqF,KAAK,EAAExG,gBAAgB,CAACoH,GAAG;YAC/B,CAAC,CACL,CAAC;YAED,IAAIF,oBAAoB,GAAI/G,GAAG,CAAC,CAAC,GAAGkD,gBAAgB,CAAC3B,SAAU,EAAE;cAC7D;AAC5B;AACA;AACA;AACA;AACA;cAC4B,MAAMtB,WAAW,CAAC,CAAC,CAAC;YACxB,CAAC,MAAM;cACH;cACA,MAAMW,UAAU,CACZO,UAAU,EACV+B,gBAAgB,CAAC3B,SACrB,CAAC;YACL;YACA;UACJ;UACA,IAAM+B,SAAmC,GAAGH,YAAY,CAACE,OAAO,CAC3DE,GAAG,CAACC,GAAG,IAAIhD,qBAAqB,CAACW,UAAU,CAACY,MAAM,CAACD,WAAW,EAAElC,cAAc,CAAC4D,GAAG,CAACC,GAAG,CAAC,CAAC,CAAC;UAC9Fb,KAAK,GAAGO,YAAY,CAACQ,QAAQ;UAE7BvB,WAAW,CAAC+E,IAAI,CAAC;YACb7D,SAAS;YACTI,UAAU,EAAE;cACRb,QAAQ,EAAEM,YAAY,CAACQ;YAC3B;UACJ,CAAC,CAAC;QACN;MACJ,CAAC,EAAE,CAAC;MACJ,OAAOiD,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEAxG,4BAA4B,CAACwB,OAAO,CAACO,iBAAiB,EAAEe,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["ensureNotFalsy","errorToPlainJson","flatClone","getFromMapOrThrow","now","promiseWait","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","newRxError","Subject","couchDBDocToRxDocData","mergeUrlQueryParams","couchSwapPrimaryToId","getDefaultFetch","awaitRetry","RxCouchDBReplicationState","_RxReplicationState","url","fetch","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","call","_inheritsLoose","replicateCouchDB","options","conflictHandler","primaryPath","schema","endsWith","args","name","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","response","replicationState","jsonResponse","json","results","documents","map","row","doc","checkpoint","last_seq","modifier","stream$","asObservable","initialCheckpoint","replicationPrimitivesPush","rows","conflicts","pushRowsById","Map","forEach","id","newDocumentState","set","docsByIdResponse","method","headers","body","JSON","stringify","keys","deleted","docsByIdRows","nonConflictRows","remoteRevById","Promise","all","key","realMasterState","pushRow","conflictHandlerResult","assumedMasterState","isEqual","_rev","docs","docId","sendDoc","has","responseJson","conflictAgainIds","writeResultRow","isConflict","error","ok","length","getConflictDocsUrl","conflictResponse","conflictResponseJson","conflictAgainRow","startBefore","start","bind","lastRequestStartTime","isStopped","err","subjects","next"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * This plugin can be used to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrThrow,\n now,\n promiseWait\n} from '../../plugins/utils/index.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n CouchdbChangesResult,\n CouchBulkDocResultRow,\n CouchAllDocsResponse,\n RxConflictHandler\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDB\n} from './couchdb-types.ts';\nimport {\n couchDBDocToRxDocData,\n mergeUrlQueryParams,\n couchSwapPrimaryToId,\n getDefaultFetch\n} from './couchdb-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './couchdb-helper.ts';\nexport * from './couchdb-types.ts';\n\nexport class RxCouchDBReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateCouchDB(\n options: SyncOptionsCouchDB\n) {\n const collection = options.collection;\n const conflictHandler: RxConflictHandler = collection.conflictHandler;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const primaryPath = options.collection.schema.primaryPath;\n\n if (!options.url.endsWith('/')) {\n throw newRxError('RC_COUCHDB_1', {\n args: {\n collection: options.collection.name,\n url: options.url\n }\n });\n }\n\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: CouchdbChangesResult = await response.json();\n if (!jsonResponse.results) {\n throw newRxError('RC_COUCHDB_2', {\n args: { jsonResponse }\n });\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable(),\n initialCheckpoint: options.pull.initialCheckpoint\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const conflicts: WithDeleted[] = [];\n const pushRowsById = new Map>();\n rows.forEach(row => {\n const id = (row.newDocumentState as any)[primaryPath];\n pushRowsById.set(id, row);\n });\n\n /**\n * First get the current master state from the remote\n * to check for conflicts\n */\n const docsByIdResponse = await replicationState.fetch(\n options.url + '_all_docs?' + mergeUrlQueryParams({}),\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify({\n keys: rows.map(row => (row.newDocumentState as any)[primaryPath]),\n include_docs: true,\n deleted: 'ok'\n })\n }\n );\n const docsByIdRows: CouchAllDocsResponse = await docsByIdResponse.json();\n const nonConflictRows: typeof rows = [];\n const remoteRevById = new Map();\n await Promise.all(\n docsByIdRows.rows.map(async (row) => {\n if (!row.doc) {\n nonConflictRows.push(getFromMapOrThrow(pushRowsById, row.key));\n return;\n }\n const realMasterState: WithDeleted = couchDBDocToRxDocData(primaryPath, row.doc);\n const pushRow = getFromMapOrThrow(pushRowsById, row.id);\n const conflictHandlerResult = await conflictHandler({\n realMasterState,\n newDocumentState: pushRow.assumedMasterState\n }, 'couchdb-push-1');\n if (conflictHandlerResult.isEqual) {\n remoteRevById.set(row.id, row.doc._rev);\n nonConflictRows.push(pushRow);\n } else {\n conflicts.push(realMasterState);\n }\n })\n );\n\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: nonConflictRows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n const sendDoc = flatClone(row.newDocumentState);\n if (remoteRevById.has(docId)) {\n (sendDoc as any)._rev = getFromMapOrThrow(remoteRevById, docId);\n }\n return couchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: CouchBulkDocResultRow[] = await response.json();\n\n // get conflicting writes\n const conflictAgainIds: string[] = [];\n responseJson.forEach(writeResultRow => {\n const isConflict = writeResultRow.error === 'conflict';\n if (!writeResultRow.ok && !isConflict) {\n throw newRxError('SNH', { args: { writeResultRow } });\n }\n if (isConflict) {\n conflictAgainIds.push(writeResultRow.id);\n }\n });\n\n if (conflictAgainIds.length === 0) {\n return conflicts;\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflictAgainIds)\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: CouchAllDocsResponse = await conflictResponse.json();\n conflictResponseJson.rows.forEach(conflictAgainRow => {\n conflicts.push(couchDBDocToRxDocData(collection.schema.primaryPath, conflictAgainRow.doc));\n });\n\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier,\n initialCheckpoint: options.push.initialCheckpoint\n };\n }\n\n const replicationState = new RxCouchDBReplicationState(\n options.url,\n options.fetch ? options.fetch : getDefaultFetch(),\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n let lastRequestStartTime = now();\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: CouchdbChangesResult;\n try {\n lastRequestStartTime = now();\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err: any) {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n args: { url },\n error: errorToPlainJson(err)\n })\n );\n\n if (lastRequestStartTime < (now() - replicationState.retryTime)) {\n /**\n * Last request start was long ago,\n * so we directly retry.\n * This mostly happens on timeouts\n * which are normal behavior for long polling requests.\n */\n await promiseWait(0);\n } else {\n // await next tick here otherwise we could go in to a 100% CPU blocking cycle.\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA;AACA;AACA;AACA,SACIA,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,iBAAiB,EACjBC,GAAG,EACHC,WAAW,QACR,8BAA8B;AAErC,SAASC,wBAAwB,QAAQ,6BAA6B;AAYtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;AAChC,SACIC,WAAW,EACXC,UAAU,QAEP,gBAAgB;AAEvB,SAASC,OAAO,QAAQ,MAAM;AAM9B,SACIC,qBAAqB,EACrBC,mBAAmB,EACnBC,oBAAoB,EACpBC,eAAe,QACZ,qBAAqB;AAC5B,SAASC,UAAU,QAAQ,sCAAsC;AAEjE,cAAc,qBAAqB;AACnC,cAAc,o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GAAG,EAAHA;cAAI,CAAC;cACbsF,KAAK,EAAExG,gBAAgB,CAACoH,GAAG;YAC/B,CAAC,CACL,CAAC;YAED,IAAIF,oBAAoB,GAAI/G,GAAG,CAAC,CAAC,GAAGkD,gBAAgB,CAAC5B,SAAU,EAAE;cAC7D;AAC5B;AACA;AACA;AACA;AACA;cAC4B,MAAMrB,WAAW,CAAC,CAAC,CAAC;YACxB,CAAC,MAAM;cACH;cACA,MAAMW,UAAU,CACZM,UAAU,EACVgC,gBAAgB,CAAC5B,SACrB,CAAC;YACL;YACA;UACJ;UACA,IAAMgC,SAAmC,GAAGH,YAAY,CAACE,OAAO,CAC3DE,GAAG,CAACC,GAAG,IAAIhD,qBAAqB,CAACU,UAAU,CAACa,MAAM,CAACD,WAAW,EAAElC,cAAc,CAAC4D,GAAG,CAACC,GAAG,CAAC,CAAC,CAAC;UAC9Fb,KAAK,GAAGO,YAAY,CAACQ,QAAQ;UAE7BvB,WAAW,CAAC+E,IAAI,CAAC;YACb7D,SAAS;YACTI,UAAU,EAAE;cACRb,QAAQ,EAAEM,YAAY,CAACQ;YAC3B;UACJ,CAAC,CAAC;QACN;MACJ,CAAC,EAAE,CAAC;MACJ,OAAOiD,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEAxG,4BAA4B,CAACwB,OAAO,CAACO,iBAAiB,EAAEe,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/replication-firestore/index.js b/dist/esm/plugins/replication-firestore/index.js index 78052111c27..b7c5834fa59 100644 --- a/dist/esm/plugins/replication-firestore/index.js +++ b/dist/esm/plugins/replication-firestore/index.js @@ -9,7 +9,6 @@ import { firestoreRowToDocData, getContentByIds, isoStringToServerTimestamp, ser export * from "./firestore-helper.js"; export * from "./firestore-types.js"; export var RxFirestoreReplicationState = /*#__PURE__*/function (_RxReplicationState) { - _inheritsLoose(RxFirestoreReplicationState, _RxReplicationState); function RxFirestoreReplicationState(firestore, replicationIdentifierHash, collection, pull, push, live = true, retryTime = 1000 * 5, autoStart = true) { var _this; _this = _RxReplicationState.call(this, replicationIdentifierHash, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; @@ -23,6 +22,7 @@ export var RxFirestoreReplicationState = /*#__PURE__*/function (_RxReplicationSt _this.autoStart = autoStart; return _this; } + _inheritsLoose(RxFirestoreReplicationState, _RxReplicationState); return RxFirestoreReplicationState; }(RxReplicationState); export function replicateFirestore(options) { diff --git a/dist/esm/plugins/replication-firestore/index.js.map b/dist/esm/plugins/replication-firestore/index.js.map index bf64299a7e7..3c209d61716 100644 --- a/dist/esm/plugins/replication-firestore/index.js.map +++ b/dist/esm/plugins/replication-firestore/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["appendToArray","asyncFilter","ensureNotFalsy","errorToPlainJson","flatClone","lastOfArray","toArray","doc","query","where","orderBy","limit","getDocs","onSnapshot","runTransaction","writeBatch","serverTimestamp","waitForPendingWrites","documentId","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","getSchemaByObjectPath","newRxError","Subject","firestoreRowToDocData","getContentByIds","isoStringToServerTimestamp","serverTimestampToIsoString","stripPrimaryKey","stripServerTimestampField","RxFirestoreReplicationState","_RxReplicationState","_inheritsLoose","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","_this","call","replicateFirestore","options","pullStream$","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","jsonSchema","includes","field","pullFilters","filter","undefined","pullQuery","handler","lastPulledCheckpoint","batchSize","newerQuery","sameTimeQuery","lastServerTimestamp","id","mustsReRun","useDocs","database","_tx","newerQueryResult","sameTimeQueryResult","Promise","all","metadata","hasPendingWrites","docs","missingAmount","length","additionalDocs","slice","x","checkpoint","documents","lastDoc","map","row","newCheckpoint","data","ret","modifier","stream$","asObservable","replicationPrimitivesPush","pushFilter","rows","newDocumentState","writeRowsById","docIds","docId","conflicts","getQuery","ids","docsInDbResult","docsInDbById","forEach","docDataInDb","batch","hasWrite","Object","entries","writeRow","docInDb","assumedMasterState","conflictHandler","realMasterState","isEqual","docRef","writeDocData","set","update","commit","replicationState","replicationIdentifier","startBefore","start","bind","cancelBefore","cancel","lastChangeQuery","unsubscribe","_querySnapshot","reSync","error","subjects","next"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["import {\n appendToArray,\n asyncFilter,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n lastOfArray,\n toArray\n} from '../../plugins/utils/index.ts';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types.ts';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n getContentByIds,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper.ts';\n\nexport * from './firestore-helper.ts';\nexport * from './firestore-types.ts';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateFirestore(\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(collection.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: collection.schema.jsonSchema\n });\n }\n\n const pullFilters = options.pull?.filter !== undefined\n ? toArray(options.pull.filter)\n : [];\n\n const pullQuery = query(options.firestore.collection, ...pullFilters);\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType | undefined,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(pullQuery,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(pullQuery,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(pullQuery,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additionalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n appendToArray(useDocs, additionalDocs);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint ?? null,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n const pushFilter = options.push?.filter;\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n if (pushFilter !== undefined) {\n rows = await asyncFilter(rows, (row) => pushFilter(row.newDocumentState));\n }\n\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n\n const getQuery = (ids: string[]) => {\n return getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', ids)\n )\n );\n };\n\n const docsInDbResult = await getContentByIds(docIds, getQuery);\n\n const docsInDbById: ById = {};\n docsInDbResult.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n pullQuery,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error: errorToPlainJson(error) })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,aAAa,EACbC,WAAW,EACXC,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,WAAW,EACXC,OAAO,QACJ,8BAA8B;AAErC,SACIC,GAAG,EACHC,KAAK,EACLC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,UAAU,EACVC,cAAc,EACdC,UAAU,EACVC,eAAe,EAEfC,oBAAoB,EACpBC,UAAU,QACP,oBAAoB;AAE3B,SAASC,wBAAwB,QAAQ,6BAA6B;AAQtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;A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oD,SAAS,EACTlD,OAAO,CAACwC,oBAAoB,EAAE,MAAM,CAAC,EACrCvC,KAAK,CAAC,CAAC,CACX,CAAC;MACD,IAAMyH,WAAW,GAAGvH,UAAU,CAC1BsH,eAAe,EACdE,cAAc,IAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBT,gBAAgB,CAACU,MAAM,CAAC,CAAC;MAC7B,CAAC,EACAC,KAAK,IAAK;QACPX,gBAAgB,CAACY,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChCjH,UAAU,CAAC,WAAW,EAAE;UAAE+G,KAAK,EAAEpI,gBAAgB,CAACoI,KAAK;QAAE,CAAC,CAC9D,CAAC;MACL,CACJ,CAAC;MACDX,gBAAgB,CAACM,MAAM,GAAG,MAAM;QAC5BE,WAAW,CAAC,CAAC;QACb,OAAOH,YAAY,CAAC,CAAC;MACzB,CAAC;MACD,OAAOH,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEAzG,4BAA4B,CAACyB,OAAO,CAACG,iBAAiB,EAAE2E,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["appendToArray","asyncFilter","ensureNotFalsy","errorToPlainJson","flatClone","lastOfArray","toArray","doc","query","where","orderBy","limit","getDocs","onSnapshot","runTransaction","writeBatch","serverTimestamp","waitForPendingWrites","documentId","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","getSchemaByObjectPath","newRxError","Subject","firestoreRowToDocData","getContentByIds","isoStringToServerTimestamp","serverTimestampToIsoString","stripPrimaryKey","stripServerTimestampField","RxFirestoreReplicationState","_RxReplicationState","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","_this","call","_inheritsLoose","replicateFirestore","options","pullStream$","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","jsonSchema","includes","field","pullFilters","filter","undefined","pullQuery","handler","lastPulledCheckpoint","batchSize","newerQuery","sameTimeQuery","lastServerTimestamp","id","mustsReRun","useDocs","database","_tx","newerQueryResult","sameTimeQueryResult","Promise","all","metadata","hasPendingWrites","docs","missingAmount","length","additionalDocs","slice","x","checkpoint","documents","lastDoc","map","row","newCheckpoint","data","ret","modifier","stream$","asObservable","replicationPrimitivesPush","pushFilter","rows","newDocumentState","writeRowsById","docIds","docId","conflicts","getQuery","ids","docsInDbResult","docsInDbById","forEach","docDataInDb","batch","hasWrite","Object","entries","writeRow","docInDb","assumedMasterState","conflictHandler","realMasterState","isEqual","docRef","writeDocData","set","update","commit","replicationState","replicationIdentifier","startBefore","start","bind","cancelBefore","cancel","lastChangeQuery","unsubscribe","_querySnapshot","reSync","error","subjects","next"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["import {\n appendToArray,\n asyncFilter,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n lastOfArray,\n toArray\n} from '../../plugins/utils/index.ts';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types.ts';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n getContentByIds,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper.ts';\n\nexport * from './firestore-helper.ts';\nexport * from './firestore-types.ts';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateFirestore(\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(collection.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: collection.schema.jsonSchema\n });\n }\n\n const pullFilters = options.pull?.filter !== undefined\n ? toArray(options.pull.filter)\n : [];\n\n const pullQuery = query(options.firestore.collection, ...pullFilters);\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType | undefined,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(pullQuery,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(pullQuery,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(pullQuery,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additionalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n appendToArray(useDocs, additionalDocs);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint ?? null,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n const pushFilter = options.push?.filter;\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n if (pushFilter !== undefined) {\n rows = await asyncFilter(rows, (row) => pushFilter(row.newDocumentState));\n }\n\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n\n const getQuery = (ids: string[]) => {\n return getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', ids)\n )\n );\n };\n\n const docsInDbResult = await getContentByIds(docIds, getQuery);\n\n const docsInDbById: ById = {};\n docsInDbResult.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n pullQuery,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error: errorToPlainJson(error) })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,aAAa,EACbC,WAAW,EACXC,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,WAAW,EACXC,OAAO,QACJ,8BAA8B;AAErC,SACIC,GAAG,EACHC,K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EAAE;IAC9B,IAAMyF,WAAW,GAAGF,gBAAgB,CAACG,KAAK,CAACC,IAAI,CAACJ,gBAAgB,CAAC;IACjE,IAAMK,YAAY,GAAGL,gBAAgB,CAACM,MAAM,CAACF,IAAI,CAACJ,gBAAgB,CAAC;IACnEA,gBAAgB,CAACG,KAAK,GAAG,MAAM;MAC3B,IAAMI,eAAe,GAAG3H,KAAK,CACzBoD,SAAS,EACTlD,OAAO,CAACwC,oBAAoB,EAAE,MAAM,CAAC,EACrCvC,KAAK,CAAC,CAAC,CACX,CAAC;MACD,IAAMyH,WAAW,GAAGvH,UAAU,CAC1BsH,eAAe,EACdE,cAAc,IAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBT,gBAAgB,CAACU,MAAM,CAAC,CAAC;MAC7B,CAAC,EACAC,KAAK,IAAK;QACPX,gBAAgB,CAACY,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChCjH,UAAU,CAAC,WAAW,EAAE;UAAE+G,KAAK,EAAEpI,gBAAgB,CAACoI,KAAK;QAAE,CAAC,CAC9D,CAAC;MACL,CACJ,CAAC;MACDX,gBAAgB,CAACM,MAAM,GAAG,MAAM;QAC5BE,WAAW,CAAC,CAAC;QACb,OAAOH,YAAY,CAAC,CAAC;MACzB,CAAC;MACD,OAAOH,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEAzG,4BAA4B,CAACyB,OAAO,CAACG,iBAAiB,EAAE2E,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/replication-graphql/index.js b/dist/esm/plugins/replication-graphql/index.js index be41306b2b8..56d6c7bfac0 100644 --- a/dist/esm/plugins/replication-graphql/index.js +++ b/dist/esm/plugins/replication-graphql/index.js @@ -11,7 +11,6 @@ import { addRxPlugin } from "../../index.js"; import { removeGraphQLWebSocketRef, getGraphQLWebSocket } from "./graphql-websocket.js"; import { Subject } from 'rxjs'; export var RxGraphQLReplicationState = /*#__PURE__*/function (_RxReplicationState) { - _inheritsLoose(RxGraphQLReplicationState, _RxReplicationState); function RxGraphQLReplicationState(url, clientState, replicationIdentifier, collection, deletedField, pull, push, live, retryTime, autoStart, customFetch) { var _this; _this = _RxReplicationState.call(this, replicationIdentifier, collection, deletedField, pull, push, live, retryTime, autoStart) || this; @@ -28,6 +27,7 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function (_RxReplicationStat _this.customFetch = customFetch; return _this; } + _inheritsLoose(RxGraphQLReplicationState, _RxReplicationState); var _proto = RxGraphQLReplicationState.prototype; _proto.setHeaders = function setHeaders(headers) { this.clientState.headers = flatClone(headers); diff --git a/dist/esm/plugins/replication-graphql/index.js.map b/dist/esm/plugins/replication-graphql/index.js.map index 826de7aad31..a7637e04775 100644 --- a/dist/esm/plugins/replication-graphql/index.js.map +++ b/dist/esm/plugins/replication-graphql/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","getProperty","graphQLRequest","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","removeGraphQLWebSocketRef","getGraphQLWebSocket","Subject","RxGraphQLReplicationState","_RxReplicationState","_inheritsLoose","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","call","_proto","prototype","setHeaders","headers","setCredentials","credentials","queryParams","fetch","http","replicateGraphQL","waitForLeadership","mutateableClientState","pullStream$","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","Object","keys","data","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n flatClone,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState,\n ById\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: ById): void {\n this.clientState.headers = flatClone(headers);\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper.ts';\nexport * from './graphql-schema-from-rx-schema.ts';\nexport * from './query-builder-from-rx-schema.ts';\nexport * from './graphql-websocket.ts';\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA,SACIA,cAAc,EACdC,SAAS,EACTC,WAAW,QACR,8BAA8B;AAErC,SACIC,cAAc,IAAdA,eAAc,QACX,aAAa;AAEpB,SAASC,wBAAwB,QAAQ,6BAA6B;AAYtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;AACh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ensureNotFalsy","flatClone","getProperty","graphQLRequest","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","removeGraphQLWebSocketRef","getGraphQLWebSocket","Subject","RxGraphQLReplicationState","_RxReplicationState","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","call","_inheritsLoose","_proto","prototype","setHeaders","headers","setCredentials","credentials","queryParams","fetch","http","replicateGraphQL","waitForLeadership","mutateableClientState","pullStream$","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","Object","keys","data","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n flatClone,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState,\n ById\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: ById): void {\n this.clientState.headers = flatClone(headers);\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper.ts';\nexport * from './graphql-schema-from-rx-schema.ts';\nexport * from './query-builder-from-rx-schema.ts';\nexport * from './graphql-websocket.ts';\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA,SACIA,cAAc,EACdC,SAAS,EACTC,WAAW,QACR,8BAA8B;AAErC,SACIC,cAAc,IAAdA,eAAc,QACX,aAAa;AAEpB,SAASC,wBAAwB,QAAQ,6BAA6B;AAYtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;AAChC,SACIC,WAAW,QAGR,gBAAgB;AAEvB,SACIC,yBAAyB,EACzBC,mBAAmB,QAChB,wBAAwB;AAC/B,SAASC,OAAO,QAAQ,MAAM;AAK9B,WAAaC,yBAAyB,0BAAAC,mBAAA;EAClC,SAAAD,0BACoBE,GAAqB,EACrBC,WAA4C,EAC5CC,qBAA6B,EAC7BC,UAAmC,EACnCC,YAAoB,EACpBC,IAAwD,EACxDC,IAAwC,EACxCC,IAAc,EACvBC,SAAkB,EAClBC,SAAmB,EACVC,WAAgD,EAClE;IAAA,IAAAC,KAAA;IACEA,KAAA,GAAAZ,mBAAA,CAAAa,IAAA,OACIV,qBAAqB,EACrBC,UAAU,EACVC,YAAY,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;IAACE,KAAA,CArBcX,GAAqB,GAArBA,GAAqB;IAAAW,KAAA,CACrBV,WAA4C,GAA5CA,WAA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AAC;QAC1B;MACJ,CAAC,CAAC;IACV;IACA,OAAOd,WAAW,CAAC,CAAC;EACxB,CAAC;EAED,IAAMe,YAAY,GAAGnC,uBAAuB,CAACoC,MAAM,CAACd,IAAI,CAACtB,uBAAuB,CAAC;EACjFA,uBAAuB,CAACoC,MAAM,GAAG,MAAM;IACnC,IAAI,CAACpC,uBAAuB,CAACqC,SAAS,CAAC,CAAC,EAAE;MACtC9C,WAAW,CAAC2C,QAAQ,CAAC,CAAC;MACtB,IAAIjB,aAAa,EAAE;QACfzD,yBAAyB,CAACR,cAAc,CAACa,GAAG,CAACqD,EAAE,CAAC,CAAC;MACrD;IACJ;IACA,OAAOiB,YAAY,CAAC,CAAC;EACzB,CAAC;EAED7E,4BAA4B,CAAC+B,iBAAiB,EAAEW,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC;AAEA,cAAc,aAAa;AAC3B,cAAc,oCAAoC;AAClD,cAAc,mCAAmC;AACjD,cAAc,wBAAwB","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/replication-nats/index.js b/dist/esm/plugins/replication-nats/index.js index a0d1c3789ef..dce8fa43318 100644 --- a/dist/esm/plugins/replication-nats/index.js +++ b/dist/esm/plugins/replication-nats/index.js @@ -10,7 +10,6 @@ import { awaitRetry } from "../replication/replication-helper.js"; export * from "./nats-types.js"; export * from "./nats-helper.js"; export var RxNatsReplicationState = /*#__PURE__*/function (_RxReplicationState) { - _inheritsLoose(RxNatsReplicationState, _RxReplicationState); function RxNatsReplicationState(replicationIdentifier, collection, pull, push, live = true, retryTime = 1000 * 5, autoStart = true) { var _this; _this = _RxReplicationState.call(this, replicationIdentifier, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; @@ -23,6 +22,7 @@ export var RxNatsReplicationState = /*#__PURE__*/function (_RxReplicationState) _this.autoStart = autoStart; return _this; } + _inheritsLoose(RxNatsReplicationState, _RxReplicationState); return RxNatsReplicationState; }(RxReplicationState); export function replicateNats(options) { diff --git a/dist/esm/plugins/replication-nats/index.js.map b/dist/esm/plugins/replication-nats/index.js.map index 693210cb951..86ff036ec1e 100644 --- a/dist/esm/plugins/replication-nats/index.js.map +++ b/dist/esm/plugins/replication-nats/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ensureNotFalsy","errorToPlainJson","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","newRxError","Subject","connect","DeliverPolicy","JSONCodec","ReplayPolicy","getNatsServerDocumentState","awaitRetry","RxNatsReplicationState","_RxReplicationState","_inheritsLoose","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","call","replicateNats","options","waitForLeadership","primaryPath","schema","jc","connectionStatePromise","nc","connection","jetstreamClient","jetstream","jsm","jetstreamManager","streams","add","name","streamName","subjects","subjectPrefix","natsStream","get","pullStream$","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","cn","newCheckpoint","sequence","consumer","getConsumer","opt_start_seq","deliver_policy","LastPerSubject","replay_policy","Instant","fetchedMessages","fetch","max_messages","signal","close","useMessages","m","json","seq","ack","documents","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","conflicts","Promise","all","map","writeRow","docId","newDocumentState","remoteDocState","err","message","includes","assumedMasterState","conflictHandler","realMasterState","isEqual","pushDone","publish","encode","expect","lastSubjectSequence","undefined","newServerState","replicationState","error","next","document","startBefore","start","bind","cancelBefore","cancel","lastSeq","lastDocState","getMessage","last_by_subj","newMessages","consume","docData"],"sources":["../../../../src/plugins/replication-nats/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n errorToPlainJson\n} from '../../plugins/utils/index.ts';\n\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n NatsCheckpointType,\n NatsSyncOptions\n} from './nats-types.ts';\nimport { connect, DeliverPolicy, JSONCodec, ReplayPolicy } from 'nats';\nimport { getNatsServerDocumentState } from './nats-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './nats-types.ts';\nexport * from './nats-helper.ts';\n\n\nexport class RxNatsReplicationState extends RxReplicationState {\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\n\n\nexport function replicateNats(\n options: NatsSyncOptions\n): RxNatsReplicationState {\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n const primaryPath = collection.schema.primaryPath;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const jc = JSONCodec();\n\n\n const connectionStatePromise = (async () => {\n const nc = await connect(options.connection);\n const jetstreamClient = nc.jetstream();\n const jsm = await nc.jetstreamManager();\n await jsm.streams.add({\n name: options.streamName, subjects: [\n options.subjectPrefix + '.*'\n ]\n });\n const natsStream = await jetstreamClient.streams.get(options.streamName);\n return {\n nc,\n jetstreamClient,\n jsm,\n natsStream\n };\n })();\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: NatsCheckpointType | undefined,\n batchSize: number\n ) {\n const cn = await connectionStatePromise;\n const newCheckpoint: NatsCheckpointType = {\n sequence: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0\n };\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n deliver_policy: DeliverPolicy.LastPerSubject,\n replay_policy: ReplayPolicy.Instant\n });\n\n const fetchedMessages = await consumer.fetch({\n max_messages: batchSize\n });\n await (fetchedMessages as any).signal;\n await fetchedMessages.close();\n\n const useMessages: WithDeleted[] = [];\n for await (const m of fetchedMessages) {\n useMessages.push(m.json());\n newCheckpoint.sequence = m.seq;\n m.ack();\n }\n return {\n documents: useMessages,\n checkpoint: newCheckpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const cn = await connectionStatePromise;\n const conflicts: WithDeleted[] = [];\n await Promise.all(\n rows.map(async (writeRow) => {\n const docId = (writeRow.newDocumentState as any)[primaryPath];\n\n /**\n * first get the current state of the documents from the server\n * so that we have the sequence number for conflict detection.\n */\n let remoteDocState;\n try {\n remoteDocState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n } catch (err: Error | any) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n if (\n remoteDocState &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: remoteDocState.json(),\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(remoteDocState.json());\n } else {\n // no conflict (yet)\n let pushDone = false;\n while (!pushDone) {\n try {\n await cn.jetstreamClient.publish(\n options.subjectPrefix + '.' + docId,\n jc.encode(writeRow.newDocumentState),\n {\n expect: remoteDocState ? {\n streamName: options.streamName,\n lastSubjectSequence: remoteDocState.seq\n } : undefined\n }\n );\n pushDone = true;\n } catch (err: Error | any) {\n if (err.message.includes('wrong last sequence')) {\n // A write happened while we are doing our write -> handle conflict\n const newServerState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n conflicts.push(ensureNotFalsy(newServerState).json());\n pushDone = true;\n } else {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n document: writeRow.newDocumentState,\n error: errorToPlainJson(err)\n })\n );\n\n // -> retry after wait\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n }\n }\n }\n })\n );\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxNatsReplicationState(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = async () => {\n const cn = await connectionStatePromise;\n\n /**\n * First get the last sequence so that we can\n * laster only fetch 'newer' messages.\n */\n let lastSeq = 0;\n try {\n const lastDocState = await cn.natsStream.getMessage({\n last_by_subj: options.subjectPrefix + '.*'\n });\n lastSeq = lastDocState.seq;\n } catch (err: any | Error) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastSeq\n });\n const newMessages = await consumer.consume();\n (async () => {\n for await (const m of newMessages) {\n const docData: WithDeleted = m.json();\n pullStream$.next({\n documents: [docData],\n checkpoint: {\n sequence: m.seq\n }\n });\n m.ack();\n }\n })();\n replicationState.cancel = () => {\n newMessages.close();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,cAAc,EACdC,gBAAgB,QACb,8BAA8B;AAGrC,SAASC,wBAAwB,QAAQ,6BAA6B;AAQtE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,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["ensureNotFalsy","errorToPlainJson","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","newRxError","Subject","connect","DeliverPolicy","JSONCodec","ReplayPolicy","getNatsServerDocumentState","awaitRetry","RxNatsReplicationState","_RxReplicationState","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","_this","call","_inheritsLoose","replicateNats","options","waitForLeadership","primaryPath","schema","jc","connectionStatePromise","nc","connection","jetstreamClient","jetstream","jsm","jetstreamManager","streams","add","name","streamName","subjects","subjectPrefix","natsStream","get","pullStream$","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","cn","newCheckpoint","sequence","consumer","getConsumer","opt_start_seq","deliver_policy","LastPerSubject","replay_policy","Instant","fetchedMessages","fetch","max_messages","signal","close","useMessages","m","json","seq","ack","documents","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","conflicts","Promise","all","map","writeRow","docId","newDocumentState","remoteDocState","err","message","includes","assumedMasterState","conflictHandler","realMasterState","isEqual","pushDone","publish","encode","expect","lastSubjectSequence","undefined","newServerState","replicationState","error","next","document","startBefore","start","bind","cancelBefore","cancel","lastSeq","lastDocState","getMessage","last_by_subj","newMessages","consume","docData"],"sources":["../../../../src/plugins/replication-nats/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n errorToPlainJson\n} from '../../plugins/utils/index.ts';\n\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index.ts';\n\nimport { Subject } from 'rxjs';\nimport type {\n NatsCheckpointType,\n NatsSyncOptions\n} from './nats-types.ts';\nimport { connect, DeliverPolicy, JSONCodec, ReplayPolicy } from 'nats';\nimport { getNatsServerDocumentState } from './nats-helper.ts';\nimport { awaitRetry } from '../replication/replication-helper.ts';\n\nexport * from './nats-types.ts';\nexport * from './nats-helper.ts';\n\n\nexport class RxNatsReplicationState extends RxReplicationState {\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\n\n\nexport function replicateNats(\n options: NatsSyncOptions\n): RxNatsReplicationState {\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n const primaryPath = collection.schema.primaryPath;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const jc = JSONCodec();\n\n\n const connectionStatePromise = (async () => {\n const nc = await connect(options.connection);\n const jetstreamClient = nc.jetstream();\n const jsm = await nc.jetstreamManager();\n await jsm.streams.add({\n name: options.streamName, subjects: [\n options.subjectPrefix + '.*'\n ]\n });\n const natsStream = await jetstreamClient.streams.get(options.streamName);\n return {\n nc,\n jetstreamClient,\n jsm,\n natsStream\n };\n })();\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: NatsCheckpointType | undefined,\n batchSize: number\n ) {\n const cn = await connectionStatePromise;\n const newCheckpoint: NatsCheckpointType = {\n sequence: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0\n };\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n deliver_policy: DeliverPolicy.LastPerSubject,\n replay_policy: ReplayPolicy.Instant\n });\n\n const fetchedMessages = await consumer.fetch({\n max_messages: batchSize\n });\n await (fetchedMessages as any).signal;\n await fetchedMessages.close();\n\n const useMessages: WithDeleted[] = [];\n for await (const m of fetchedMessages) {\n useMessages.push(m.json());\n newCheckpoint.sequence = m.seq;\n m.ack();\n }\n return {\n documents: useMessages,\n checkpoint: newCheckpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const cn = await connectionStatePromise;\n const conflicts: WithDeleted[] = [];\n await Promise.all(\n rows.map(async (writeRow) => {\n const docId = (writeRow.newDocumentState as any)[primaryPath];\n\n /**\n * first get the current state of the documents from the server\n * so that we have the sequence number for conflict detection.\n */\n let remoteDocState;\n try {\n remoteDocState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n } catch (err: Error | any) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n if (\n remoteDocState &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: remoteDocState.json(),\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(remoteDocState.json());\n } else {\n // no conflict (yet)\n let pushDone = false;\n while (!pushDone) {\n try {\n await cn.jetstreamClient.publish(\n options.subjectPrefix + '.' + docId,\n jc.encode(writeRow.newDocumentState),\n {\n expect: remoteDocState ? {\n streamName: options.streamName,\n lastSubjectSequence: remoteDocState.seq\n } : undefined\n }\n );\n pushDone = true;\n } catch (err: Error | any) {\n if (err.message.includes('wrong last sequence')) {\n // A write happened while we are doing our write -> handle conflict\n const newServerState = await getNatsServerDocumentState(\n cn.natsStream,\n options.subjectPrefix,\n docId\n );\n conflicts.push(ensureNotFalsy(newServerState).json());\n pushDone = true;\n } else {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', {\n document: writeRow.newDocumentState,\n error: errorToPlainJson(err)\n })\n );\n\n // -> retry after wait\n await awaitRetry(\n collection,\n replicationState.retryTime\n );\n }\n }\n }\n }\n })\n );\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxNatsReplicationState(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = async () => {\n const cn = await connectionStatePromise;\n\n /**\n * First get the last sequence so that we can\n * laster only fetch 'newer' messages.\n */\n let lastSeq = 0;\n try {\n const lastDocState = await cn.natsStream.getMessage({\n last_by_subj: options.subjectPrefix + '.*'\n });\n lastSeq = lastDocState.seq;\n } catch (err: any | Error) {\n if (!err.message.includes('no message found')) {\n throw err;\n }\n }\n\n const consumer = await cn.natsStream.getConsumer({\n opt_start_seq: lastSeq\n });\n const newMessages = await consumer.consume();\n (async () => {\n for await (const m of newMessages) {\n const docData: WithDeleted = m.json();\n pullStream$.next({\n documents: [docData],\n checkpoint: {\n sequence: m.seq\n }\n });\n m.ack();\n }\n })();\n replicationState.cancel = () => {\n newMessages.close();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,cAAc,EACdC,gBAAgB,QACb,8BAA8B;AAGrC,SAASC,wBAAwB,QAAQ,6BAA6B;AAQtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;AAChC,SACIC,WAAW,EACXC,UAAU,QAEP,gBAAgB;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x-collection.js index 8fa8c1e8920..99c9e9aefc8 100644 --- a/dist/esm/rx-collection.js +++ b/dist/esm/rx-collection.js @@ -517,7 +517,7 @@ export var RxCollectionBase = /*#__PURE__*/function () { await this.destroy(); await removeCollectionStorages(this.database.storage, this.database.internalStore, this.database.token, this.database.name, this.name, this.database.password, this.database.hashFunction); }; - _createClass(RxCollectionBase, [{ + return _createClass(RxCollectionBase, [{ key: "insert$", get: function () { return this.$.pipe(filter(cE => cE.operation === 'INSERT')); @@ -547,7 +547,6 @@ export var RxCollectionBase = /*#__PURE__*/function () { return this; } }]); - return RxCollectionBase; }(); /** diff --git a/dist/esm/rx-collection.js.map b/dist/esm/rx-collection.js.map index 4bca1346301..2e96f6642a8 100644 --- a/dist/esm/rx-collection.js.map +++ b/dist/esm/rx-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection.js","names":["filter","map","mergeMap","ucfirst","flatClone","promiseSeries","pluginMissing","ensureNotFalsy","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","fillObjectDataBeforeInsert","createRxCollectionStorageInstance","removeCollectionStorages","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocumentCache","mapDocumentsDataToCacheDocs","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createNewRxDocument","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","throwIfIsStorageWriteError","defaultConflictHandler","IncrementalWriteQueue","beforeDocumentUpdateWrite","overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","checkpoint$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","jsonSchema","primaryPath","newData","oldData","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","changeEventBulk","collectionName","events","checkpoint","cE","isLocal","docData","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","cleanup","_minimumDeletedTime","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","useDocs","useDocData","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","successIds","d","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","query","findOne","isArray","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","password","hashFunction","_createClass","operation","collection","colProto","Object","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","isDevMode","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration-schema');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration-schema');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n const mangoQuery: MangoQuery = {\n selector: {\n [this.schema.primaryPath]: {\n $in: ids.slice(0)\n }\n } as any\n };\n const query = createRxQuery('findByIds', mangoQuery, this as any);\n return query as any;\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";AAAA,SACIA,MAAM,EACNC,GAAG,EACHC,QAAQ,QACL,MAAM;AAEb,SACIC,OAAO,EACPC,SAAS,EACTC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,QACjB,0BAA0B;AACjC,SACIC,0BAA0B,EAC1BC,iCAAiC,EACjCC,wBAAwB,QACrB,2BAA2B;AAClC,SACIC,aAAa,EACbC,gBAAgB,QACb,eAAe;AACtB,SACIC,UAAU,EACVC,cAAc,QACX,eAAe;AAItB,SACIC,aAAa,EAAEC,2BAA2B,QACvC,gBAAgB;AACvB,SAEIC,gBAAgB,EAChBC,6BAA6B,QAC1B,kBAAkB;AACzB,SAEIC,uBAAuB,QACpB,0BAA0B;AACjC,SACIC,mBAAmB,EACnBC,cAAc,QACX,YAAY;AA0CnB,SACIC,mBAAmB,QAChB,kCAAkC;AACzC,SACIC,yBAAyB,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OAAO,EAAE;UACL5N,IAAI;UACJC,MAAM;UACNU,eAAe;UACfR,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtByM,cAAc;UACdxM;QACJ;MACJ,CAAC,CAAC;MACF,OAAO4L,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAICwB,KAAK,CAAC9F,GAAG,IAAI;MACV,OAAOpH,eAAe,CAAC+K,KAAK,CAAC,CAAC,CACzBvH,IAAI,CAAC,MAAMwB,OAAO,CAACmI,MAAM,CAAC/F,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASgG,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlO,gBAAgB;AAC1C","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["filter","map","mergeMap","ucfirst","flatClone","promiseSeries","pluginMissing","ensureNotFalsy","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","fillObjectDataBeforeInsert","createRxCollectionStorageInstance","removeCollectionStorages","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocumentCache","mapDocumentsDataToCacheDocs","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createNewRxDocument","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","throwIfIsStorageWriteError","defaultConflictHandler","IncrementalWriteQueue","beforeDocumentUpdateWrite","overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","checkpoint$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","jsonSchema","primaryPath","newData","oldData","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","changeEventBulk","collectionName","events","checkpoint","cE","isLocal","docData","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","cleanup","_minimumDeletedTime","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","useDocs","useDocData","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","successIds","d","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","query","findOne","isArray","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","password","hashFunction","_createClass","operation","collection","colProto","Object","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","isDevMode","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration-schema');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration-schema');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n const mangoQuery: MangoQuery = {\n selector: {\n [this.schema.primaryPath]: {\n $in: ids.slice(0)\n }\n } as any\n };\n const query = createRxQuery('findByIds', mangoQuery, this as any);\n return query as any;\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";AAAA,SACIA,MAAM,EACNC,GAAG,EACHC,QAAQ,QACL,MAAM;AAEb,SACIC,OAAO,EACPC,SAAS,EACTC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,QACjB,0BAA0B;AACjC,SACIC,0BAA0B,EAC1BC,iCAAiC,EACjCC,wBAAwB,QACrB,2BAA2B;AAClC,SACIC,aAAa,EACbC,gBAAgB,QACb,eAAe;AACtB,SACIC,UAAU,EACVC,cAAc,QACX,eAAe;AAItB,SACIC,aAAa,EAAEC,2BAA2B,QACvC,gBAAgB;AACvB,SAEIC,gBAAgB,EAChBC,6BAA6B,QAC1B,kBAAkB;AACzB,SAEIC,uBAAuB,QACpB,0BAA0B;AACjC,SACIC,mBAAmB,EACnBC,cAAc,QACX,YAAY;AA0CnB,SACIC,mBAAmB,QAChB,kC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AU;QACVuB,OAAO,EAAE;UACL5N,IAAI;UACJC,MAAM;UACNU,eAAe;UACfR,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtByM,cAAc;UACdxM;QACJ;MACJ,CAAC,CAAC;MACF,OAAO4L,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAICwB,KAAK,CAAC9F,GAAG,IAAI;MACV,OAAOpH,eAAe,CAAC+K,KAAK,CAAC,CAAC,CACzBvH,IAAI,CAAC,MAAMwB,OAAO,CAACmI,MAAM,CAAC/F,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASgG,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlO,gBAAgB;AAC1C","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/rx-database.js b/dist/esm/rx-database.js index 1d24412949d..ef99b7b34ae 100644 --- a/dist/esm/rx-database.js +++ b/dist/esm/rx-database.js @@ -371,7 +371,7 @@ export var RxDatabaseBase = /*#__PURE__*/function () { _proto.remove = function remove() { return this.destroy().then(() => removeRxDatabase(this.name, this.storage, this.password)); }; - _createClass(RxDatabaseBase, [{ + return _createClass(RxDatabaseBase, [{ key: "$", get: function () { return this.observable$; @@ -382,7 +382,6 @@ export var RxDatabaseBase = /*#__PURE__*/function () { return this; } }]); - return RxDatabaseBase; }(); /** diff --git a/dist/esm/rx-database.js.map b/dist/esm/rx-database.js.map index a44d633dd42..29a486d5347 100644 --- a/dist/esm/rx-database.js.map +++ b/dist/esm/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["IdleQueue","pluginMissing","flatClone","PROMISE_RESOLVE_FALSE","randomCouchString","ensureNotFalsy","getDefaultRevision","getDefaultRxDocumentMeta","defaultHashSha256","RXDB_VERSION","newRxError","createRxSchema","runPluginHooks","runAsyncPluginHooks","Subject","mergeMap","createRxCollection","flatCloneDocWithMeta","getSingleDocument","getWrappedStorageInstance","INTERNAL_STORAGE_NAME","ObliviousSet","ensureStorageTokenDocumentExists","getAllCollectionDocuments","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","INTERNAL_STORE_SCHEMA","_collectionNamePrimary","removeCollectionStorages","overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","reactivity","idleQueue","rxdbVersion","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","states","eventBulks$","observable$","pipe","changeEventBulk","events","storageToken","storageTokenDocument","emittedEventBulkIds","asRxDatabase","catch","err","push","then","doc","data","_proto","prototype","getReactivityFactory","database","$emit","has","id","add","next","removeCollectionDoc","schema","writeDoc","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","hookData","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","addState","_name","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","devMode","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","collectionNames","forEach","removedCollectionNames","Array","from","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise,\n RxState\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\nimport type { RxReactivityFactory } from './types/plugins/reactivity.d.ts';\n\n/**\n * stores the used database names+storage names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n Reactivity = unknown\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean,\n public readonly reactivity?: RxReactivityFactory\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public getReactivityFactory(): RxReactivityFactory {\n if (!this.reactivity) {\n throw newRxError('DB14', { database: this.name });\n }\n return this.reactivity;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Because having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public states: { [name: string]: RxState; } = {};\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n addState(_name?: string): Promise> {\n throw pluginMissing('state');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration-schema');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stuff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.storage.name + '|' + this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage, this.password));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions,\n Reactivity\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and storage already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string,\n storage: RxStorage\n) {\n const key = storage.name + '|' + name;\n if (!USED_DATABASE_NAMES.has(key)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n storage: storage.name,\n link: 'https://rxdb.info/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password,\n devMode: overwritable.isDevMode()\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any,\n Reactivity = unknown\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = true,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256,\n reactivity\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n> {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name, storage);\n }\n USED_DATABASE_NAMES.add(storage.name + '|' + name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(storage.name + '|' + name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount,\n reactivity\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage,\n password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName,\n password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";AAAA,SAASA,SAAS,QAAQ,mBAAmB;AA+B7C,SACIC,aAAa,EACbC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,EACjBC,YAAY,QACT,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AACtB,SACIC,cAAc,QAEX,gBAAgB;AACvB,SACIC,cAAc,EACdC,mBAAmB,QAChB,YAAY;AACnB,SACIC,OAAO,QAGJ,MAAM;AACb,SACIC,QAAQ,QACL,gBAAgB;AACvB,SACIC,kBAAkB,QACf,oBAAoB;AAC3B,SACIC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,EACzBC,qBAAqB,QAElB,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,eAAe;AAC5C,SACIC,gCAAgC,EAChCC,yBAAyB,EACzBC,+BAA+B,EAC/BC,2BAA2B,EAC3BC,qBAAqB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CAACE,cAAc,IAAIvE,wBAAwB,CACjEQ,OAAO,EACPuI,0BAA0B,EAC1BX,qBAAqB,EACrBC,YAAY,EACZ9D,cAAc,EACd7D,QACJ,CAAC,CACL,CAAC;EAED,MAAMzB,mBAAmB,CAAC,sBAAsB,EAAE;IAC9CoJ,YAAY;IACZ7H;EACJ,CAAC,CAAC;EAEF,MAAMuI,0BAA0B,CAACjB,MAAM,CAAC,CAAC;EACzC,OAAOqB,sBAAsB;AACjC;AAEA,OAAO,SAASG,YAAYA,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYlJ,cAAc;AACxC;AAEA,OAAO,SAASmJ,OAAOA,CAAA,EAAW;EAC9B,OAAOpJ,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeqJ,iCAAiCA,CACnD3G,QAAoB,EACJ;EAChB,IAAM4G,QAAQ,GAAG,MAAM5G,QAAQ,CAACZ,oBAAoB;EACpD,OAAOwH,QAAQ,CAAChH,IAAI,CAACiH,aAAa,KAAK7G,QAAQ,CAACvC,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAemF,qBAAqBA,CACvCmD,UAA8C,EAChD;EACE,MAAMA,UAAU,CAAC5G,YAAY;EAC7B,IAAI4G,UAAU,CAACtH,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMsH,UAAU,CAACtH,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-database.js","names":["IdleQueue","pluginMissing","flatClone","PROMISE_RESOLVE_FALSE","randomCouchString","ensureNotFalsy","getDefaultRevision","getDefaultRxDocumentMeta","defaultHashSha256","RXDB_VERSION","newRxError","createRxSchema","runPluginHooks","runAsyncPluginHooks","Subject","mergeMap","createRxCollection","flatCloneDocWithMeta","getSingleDocument","getWrappedStorageInstance","INTERNAL_STORAGE_NAME","ObliviousSet","ensureStorageTokenDocumentExists","getAllCollectionDocuments","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","INTERNAL_STORE_SCHEMA","_collectionNamePrimary","removeCollectionStorages","overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","reactivity","idleQueue","rxdbVersion","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","states","eventBulks$","observable$","pipe","changeEventBulk","events","storageToken","storageTokenDocument","emittedEventBulkIds","asRxDatabase","catch","err","push","then","doc","data","_proto","prototype","getReactivityFactory","database","$emit","has","id","add","next","removeCollectionDoc","schema","writeDoc","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","hookData","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","addState","_name","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","devMode","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","collectionNames","forEach","removedCollectionNames","Array","from","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise,\n RxState\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\nimport type { RxReactivityFactory } from './types/plugins/reactivity.d.ts';\n\n/**\n * stores the used database names+storage names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n Reactivity = unknown\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean,\n public readonly reactivity?: RxReactivityFactory\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public getReactivityFactory(): RxReactivityFactory {\n if (!this.reactivity) {\n throw newRxError('DB14', { database: this.name });\n }\n return this.reactivity;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Because having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public states: { [name: string]: RxState; } = {};\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n addState(_name?: string): Promise> {\n throw pluginMissing('state');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration-schema');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stuff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.storage.name + '|' + this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage, this.password));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions,\n Reactivity\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and storage already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string,\n storage: RxStorage\n) {\n const key = storage.name + '|' + name;\n if (!USED_DATABASE_NAMES.has(key)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n storage: storage.name,\n link: 'https://rxdb.info/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password,\n devMode: overwritable.isDevMode()\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any,\n Reactivity = unknown\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = true,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256,\n reactivity\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n> {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name, storage);\n }\n USED_DATABASE_NAMES.add(storage.name + '|' + name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(storage.name + '|' + name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount,\n reactivity\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage,\n password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName,\n password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";AAAA,SAASA,SAAS,QAAQ,mBAAmB;AA+B7C,SACIC,aAAa,EACbC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,EACjBC,YAAY,QACT,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AACtB,SACIC,cAAc,QAEX,gBAAgB;AACvB,SACIC,cAAc,EACdC,mBAAmB,QAChB,YAAY;AACnB,SACIC,OAAO,QAGJ,MAAM;AACb,SACIC,QAAQ,QACL,gBAAgB;AACvB,SACIC,kBAAkB,QACf,oBAAoB;AAC3B,SACIC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,EACzBC,qBAAqB,QAElB,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,eAAe;AAC5C,SACIC,gCAAgC,EAChCC,yBAAyB,EACzBC,+BAA+B,EAC/BC,2BAA2B,EAC3BC,qBAAqB,EACrBC,sBAAsB,QACnB,iCAAiC;AACxC,SAASC,wBAAwB,QAAQ,2BAA2B;AACpE,SAASC,YAAY,QAAQ,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7D,QACJ,CAAC,CACL,CAAC;EAED,MAAMzB,mBAAmB,CAAC,sBAAsB,EAAE;IAC9CoJ,YAAY;IACZ7H;EACJ,CAAC,CAAC;EAEF,MAAMuI,0BAA0B,CAACjB,MAAM,CAAC,CAAC;EACzC,OAAOqB,sBAAsB;AACjC;AAEA,OAAO,SAASG,YAAYA,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYlJ,cAAc;AACxC;AAEA,OAAO,SAASmJ,OAAOA,CAAA,EAAW;EAC9B,OAAOpJ,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeqJ,iCAAiCA,CACnD3G,QAAoB,EACJ;EAChB,IAAM4G,QAAQ,GAAG,MAAM5G,QAAQ,CAACZ,oBAAoB;EACpD,OAAOwH,QAAQ,CAAChH,IAAI,CAACiH,aAAa,KAAK7G,QAAQ,CAACvC,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAemF,qBAAqBA,CACvCmD,UAA8C,EAChD;EACE,MAAMA,UAAU,CAAC5G,YAAY;EAC7B,IAAI4G,UAAU,CAACtH,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMsH,UAAU,CAACtH,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/rx-error.js b/dist/esm/rx-error.js index d6c788619cd..9b013e1ec01 100644 --- a/dist/esm/rx-error.js +++ b/dist/esm/rx-error.js @@ -33,7 +33,6 @@ function messageForError(message, code, parameters) { return 'RxError (' + code + '):' + '\n' + message + '\n' + parametersToString(parameters); } export var RxError = /*#__PURE__*/function (_Error) { - _inheritsLoose(RxError, _Error); // always true, use this to detect if its an rxdb-error function RxError(code, message, parameters = {}) { @@ -46,11 +45,12 @@ export var RxError = /*#__PURE__*/function (_Error) { _this.rxdb = true; // tag them as internal return _this; } + _inheritsLoose(RxError, _Error); var _proto = RxError.prototype; _proto.toString = function toString() { return this.message; }; - _createClass(RxError, [{ + return _createClass(RxError, [{ key: "name", get: function () { return 'RxError (' + this.code + ')'; @@ -61,10 +61,8 @@ export var RxError = /*#__PURE__*/function (_Error) { return false; } }]); - return RxError; }( /*#__PURE__*/_wrapNativeSuper(Error)); export var RxTypeError = /*#__PURE__*/function (_TypeError) { - _inheritsLoose(RxTypeError, _TypeError); // always true, use this to detect if its an rxdb-error function RxTypeError(code, message, parameters = {}) { @@ -77,11 +75,12 @@ export var RxTypeError = /*#__PURE__*/function (_TypeError) { _this2.rxdb = true; // tag them as internal return _this2; } + _inheritsLoose(RxTypeError, _TypeError); var _proto2 = RxTypeError.prototype; _proto2.toString = function toString() { return this.message; }; - _createClass(RxTypeError, [{ + return _createClass(RxTypeError, [{ key: "name", get: function () { return 'RxTypeError (' + this.code + ')'; @@ -92,7 +91,6 @@ export var RxTypeError = /*#__PURE__*/function (_TypeError) { return true; } }]); - return RxTypeError; }( /*#__PURE__*/_wrapNativeSuper(TypeError)); export function newRxError(code, parameters) { return new RxError(code, overwritable.tunnelErrorMessage(code), parameters); diff --git a/dist/esm/rx-error.js.map b/dist/esm/rx-error.js.map index 01fd058cc6c..137ff6fcf86 100644 --- a/dist/esm/rx-error.js.map +++ b/dist/esm/rx-error.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.js","names":["overwritable","parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","err","JSON","stringify","getOwnPropertyNames","_k","v","undefined","e","join","messageForError","message","code","RxError","_Error","_inheritsLoose","_this","mes","call","rxdb","_proto","prototype","toString","_createClass","key","get","_wrapNativeSuper","Error","RxTypeError","_TypeError","_this2","_proto2","TypeError","newRxError","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","status","STORAGE_WRITE_ERROR_CODE_TO_MESSAGE","rxStorageWriteErrorToRxError","name","document","documentId","writeError"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable.ts';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageWriteError,\n RxStorageWriteErrorConflict\n} from './types/index.d.ts';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n if (k === 'errors') {\n paramStr = parameters[k].map((err: any) => JSON.stringify(err, Object.getOwnPropertyNames(err)));\n } else {\n paramStr = JSON.stringify(parameters[k], function (_k, v) {\n return v === undefined ? null : v;\n }, 2);\n }\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err?: RxStorageWriteError | any\n): RxStorageWriteErrorConflict | false {\n if (\n err &&\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n\n\nconst STORAGE_WRITE_ERROR_CODE_TO_MESSAGE: { [k: number]: string; } = {\n 409: 'document write conflict',\n 422: 'schema validation error',\n 510: 'attachment data missing'\n};\n\nexport function rxStorageWriteErrorToRxError(err: RxStorageWriteError): RxError {\n return newRxError('COL20', {\n name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status],\n document: err.documentId,\n writeError: err\n });\n}\n"],"mappings":";;;AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,mBAAmB;AAQhD;AACA;AACA;AACA,SAASC,kBAAkBA,CAACC,UAAe,EAAU;EACjD,IAAIC,GAAG,GAAG,EAAE;EACZ,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CAACI,MAAM,KAAK,CAAC,EACpC,OAAOH,GAAG;EACdA,GAAG,IAAI,uBAAuB;EAC9BA,GAAG,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CACzBK,GAAG,CAACC,CAAC,IAAI;IACN,IAAIC,QAAQ,GAAG,iBAAiB;IAChC,IAAI;MACA,IAAID,CAAC,KAAK,QAAQ,EAAE;QAChBC,QAAQ,GAAGP,UAAU,CAACM,CAAC,CAAC,CAACD,GAAG,CAAEG,GAAQ,IAAKC,IAAI,CAACC,SAAS,CAACF,GAAG,EAAEN,MAAM,CAACS,mBAAmB,CAACH,GAAG,CAAC,CAAC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B4BM,SAAS;AA6B1C,OAAO,SAASC,UAAUA,CACtBrB,IAAgB,EAChBnB,UAA8B,EACvB;EACP,OAAO,IAAIoB,OAAO,CACdD,IAAI,EACJrB,YAAY,CAAC2C,kBAAkB,CAACtB,IAAI,CAAC,EACrCnB,UACJ,CAAC;AACL;AAEA,OAAO,SAAS0C,cAAcA,CAC1BvB,IAAgB,EAChBnB,UAA8B,EACnB;EACX,OAAO,IAAImC,WAAW,CAClBhB,IAAI,EACJrB,YAAY,CAAC2C,kBAAkB,CAACtB,IAAI,CAAC,EACrCnB,UACJ,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA,OAAO,SAAS2C,wBAAwBA,CACpCnC,GAA0C,EACI;EAC9C,IACIA,GAAG,IACHA,GAAG,CAACoC,MAAM,KAAK,GAAG,EACpB;IACE,OAAOpC,GAAG;EACd,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ;AAGA,IAAMqC,mCAA6D,GAAG;EAClE,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE;AACT,CAAC;AAED,OAAO,SAASC,4BAA4BA,CAACtC,GAA6B,EAAW;EACjF,OAAOgC,UAAU,CAAC,OAAO,EAAE;IACvBO,IAAI,EAAEF,mCAAmC,CAACrC,GAAG,CAACoC,MAAM,CAAC;IACrDI,QAAQ,EAAExC,GAAG,CAACyC,UAAU;IACxBC,UAAU,EAAE1C;EAChB,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-error.js","names":["overwritable","parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","err","JSON","stringify","getOwnPropertyNames","_k","v","undefined","e","join","messageForError","message","code","RxError","_Error","_this","mes","call","rxdb","_inheritsLoose","_proto","prototype","toString","_createClass","key","get","_wrapNativeSuper","Error","RxTypeError","_TypeError","_this2","_proto2","TypeError","newRxError","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","status","STORAGE_WRITE_ERROR_CODE_TO_MESSAGE","rxStorageWriteErrorToRxError","name","document","documentId","writeError"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable.ts';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageWriteError,\n RxStorageWriteErrorConflict\n} from './types/index.d.ts';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n if (k === 'errors') {\n paramStr = parameters[k].map((err: any) => JSON.stringify(err, Object.getOwnPropertyNames(err)));\n } else {\n paramStr = JSON.stringify(parameters[k], function (_k, v) {\n return v === undefined ? null : v;\n }, 2);\n }\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err?: RxStorageWriteError | any\n): RxStorageWriteErrorConflict | false {\n if (\n err &&\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n\n\nconst STORAGE_WRITE_ERROR_CODE_TO_MESSAGE: { [k: number]: string; } = {\n 409: 'document write conflict',\n 422: 'schema validation error',\n 510: 'attachment data missing'\n};\n\nexport function rxStorageWriteErrorToRxError(err: RxStorageWriteError): RxError {\n return newRxError('COL20', {\n name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status],\n document: err.documentId,\n writeError: err\n });\n}\n"],"mappings":";;;AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,mBAAmB;AAQhD;AACA;AACA;AACA,SAASC,kBAAkBA,CAACC,UAAe,EAAU;EACjD,IAAIC,GAAG,GAAG,EAAE;EACZ,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CAACI,MAAM,KAAK,CAAC,EACpC,OAAOH,GAAG;EACdA,GAAG,IAAI,uBAAuB;EAC9BA,GAAG,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CACzBK,GAAG,CAACC,CAAC,IAAI;IACN,IAAIC,QAAQ,GAAG,iBAAiB;IAChC,IAAI;MACA,IAAID,CAAC,KAAK,QAAQ,EAAE;QAChBC,QAAQ,GAAGP,UAAU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IAAAY,GAAA;IAAAC,GAAA,EAID,SAAAA,CAAA,EAAyB;MACrB,OAAO,IAAI;IACf;EAAC;AAAA,gBAAAC,gBAAA,CA1B4BM,SAAS;AA6B1C,OAAO,SAASC,UAAUA,CACtBrB,IAAgB,EAChBnB,UAA8B,EACvB;EACP,OAAO,IAAIoB,OAAO,CACdD,IAAI,EACJrB,YAAY,CAAC2C,kBAAkB,CAACtB,IAAI,CAAC,EACrCnB,UACJ,CAAC;AACL;AAEA,OAAO,SAAS0C,cAAcA,CAC1BvB,IAAgB,EAChBnB,UAA8B,EACnB;EACX,OAAO,IAAImC,WAAW,CAClBhB,IAAI,EACJrB,YAAY,CAAC2C,kBAAkB,CAACtB,IAAI,CAAC,EACrCnB,UACJ,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA,OAAO,SAAS2C,wBAAwBA,CACpCnC,GAA0C,EACI;EAC9C,IACIA,GAAG,IACHA,GAAG,CAACoC,MAAM,KAAK,GAAG,EACpB;IACE,OAAOpC,GAAG;EACd,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ;AAGA,IAAMqC,mCAA6D,GAAG;EAClE,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE;AACT,CAAC;AAED,OAAO,SAASC,4BAA4BA,CAACtC,GAA6B,EAAW;EACjF,OAAOgC,UAAU,CAAC,OAAO,EAAE;IACvBO,IAAI,EAAEF,mCAAmC,CAACrC,GAAG,CAACoC,MAAM,CAAC;IACrDI,QAAQ,EAAExC,GAAG,CAACyC,UAAU;IACxBC,UAAU,EAAE1C;EAChB,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/rx-query-single-result.js b/dist/esm/rx-query-single-result.js index 1d5e9b3e1b3..f349830219d 100644 --- a/dist/esm/rx-query-single-result.js +++ b/dist/esm/rx-query-single-result.js @@ -32,7 +32,7 @@ export var RxQuerySingleResult = /*#__PURE__*/function () { * to ensure we do not store the same data twice and fill up the memory. * @overwrites itself with the actual value */ - _createClass(RxQuerySingleResult, [{ + return _createClass(RxQuerySingleResult, [{ key: "docsData", get: function () { return overwriteGetterForCaching(this, 'docsData', this.documents.map(d => d._data)); @@ -60,6 +60,5 @@ export var RxQuerySingleResult = /*#__PURE__*/function () { return overwriteGetterForCaching(this, 'docsMap', map); } }]); - return RxQuerySingleResult; }(); //# sourceMappingURL=rx-query-single-result.js.map \ No newline at end of file diff --git a/dist/esm/rx-query-single-result.js.map b/dist/esm/rx-query-single-result.js.map index cc7bbfe8318..71adc454124 100644 --- a/dist/esm/rx-query-single-result.js.map +++ b/dist/esm/rx-query-single-result.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query-single-result.js","names":["mapDocumentsDataToCacheDocs","now","overwriteGetterForCaching","RxQuerySingleResult","collection","docsDataFromStorageInstance","count","time","documents","_docCache","_createClass","key","get","map","d","_data","Map","forEach","set","primary","i","length","doc"],"sources":["../../src/rx-query-single-result.ts"],"sourcesContent":["import { mapDocumentsDataToCacheDocs } from './doc-cache.ts';\nimport { now, overwriteGetterForCaching } from './plugins/utils/index.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\n\n/**\n * RxDB needs the query results in multiple formats.\n * Sometimes as a Map or an array with only the documentData.\n * For better performance we work with this class\n * that initializes stuff lazily so that\n * we can directly work with the query results after RxQuery.exec()\n */\nexport class RxQuerySingleResult{\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n public readonly time = now();\n public readonly documents: RxDocument[];\n constructor(\n public readonly collection: RxCollection,\n // only used internally, do not use outside, use this.docsData instead\n docsDataFromStorageInstance: RxDocumentData[],\n // can be overwritten for count-queries\n public readonly count: number,\n ) {\n this.documents = mapDocumentsDataToCacheDocs(this.collection._docCache, docsDataFromStorageInstance);\n }\n\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n * @overwrites itself with the actual value\n */\n get docsData(): RxDocumentData[] {\n return overwriteGetterForCaching(\n this,\n 'docsData',\n this.documents.map(d => d._data)\n );\n }\n\n\n // A key->document map, used in the event reduce optimization.\n get docsDataMap(): Map> {\n const map = new Map>();\n this.documents.forEach(d => {\n map.set(d.primary, d._data);\n });\n return overwriteGetterForCaching(\n this,\n 'docsDataMap',\n map\n );\n }\n\n get docsMap(): Map> {\n const map = new Map>();\n const documents = this.documents;\n for (let i = 0; i < documents.length; i++) {\n const doc = documents[i];\n map.set(doc.primary, doc);\n }\n return overwriteGetterForCaching(\n this,\n 'docsMap',\n map\n );\n }\n}\n"],"mappings":";AAAA,SAASA,2BAA2B,QAAQ,gBAAgB;AAC5D,SAASC,GAAG,EAAEC,yBAAyB,QAAQ,0BAA0B;AAOzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,mBAAmB;EAC5B;AACJ;AACA;AACA;AACA;;EAGI,SAAAA,oBACoBC,UAAmC;EACnD;EACAC,2BAAwD;EACxD;EACgBC,KAAa,EAC/B;IAAA,KARcC,IAAI,GAAGN,GAAG,CAAC,CAAC;IAAA,KAGRG,UAAmC,GAAnCA,UAAmC;IAAA,KAInCE,KAAa,GAAbA,KAAa;IAE7B,IAAI,CAACE,SAAS,GAAGR,2BAA2B,CAAiB,IAAI,CAACI,UAAU,CAACK,SAAS,EAAEJ,2BAA2B,CAAC;EACxH;;EAGA;AACJ;AACA;AACA;AACA;AACA;EALIK,YAAA,CAAAP,mBAAA;IAAAQ,GAAA;IAAAC,GAAA,EAMA,SAAAA,CAAA,EAA4C;MACxC,OAAOV,yBAAyB,CAC5B,IAAI,EACJ,UAAU,EACV,IAAI,CAACM,SAAS,CAACK,GAAG,CAACC,CAAC,IAAIA,CAAC,CAACC,KAAK,CACnC,CAAC;IACL;;IAGA;EAAA;IAAAJ,GAAA;IAAAC,GAAA,EACA,SAAAA,CAAA,EAA0D;MACtD,IAAMC,GAAG,GAAG,IAAIG,GAAG,CAAoC,CAAC;MACxD,IAAI,CAACR,SAAS,CAACS,OAAO,CAACH,CAAC,IAAI;QACxBD,GAAG,CAACK,GAAG,CAACJ,CAAC,CAACK,OAAO,EAAEL,CAAC,CAACC,KAAK,CAAC;MAC/B,CAAC,CAAC;MACF,OAAOb,yBAAyB,CAC5B,IAAI,EACJ,aAAa,EACbW,GACJ,CAAC;IACL;EAAC;IAAAF,GAAA;IAAAC,GAAA,EAED,SAAAA,CAAA,EAAkD;MAC9C,IAAMC,GAAG,GAAG,IAAIG,GAAG,CAAgC,CAAC;MACpD,IAAMR,SAAS,GAAG,IAAI,CAACA,SAAS;MAChC,KAAK,IAAIY,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGZ,SAAS,CAACa,MAAM,EAAED,CAAC,EAAE,EAAE;QACvC,IAAME,GAAG,GAAGd,SAAS,CAACY,CAAC,CAAC;QACxBP,GAAG,CAACK,GAAG,CAACI,GAAG,CAACH,OAAO,EAAEG,GAAG,CAAC;MAC7B;MACA,OAAOpB,yBAAyB,CAC5B,IAAI,EACJ,SAAS,EACTW,GACJ,CAAC;IACL;EAAC;EAAA,OAAAV,mBAAA;AAAA","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-query-single-result.js","names":["mapDocumentsDataToCacheDocs","now","overwriteGetterForCaching","RxQuerySingleResult","collection","docsDataFromStorageInstance","count","time","documents","_docCache","_createClass","key","get","map","d","_data","Map","forEach","set","primary","i","length","doc"],"sources":["../../src/rx-query-single-result.ts"],"sourcesContent":["import { mapDocumentsDataToCacheDocs } from './doc-cache.ts';\nimport { now, overwriteGetterForCaching } from './plugins/utils/index.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\n\n/**\n * RxDB needs the query results in multiple formats.\n * Sometimes as a Map or an array with only the documentData.\n * For better performance we work with this class\n * that initializes stuff lazily so that\n * we can directly work with the query results after RxQuery.exec()\n */\nexport class RxQuerySingleResult{\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n public readonly time = now();\n public readonly documents: RxDocument[];\n constructor(\n public readonly collection: RxCollection,\n // only used internally, do not use outside, use this.docsData instead\n docsDataFromStorageInstance: RxDocumentData[],\n // can be overwritten for count-queries\n public readonly count: number,\n ) {\n this.documents = mapDocumentsDataToCacheDocs(this.collection._docCache, docsDataFromStorageInstance);\n }\n\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n * @overwrites itself with the actual value\n */\n get docsData(): RxDocumentData[] {\n return overwriteGetterForCaching(\n this,\n 'docsData',\n this.documents.map(d => d._data)\n );\n }\n\n\n // A key->document map, used in the event reduce optimization.\n get docsDataMap(): Map> {\n const map = new Map>();\n this.documents.forEach(d => {\n map.set(d.primary, d._data);\n });\n return overwriteGetterForCaching(\n this,\n 'docsDataMap',\n map\n );\n }\n\n get docsMap(): Map> {\n const map = new Map>();\n const documents = this.documents;\n for (let i = 0; i < documents.length; i++) {\n const doc = documents[i];\n map.set(doc.primary, doc);\n }\n return overwriteGetterForCaching(\n this,\n 'docsMap',\n map\n );\n }\n}\n"],"mappings":";AAAA,SAASA,2BAA2B,QAAQ,gBAAgB;AAC5D,SAASC,GAAG,EAAEC,yBAAyB,QAAQ,0BAA0B;AAOzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,mBAAmB;EAC5B;AACJ;AACA;AACA;AACA;;EAGI,SAAAA,oBACoBC,UAAmC;EACnD;EACAC,2BAAwD;EACxD;EACgBC,KAAa,EAC/B;IAAA,KARcC,IAAI,GAAGN,GAAG,CAAC,CAAC;IAAA,KAGRG,UAAmC,GAAnCA,UAAmC;IAAA,KAInCE,KAAa,GAAbA,KAAa;IAE7B,IAAI,CAACE,SAAS,GAAGR,2BAA2B,CAAiB,IAAI,CAACI,UAAU,CAACK,SAAS,EAAEJ,2BAA2B,CAAC;EACxH;;EAGA;AACJ;AACA;AACA;AACA;AACA;EALI,OAAAK,YAAA,CAAAP,mBAAA;IAAAQ,GAAA;IAAAC,GAAA,EAMA,SAAAA,CAAA,EAA4C;MACxC,OAAOV,yBAAyB,CAC5B,IAAI,EACJ,UAAU,EACV,IAAI,CAACM,SAAS,CAACK,GAAG,CAACC,CAAC,IAAIA,CAAC,CAACC,KAAK,CACnC,CAAC;IACL;;IAGA;EAAA;IAAAJ,GAAA;IAAAC,GAAA,EACA,SAAAA,CAAA,EAA0D;MACtD,IAAMC,GAAG,GAAG,IAAIG,GAAG,CAAoC,CAAC;MACxD,IAAI,CAACR,SAAS,CAACS,OAAO,CAACH,CAAC,IAAI;QACxBD,GAAG,CAACK,GAAG,CAACJ,CAAC,CAACK,OAAO,EAAEL,CAAC,CAACC,KAAK,CAAC;MAC/B,CAAC,CAAC;MACF,OAAOb,yBAAyB,CAC5B,IAAI,EACJ,aAAa,EACbW,GACJ,CAAC;IACL;EAAC;IAAAF,GAAA;IAAAC,GAAA,EAED,SAAAA,CAAA,EAAkD;MAC9C,IAAMC,GAAG,GAAG,IAAIG,GAAG,CAAgC,CAAC;MACpD,IAAMR,SAAS,GAAG,IAAI,CAACA,SAAS;MAChC,KAAK,IAAIY,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGZ,SAAS,CAACa,MAAM,EAAED,CAAC,EAAE,EAAE;QACvC,IAAME,GAAG,GAAGd,SAAS,CAACY,CAAC,CAAC;QACxBP,GAAG,CAACK,GAAG,CAACI,GAAG,CAACH,OAAO,EAAEG,GAAG,CAAC;MAC7B;MACA,OAAOpB,yBAAyB,CAC5B,IAAI,EACJ,SAAS,EACTW,GACJ,CAAC;IACL;EAAC;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/rx-query.js b/dist/esm/rx-query.js index d21bcdf6b02..39e1bb29ef3 100644 --- a/dist/esm/rx-query.js +++ b/dist/esm/rx-query.js @@ -252,7 +252,7 @@ export var RxQueryBase = /*#__PURE__*/function () { _proto.limit = function limit(_amount) { throw pluginMissing('query-builder'); }; - _createClass(RxQueryBase, [{ + return _createClass(RxQueryBase, [{ key: "$", get: function () { if (!this._$) { @@ -338,7 +338,6 @@ export var RxQueryBase = /*#__PURE__*/function () { return this; } }]); - return RxQueryBase; }(); export function _getDefaultQuery() { return { diff --git a/dist/esm/rx-query.js.map b/dist/esm/rx-query.js.map index 61dff97974c..842366c7ad3 100644 --- a/dist/esm/rx-query.js.map +++ b/dist/esm/rx-query.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.js","names":["BehaviorSubject","firstValueFrom","merge","mergeMap","filter","map","startWith","distinctUntilChanged","shareReplay","sortObject","pluginMissing","overwriteGetterForCaching","now","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","ensureNotFalsy","areRxDocumentArraysEqual","appendToArray","newRxError","runPluginHooks","calculateNewResults","triggerCacheReplacement","getQueryMatcher","normalizeMangoQuery","RxQuerySingleResult","getQueryPlan","_queryCount","newQueryID","RxQueryBase","op","mangoQuery","collection","other","id","_execOverDatabaseCount","_creationTime","_lastEnsureEqual","uncached","refCount$","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","_getDefaultQuery","isFindOneByIdQuery","schema","primaryPath","_proto","prototype","_setResultData","newResultData","Map","Array","from","values","newQueryResult","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","count","mode","database","allowSlowCount","queryObj","ids","selector","$in","ret","mustBeQueried","forEach","docData","_docCache","getLatestDocumentDataIfExists","_deleted","doc","getCachedRxDocument","set","push","docs","findDocumentsById","primary","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","$","toString","stringObj","value","JSON","stringify","hookInput","rxQuery","jsonSchema","$eq","index","unshift","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","update","_updateObj","where","_queryObj","sort","_params","skip","_amount","limit","_createClass","key","get","_$","results$","pipe","changeEvent","isLocal","prev","curr","time","useResult","documents","docsMap","slice","reactivity","getReactivityFactory","fromObservable","undefined","normalizedQuery","tunnelQueryCache","_queryCache","getByQuery","createRxQuery","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","runFullQueryAgain","changed","newResults","docsData","resolve","mutateableQuery","queryPlan","docIds","docId","docsFromStorage","fromStorageList","queryResult","Object","keys","find","r","isRxQuery","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual,\n appendToArray\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData,\n QueryMatcher,\n RxJsonSchema,\n FilledMangoQuery\n} from './types/index.d.ts';\nimport { calculateNewResults } from './event-reduce.ts';\nimport { triggerCacheReplacement } from './query-cache.ts';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper.ts';\nimport { RxQuerySingleResult } from './rx-query-single-result.ts';\nimport { getQueryPlan } from './query-planner.ts';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n RxQueryResult,\n OrmMethods = {},\n Reactivity = unknown,\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string | string[];\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: RxQuerySingleResult | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly>,\n public collection: RxCollection,\n // used by some plugins\n public other: any = {}\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.documents.length === 0 ? null : useResult.documents[0];\n } else if (this.op === 'findByIds') {\n return useResult.docsMap;\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.documents.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n get $$(): Reactivity {\n const reactivity = this.collection.database.getReactivityFactory();\n return reactivity.fromObservable(\n this.$,\n undefined\n );\n }\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from the storage\n */\n _setResultData(newResultData: RxDocumentData[] | number | Map>): void {\n if (typeof newResultData === 'number') {\n this._result = new RxQuerySingleResult(\n this.collection,\n [],\n newResultData\n );\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const newQueryResult = new RxQuerySingleResult(\n this.collection,\n newResultData,\n newResultData.length\n );\n this._result = newQueryResult;\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n async _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n const result = await this.collection.storageInstance.count(preparedQuery);\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n }\n\n if (this.op === 'findByIds') {\n const ids: string[] = ensureNotFalsy(this.mangoQuery.selector as any)[this.collection.schema.primaryPath].$in;\n const ret = new Map>();\n const mustBeQueried: string[] = [];\n // first try to fill from docCache\n ids.forEach(id => {\n const docData = this.collection._docCache.getLatestDocumentDataIfExists(id);\n if (docData) {\n if (!docData._deleted) {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(id, doc);\n }\n } else {\n mustBeQueried.push(id);\n }\n });\n // everything which was not in docCache must be fetched from the storage\n if (mustBeQueried.length > 0) {\n const docs = await this.collection.storageInstance.findDocumentsById(mustBeQueried, false);\n docs.forEach(docData => {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret as any;\n }\n\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this as any)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n const normalizedQuery = normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n );\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n getQueryMatcher(\n schema,\n normalizedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n )\n };\n (hookInput.mangoQuery.selector as any)._deleted = { $eq: false };\n if (hookInput.mangoQuery.index) {\n hookInput.mangoQuery.index.unshift('_deleted');\n }\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery as any\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n return this\n .exec()\n .then(docs => {\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n });\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection,\n other?: any\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection,\n other\n });\n\n let ret = new RxQueryBase(op, queryObj, collection, other);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n\n /**\n * The RxStorage is defined to always first emit events and then return\n * on bulkWrite() calls. So here we have to use the counter AFTER the execOverDatabase()\n * has been run, not the one from before.\n */\n rxQuery._latestChangeEvent = rxQuery.collection._changeEventBuffer.counter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\nexport function prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n): PreparedQuery {\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensure findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n if (Array.isArray(rxQuery.isFindOneByIdQuery)) {\n let docIds = rxQuery.isFindOneByIdQuery;\n docIds = docIds.filter(docId => {\n // first try to fill from docCache\n const docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (docData) {\n if (!docData._deleted) {\n docs.push(docData);\n }\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n if (docIds.length > 0) {\n const docsFromStorage = await collection.storageInstance.findDocumentsById(docIds, false);\n appendToArray(docs, docsFromStorage);\n }\n } else {\n const docId = rxQuery.isFindOneByIdQuery;\n\n // first try to fill from docCache\n let docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (!docData) {\n // otherwise get from storage\n const fromStorageList = await collection.storageInstance.findDocumentsById([docId], false);\n if (fromStorageList[0]) {\n docData = fromStorageList[0];\n }\n }\n if (docData && !docData._deleted) {\n docs.push(docData);\n }\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string | string[] {\n // must have exactly one operator which must be $eq || $in\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n const value: any = query.selector[primaryPath];\n if (typeof value === 'string') {\n return value;\n } else if (\n Object.keys(value).length === 1 &&\n typeof value.$eq === 'string'\n ) {\n return value.$eq;\n }\n\n // same with $in string arrays\n if (\n Object.keys(value).length === 1 &&\n Array.isArray(value.$eq) &&\n // must only contain strings\n !(value.$eq as any[]).find(r => typeof r !== 'string')\n ) {\n return value.$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isRxQuery(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";AAAA,SACIA,eAAe,EACfC,cAAc,EAEdC,KAAK,QACF,MAAM;AACb,SACIC,QAAQ,EACRC,MAAM,EACNC,GAAG,EACHC,SAAS,EACTC,oBAAoB,EACpBC,WAAW,QACR,gBAAgB;AACvB,SACIC,UAAU,EACVC,aAAa,EACbC,yBAAyB,EACzBC,GAAG,EACHC,qBAAqB,EACrBC,0BAA0B,EAC1BC,cAAc,EACdC,wBAAwB,EACxBC,aAAa,QACV,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AAC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AAC,CAACZ,MAAM,KAAK,CAAC,IACxCkC,KAAK,CAACtB,QAAQ,CAACtB,WAAW,CAAC,EAC7B;IACE,IAAMiD,KAAU,GAAGL,KAAK,CAACtB,QAAQ,CAACtB,WAAW,CAAC;IAC9C,IAAI,OAAOiD,KAAK,KAAK,QAAQ,EAAE;MAC3B,OAAOA,KAAK;IAChB,CAAC,MAAM,IACHiF,MAAM,CAACC,IAAI,CAAClF,KAAK,CAAC,CAACvC,MAAM,KAAK,CAAC,IAC/B,OAAOuC,KAAK,CAACM,GAAG,KAAK,QAAQ,EAC/B;MACE,OAAON,KAAK,CAACM,GAAG;IACpB;;IAEA;IACA,IACI2E,MAAM,CAACC,IAAI,CAAClF,KAAK,CAAC,CAACvC,MAAM,KAAK,CAAC,IAC/BJ,KAAK,CAACwD,OAAO,CAACb,KAAK,CAACM,GAAG,CAAC;IACxB;IACA,CAAEN,KAAK,CAACM,GAAG,CAAW6E,IAAI,CAACC,CAAC,IAAI,OAAOA,CAAC,KAAK,QAAQ,CAAC,EACxD;MACE,OAAOpF,KAAK,CAACM,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIA,OAAO,SAAS+E,SAASA,CAACC,GAAQ,EAAW;EACzC,OAAOA,GAAG,YAAY1J,WAAW;AACrC","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-query.js","names":["BehaviorSubject","firstValueFrom","merge","mergeMap","filter","map","startWith","distinctUntilChanged","shareReplay","sortObject","pluginMissing","overwriteGetterForCaching","now","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","ensureNotFalsy","areRxDocumentArraysEqual","appendToArray","newRxError","runPluginHooks","calculateNewResults","triggerCacheReplacement","getQueryMatcher","normalizeMangoQuery","RxQuerySingleResult","getQueryPlan","_queryCount","newQueryID","RxQueryBase","op","mangoQuery","collection","other","id","_execOverDatabaseCount","_creationTime","_lastEnsureEqual","uncached","refCount$","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","_getDefaultQuery","isFindOneByIdQuery","schema","primaryPath","_proto","prototype","_setResultData","newResultData","Map","Array","from","values","newQueryResult","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","count","mode","database","allowSlowCount","queryObj","ids","selector","$in","ret","mustBeQueried","forEach","docData","_docCache","getLatestDocumentDataIfExists","_deleted","doc","getCachedRxDocument","set","push","docs","findDocumentsById","primary","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","$","toString","stringObj","value","JSON","stringify","hookInput","rxQuery","jsonSchema","$eq","index","unshift","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","update","_updateObj","where","_queryObj","sort","_params","skip","_amount","limit","_createClass","key","get","_$","results$","pipe","changeEvent","isLocal","prev","curr","time","useResult","documents","docsMap","slice","reactivity","getReactivityFactory","fromObservable","undefined","normalizedQuery","tunnelQueryCache","_queryCache","getByQuery","createRxQuery","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","runFullQueryAgain","changed","newResults","docsData","resolve","mutateableQuery","queryPlan","docIds","docId","docsFromStorage","fromStorageList","queryResult","Object","keys","find","r","isRxQuery","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual,\n appendToArray\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData,\n QueryMatcher,\n RxJsonSchema,\n FilledMangoQuery\n} from './types/index.d.ts';\nimport { calculateNewResults } from './event-reduce.ts';\nimport { triggerCacheReplacement } from './query-cache.ts';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper.ts';\nimport { RxQuerySingleResult } from './rx-query-single-result.ts';\nimport { getQueryPlan } from './query-planner.ts';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n RxQueryResult,\n OrmMethods = {},\n Reactivity = unknown,\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string | string[];\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: RxQuerySingleResult | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly>,\n public collection: RxCollection,\n // used by some plugins\n public other: any = {}\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.documents.length === 0 ? null : useResult.documents[0];\n } else if (this.op === 'findByIds') {\n return useResult.docsMap;\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.documents.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n get $$(): Reactivity {\n const reactivity = this.collection.database.getReactivityFactory();\n return reactivity.fromObservable(\n this.$,\n undefined\n );\n }\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from the storage\n */\n _setResultData(newResultData: RxDocumentData[] | number | Map>): void {\n if (typeof newResultData === 'number') {\n this._result = new RxQuerySingleResult(\n this.collection,\n [],\n newResultData\n );\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const newQueryResult = new RxQuerySingleResult(\n this.collection,\n newResultData,\n newResultData.length\n );\n this._result = newQueryResult;\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n async _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n const result = await this.collection.storageInstance.count(preparedQuery);\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n }\n\n if (this.op === 'findByIds') {\n const ids: string[] = ensureNotFalsy(this.mangoQuery.selector as any)[this.collection.schema.primaryPath].$in;\n const ret = new Map>();\n const mustBeQueried: string[] = [];\n // first try to fill from docCache\n ids.forEach(id => {\n const docData = this.collection._docCache.getLatestDocumentDataIfExists(id);\n if (docData) {\n if (!docData._deleted) {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(id, doc);\n }\n } else {\n mustBeQueried.push(id);\n }\n });\n // everything which was not in docCache must be fetched from the storage\n if (mustBeQueried.length > 0) {\n const docs = await this.collection.storageInstance.findDocumentsById(mustBeQueried, false);\n docs.forEach(docData => {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret as any;\n }\n\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this as any)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n const normalizedQuery = normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n );\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n getQueryMatcher(\n schema,\n normalizedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n this.mangoQuery\n )\n };\n (hookInput.mangoQuery.selector as any)._deleted = { $eq: false };\n if (hookInput.mangoQuery.index) {\n hookInput.mangoQuery.index.unshift('_deleted');\n }\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery as any\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n return this\n .exec()\n .then(docs => {\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n });\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection,\n other?: any\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection,\n other\n });\n\n let ret = new RxQueryBase(op, queryObj, collection, other);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n\n /**\n * The RxStorage is defined to always first emit events and then return\n * on bulkWrite() calls. So here we have to use the counter AFTER the execOverDatabase()\n * has been run, not the one from before.\n */\n rxQuery._latestChangeEvent = rxQuery.collection._changeEventBuffer.counter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\nexport function prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n): PreparedQuery {\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensure findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n if (Array.isArray(rxQuery.isFindOneByIdQuery)) {\n let docIds = rxQuery.isFindOneByIdQuery;\n docIds = docIds.filter(docId => {\n // first try to fill from docCache\n const docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (docData) {\n if (!docData._deleted) {\n docs.push(docData);\n }\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n if (docIds.length > 0) {\n const docsFromStorage = await collection.storageInstance.findDocumentsById(docIds, false);\n appendToArray(docs, docsFromStorage);\n }\n } else {\n const docId = rxQuery.isFindOneByIdQuery;\n\n // first try to fill from docCache\n let docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (!docData) {\n // otherwise get from storage\n const fromStorageList = await collection.storageInstance.findDocumentsById([docId], false);\n if (fromStorageList[0]) {\n docData = fromStorageList[0];\n }\n }\n if (docData && !docData._deleted) {\n docs.push(docData);\n }\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string | string[] {\n // must have exactly one operator which must be $eq || $in\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n const value: any = query.selector[primaryPath];\n if (typeof value === 'string') {\n return value;\n } else if (\n Object.keys(value).length === 1 &&\n typeof value.$eq === 'string'\n ) {\n return value.$eq;\n }\n\n // same with $in string arrays\n if (\n Object.keys(value).length === 1 &&\n Array.isArray(value.$eq) &&\n // must only contain strings\n !(value.$eq as any[]).find(r => typeof r !== 'string')\n ) {\n return value.$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isRxQuery(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";AAAA,SACIA,eAAe,EACfC,cAAc,EAEdC,KAAK,QACF,MAAM;AACb,SACIC,QAAQ,EACRC,MAAM,EACNC,GAAG,EACHC,SAAS,EACTC,oBAAoB,EACpBC,WAAW,QACR,gBAAgB;AACvB,SACIC,UAAU,EACVC,aAAa,EACbC,yBAAyB,EACzBC,GAAG,EACHC,qBAAqB,EACrBC,0BAA0B,EAC1BC,cAAc,EACdC,wBAAwB,EACxBC,aAAa,QACV,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AACtB,SACIC,cAAc,QACX,YAAY;AAiBnB,SAASC,mBAAmB,QAAQ,mBAAmB;AACvD,SAASC,uBAAuB,QAAQ,kBAAkB;AAC1D,SAASC,eAAe,EAAEC,mBAAmB,QAAQ,sBAAsB;AAC3E,SAASC,mBAAmB,QAAQ,6BAA6B;AACjE,SAASC,YAAY,QAAQ,oBAAoB;AAEjD,IAAIC,WAAW,GAAG,CAAC;AACnB,IAAMC,UAAU,GAAG,SAAAA,CAAA,EAAoB;EACnC,OAAO,EAAED,WAAW;AACxB,CAAC;AAED,WAAaE,WAAW;EASpB;AACJ;AACA;;EAII;;EAKA;;EAMA;AACJ;AACA;AACA;;EAII,SAAAA,YACWC,EAAa,EACbC,UAA2C,EAC3CC,UAAmC;EAC1C;EACOC,KAAU,GAAG,CAAC,CAAC,EACxB;IAAA,KAhCKC,EAAE,GAAWN,UAAU,CAAC,CAAC;IAAA,KAKzBO,sBAAsB,GAAW,CAAC;IAAA,KAClCC,aAAa,GAAGvB,GAAG,CAAC,CAAC;IAAA,KAGrBwB,gBAAgB,GAAG,CAAC;IAAA,KAEpBC,QAAQ,GAAG,KAAK;IAAA,KAGhBC,S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SAASA,CAACC,GAAQ,EAAW;EACzC,OAAOA,GAAG,YAAY1J,WAAW;AACrC","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/rx-schema.js b/dist/esm/rx-schema.js index 618f86eab80..2628d923875 100644 --- a/dist/esm/rx-schema.js +++ b/dist/esm/rx-schema.js @@ -94,7 +94,7 @@ export var RxSchema = /*#__PURE__*/function () { _proto.getPrimaryOfDocumentData = function getPrimaryOfDocumentData(documentData) { return getComposedPrimaryKeyOfDocumentData(this.jsonSchema, documentData); }; - _createClass(RxSchema, [{ + return _createClass(RxSchema, [{ key: "version", get: function () { return this.jsonSchema.version; @@ -119,7 +119,6 @@ export var RxSchema = /*#__PURE__*/function () { return overwriteGetterForCaching(this, 'hash', this.hashFunction(JSON.stringify(this.jsonSchema))); } }]); - return RxSchema; }(); export function getIndexes(jsonSchema) { return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]); diff --git a/dist/esm/rx-schema.js.map b/dist/esm/rx-schema.js.map index 527c18ceecb..9188bc2802f 100644 --- a/dist/esm/rx-schema.js.map +++ b/dist/esm/rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema.js","names":["overwriteGetterForCaching","isMaybeReadonlyArray","deepEqual","newRxError","runPluginHooks","fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","getFinalFields","getPrimaryFieldOfPrimaryKey","getSchemaByObjectPath","normalizeRxJsonSchema","overwritable","RxSchema","jsonSchema","hashFunction","indexes","getIndexes","primaryPath","primaryKey","finalFields","_proto","prototype","validateChange","dataBefore","dataAfter","forEach","fieldName","schema","getDocumentPrototype","proto","pathProperties","Object","keys","key","fullPath","__defineGetter__","get","undefined","ret","defineProperty","get$","enumerable","configurable","get$$","populate","getPrimaryOfDocumentData","documentData","_createClass","version","values","entries","properties","filter","v","hasOwnProperty","call","k","default","JSON","stringify","map","index","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","useJsonSchema","deepFreezeWhenDevMode","isRxSchema","obj","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import {\n overwriteGetterForCaching,\n isMaybeReadonlyArray,\n deepEqual\n} from './plugins/utils/index.ts';\nimport {\n newRxError,\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\n\nimport type {\n DeepMutable,\n DeepReadonly,\n HashFunction,\n MaybeReadonly,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types/index.d.ts';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath,\n normalizeRxJsonSchema\n} from './rx-schema-helper.ts';\nimport { overwritable } from './overwritable.ts';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>,\n public readonly hashFunction: HashFunction\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => Object.prototype.hasOwnProperty.call(v, 'default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n *\n * TODO this should be a pure function that\n * caches the hash in a WeakMap.\n */\n public get hash(): Promise {\n return overwriteGetterForCaching(\n this,\n 'hash',\n this.hashFunction(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto: any = {};\n\n /**\n * On the top level, we know all keys\n * and therefore do not have to create a new Proxy object\n * for each document. Instead we define the getter in the prototype once.\n */\n const pathProperties = getSchemaByObjectPath(\n this.jsonSchema,\n ''\n );\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = key;\n\n // getter - value\n proto.__defineGetter__(\n key,\n function (this: RxDocument) {\n if (!this.get || typeof this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(proto, key + '$', {\n get: function () {\n return this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - reactivity$$\n Object.defineProperty(proto, key + '$$', {\n get: function () {\n return this.get$$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(proto, key + '_', {\n get: function () {\n return this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n });\n\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n hashFunction: HashFunction,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema, hashFunction);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isRxSchema(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";AAAA,SACIA,yBAAyB,EACzBC,oBAAoB,EACpBC,SAAS,QACN,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AACtB,SACIC,cAAc,QACX,YAAY;AAYnB,SACIC,uBAAuB,EACvBC,mCAAmC,EACnCC,cAAc,EACdC,2BAA2B,EAC3BC,qBAAqB,EACrBC,qBAAqB,QAClB,uBAAuB;AAC9B,SAASC,YAAY,QAAQ,mBAAmB;AAEhD,WAAaC,QAAQ;EAKjB,SAAAA,SACoBC,UAAmD,EACnDC,YAA0B,EAC5C;IAAA,KAFkBD,UAAmD,GAAnDA,UAAmD;IAAA,KACnDC,YAA0B,GAA1BA,YAA0B;IAE1C,IAAI,CAACC,OAAO,GAAGC,UAAU,CAAC,IAAI,CAACH,UAAU,CAAC;;IAE1C;IACA,IAAI,CAACI,WAAW,GAAGT,2BAA2B,CAAC,IAAI,CAACK,UAAU,CAACK,UAAU,CAAC;IAE1E,IAAI,CAACC,WAAW,GAAGZ,cAAc,CAAC,IAAI,CAACM,UAAU,CAAC;EACtD;EAAC,IAAAO,MAAA,GAAAR,QAAA,CAAAS,SA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0D,aAAa,CAAC;EACpDzD,YAAY,CAAC0D,qBAAqB,CAACD,aAAa,CAAC;EAEjD,IAAMzC,MAAM,GAAG,IAAIf,QAAQ,CAACwD,aAAa,EAAEtD,YAAY,CAAC;EACxDV,cAAc,CAAC,gBAAgB,EAAEuB,MAAM,CAAC;EACxC,OAAOA,MAAM;AACjB;AAEA,OAAO,SAAS2C,UAAUA,CAACC,GAAQ,EAAW;EAC1C,OAAOA,GAAG,YAAY3D,QAAQ;AAClC;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAAS4D,mBAAmBA,CAA4C7C,MAAS,EAAkB;EACtG,OAAOA,MAAM;AACjB","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-schema.js","names":["overwriteGetterForCaching","isMaybeReadonlyArray","deepEqual","newRxError","runPluginHooks","fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","getFinalFields","getPrimaryFieldOfPrimaryKey","getSchemaByObjectPath","normalizeRxJsonSchema","overwritable","RxSchema","jsonSchema","hashFunction","indexes","getIndexes","primaryPath","primaryKey","finalFields","_proto","prototype","validateChange","dataBefore","dataAfter","forEach","fieldName","schema","getDocumentPrototype","proto","pathProperties","Object","keys","key","fullPath","__defineGetter__","get","undefined","ret","defineProperty","get$","enumerable","configurable","get$$","populate","getPrimaryOfDocumentData","documentData","_createClass","version","values","entries","properties","filter","v","hasOwnProperty","call","k","default","JSON","stringify","map","index","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","useJsonSchema","deepFreezeWhenDevMode","isRxSchema","obj","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import {\n overwriteGetterForCaching,\n isMaybeReadonlyArray,\n deepEqual\n} from './plugins/utils/index.ts';\nimport {\n newRxError,\n} from './rx-error.ts';\nimport {\n runPluginHooks\n} from './hooks.ts';\n\nimport type {\n DeepMutable,\n DeepReadonly,\n HashFunction,\n MaybeReadonly,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types/index.d.ts';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath,\n normalizeRxJsonSchema\n} from './rx-schema-helper.ts';\nimport { overwritable } from './overwritable.ts';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>,\n public readonly hashFunction: HashFunction\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => Object.prototype.hasOwnProperty.call(v, 'default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n *\n * TODO this should be a pure function that\n * caches the hash in a WeakMap.\n */\n public get hash(): Promise {\n return overwriteGetterForCaching(\n this,\n 'hash',\n this.hashFunction(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto: any = {};\n\n /**\n * On the top level, we know all keys\n * and therefore do not have to create a new Proxy object\n * for each document. Instead we define the getter in the prototype once.\n */\n const pathProperties = getSchemaByObjectPath(\n this.jsonSchema,\n ''\n );\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = key;\n\n // getter - value\n proto.__defineGetter__(\n key,\n function (this: RxDocument) {\n if (!this.get || typeof this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(proto, key + '$', {\n get: function () {\n return this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - reactivity$$\n Object.defineProperty(proto, key + '$$', {\n get: function () {\n return this.get$$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(proto, key + '_', {\n get: function () {\n return this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n });\n\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n hashFunction: HashFunction,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema, hashFunction);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isRxSchema(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";AAAA,SACIA,yBAAyB,EACzBC,oBAAoB,EACpBC,SAAS,QACN,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AACtB,SACIC,cAAc,QACX,YAAY;AAYnB,SACIC,uBAAuB,EACvBC,mCAAmC,EACnCC,cAAc,EACdC,2BAA2B,EAC3BC,qBAAqB,EACrBC,qBAAqB,QAClB,uBAAuB;AAC9B,SAASC,YAAY,QAAQ,mBAAmB;AAEhD,WAAaC,QAAQ;EAKjB,SAAAA,SACoBC,UAAmD,EACnDC,YAA0B,EAC5C;IAAA,KAFkBD,UAAmD,GAAnDA,UAAmD;IAAA,KACnDC,YAA0B,GAA1BA,YAA0B;IAE1C,IAAI,CAACC,OAAO,GAAGC,UAAU,CAAC,IAAI,CAACH,UAAU,CAAC;;IAE1C;IACA,IAAI,CAACI,WAAW,GAAGT,2BAA2B,CAAC,IAAI,CAACK,UAAU,CAACK,UAAU,CAAC;IAE1E,IAAI,CAACC,WAAW,GAAGZ,cAAc,CAAC,IAAI,CAACM,UAAU,CAAC;EACtD;EAAC,IAAAO,MAAA,GAAAR,QAAA,CAAAS,SAAA;EAiCD;AACJ;AACA;AACA;AACA;AACA;EALID,MAAA,CAMAE,cAAc,GAAd,SAAAA,eAAeC,UAAe,EAAEC,SAAc,EAAQ;IAClD,IAAI,CAACL,WAAW,CAACM,OAAO,CAACC,SAAS,IAAI;MAClC,IAAI,CAACxB,SAAS,CAACqB,UAAU,CAACG,SAAS,CAAC,EAAEF,SAAS,CAACE,SAAS,CAAC,CAAC,EAAE;QACzD,MAAMvB,UAAU,CAA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AClC;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAAS4D,mBAAmBA,CAA4C7C,MAAS,EAAkB;EACtG,OAAOA,MAAM;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/docs/404.html b/docs/404.html index 9c87d85832d..90595bcc76c 100644 --- a/docs/404.html +++ b/docs/404.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/adapters.html b/docs/adapters.html index fc05b17389f..5ec9426290b 100644 --- a/docs/adapters.html +++ b/docs/adapters.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/alternatives.html b/docs/alternatives.html index 6c92fb97955..5c5115ebf4e 100644 --- a/docs/alternatives.html +++ b/docs/alternatives.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/angular-database.html b/docs/articles/angular-database.html index 57447e1cf80..3c2152ba5d2 100644 --- a/docs/articles/angular-database.html +++ b/docs/articles/angular-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/browser-database.html b/docs/articles/browser-database.html index 7daf225e2b7..651caf48026 100644 --- a/docs/articles/browser-database.html +++ b/docs/articles/browser-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/browser-storage.html b/docs/articles/browser-storage.html index 03d06b4806d..cd894c8c12e 100644 --- a/docs/articles/browser-storage.html +++ b/docs/articles/browser-storage.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/data-base.html b/docs/articles/data-base.html index 508efe23f45..1884199493b 100644 --- a/docs/articles/data-base.html +++ b/docs/articles/data-base.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/embedded-database.html b/docs/articles/embedded-database.html index f1fa829d5a7..af26834d256 100644 --- a/docs/articles/embedded-database.html +++ b/docs/articles/embedded-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/flutter-database.html b/docs/articles/flutter-database.html index 06d074ba5b6..23db3651eea 100644 --- a/docs/articles/flutter-database.html +++ b/docs/articles/flutter-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/frontend-database.html b/docs/articles/frontend-database.html index 1701b2654a7..a66318c672d 100644 --- a/docs/articles/frontend-database.html +++ b/docs/articles/frontend-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/in-memory-nosql-database.html b/docs/articles/in-memory-nosql-database.html index ef3769b3322..a0c7eceb0c9 100644 --- a/docs/articles/in-memory-nosql-database.html +++ b/docs/articles/in-memory-nosql-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/ionic-database.html b/docs/articles/ionic-database.html index 20018fb6fff..aef5a14ec23 100644 --- a/docs/articles/ionic-database.html +++ b/docs/articles/ionic-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/json-database.html b/docs/articles/json-database.html index a77066b45a3..38e7af15055 100644 --- a/docs/articles/json-database.html +++ b/docs/articles/json-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/localstorage.html b/docs/articles/localstorage.html index ee102d70cca..15f4e25b218 100644 --- a/docs/articles/localstorage.html +++ b/docs/articles/localstorage.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/mobile-database.html b/docs/articles/mobile-database.html index 29a6894c358..72b374b2df9 100644 --- a/docs/articles/mobile-database.html +++ b/docs/articles/mobile-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/progressive-web-app-database.html b/docs/articles/progressive-web-app-database.html index 4833a17f132..d95a75f1777 100644 --- a/docs/articles/progressive-web-app-database.html +++ b/docs/articles/progressive-web-app-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/react-database.html b/docs/articles/react-database.html index b9c4876eee1..2d503dc4c6c 100644 --- a/docs/articles/react-database.html +++ b/docs/articles/react-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/realtime-database.html b/docs/articles/realtime-database.html index b66f731aa55..89d592923ae 100644 --- a/docs/articles/realtime-database.html +++ b/docs/articles/realtime-database.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/articles/websockets-sse-polling-webrtc-webtransport.html b/docs/articles/websockets-sse-polling-webrtc-webtransport.html index f02352898a5..04db35a353c 100644 --- a/docs/articles/websockets-sse-polling-webrtc-webtransport.html +++ b/docs/articles/websockets-sse-polling-webrtc-webtransport.html @@ -15,8 +15,8 @@ - - + + diff --git a/docs/assets/js/0e268d20.373a368c.js b/docs/assets/js/0e268d20.373a368c.js new file mode 100644 index 00000000000..3324be206f2 --- /dev/null +++ b/docs/assets/js/0e268d20.373a368c.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[2584],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Kr,C3:()=>zr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},d=new Set(["__proto__","prototype","constructor"]),h=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(d.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(d.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!h.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(d.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function y(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function j(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=j(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])}((0,w.A)(Error)),_=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=j(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}])}((0,w.A)(TypeError));function I(e,t){return new D(e,k.tunnelErrorMessage(e),t)}function R(e,t){return new _(e,k.tunnelErrorMessage(e),t)}function S(e){return!(!e||409!==e.status)&&e}var E={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var C=/\./g,P="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=y(t,e);if(void 0===r)throw I("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function F(e){var t=q((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=Q,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var Q={type:"object",properties:{lwt:{type:"number",minimum:$,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=q(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",z="changes",K="attachments",U="dexie",Z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=q(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),le=r(3337),ue=String.fromCharCode(65535),de=Number.MIN_SAFE_INTEGER;function he(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:l?de:ue,endKey:a?ue:de,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=de),void 0===i.endKey&&(i.endKey=ue),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),l&&!i.inclusiveStart&&(l=!1),a&&!i.inclusiveEnd&&(a=!1),i})),d=u.map((e=>e.startKey)),h=u.map((e=>e.endKey)),m={index:e,startKeys:d,endKeys:h,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ye(e,t.selector,d,h)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==de&&e!==ue));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==ue&&e!==de));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,s=m)})),!s)throw I("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ye(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&s.add(o),"$eq"!==u){if(i.length>0)return!1;i.push(u)}}var d=[],h=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var y=f[0];if(y&&h.add(m),"$eq"!==y){if(d.length>0)return!1;d.push(y)}}var v=0;for(var g of e){for(var b of[s,h]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[v]!==a[v]&&s.size>0&&h.size>0)return!1;v++}return!0}var ve=r(744),ge=r(2779),be=r(1692),xe=r(4903),we=r(7705),ke=r(2403),je=r(6776),De=r(6950),_e=r(6823),Ie=!1;function Re(e){return Ie||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:xe.xF,$project:xe.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:we.a6,$eq:ke.XV,$elemMatch:De.Jy,$exists:_e.P,$gt:ke.MR,$gte:ke.fy,$in:ke.oZ,$lt:ke.NV,$lte:ke.Q_,$ne:ke.C5,$nin:ke.GU,$mod:je.Pp,$nor:we.q3,$not:we.En,$or:we.sU,$regex:je.WP,$size:De.Ig,$type:_e.T}),Ie=!0),new be.X(e)}function Se(e,t){var r=q(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ee(e,t){if(!t.sort)throw I("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Pe(e){return e===de?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Ne(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ae(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=Ce(e.schema,t.query));var c=Ne(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),l=s.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),s.sortSatisfiedByIndex&&u.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var d=Ee(e.schema,t.query);u=u.sort(d)}return{documents:u=u.slice(n,i)}}function $e(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Be(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?$e(r).height:0)+1+"-"+e}var Te="_rxdb_internal";async function qe(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Fe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:k.deepFreezeWhenDevMode(a),previousDocumentData:k.deepFreezeWhenDevMode(n)}}function Qe(e,t,r,a){if(a)throw 409===a.status?I("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?I("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function ze(e){var t=s(e);return t._meta=s(e._meta),t}function Ke(e,t,r){k.deepFreezeWhenDevMode(r);var a=q(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),k.isDevMode()){i=T(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw I("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw I("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:B(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(3561),Ze=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ze.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ue.X)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),u()};var d=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),d()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=q(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw I("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,l=[],u=[],d=[],h={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=h.events,p=[],f=[],y=[],v=r.size>0,g=a.length,b=function(){var e,n=a[x],h=n.document,g=n.previous,b=h[t],w=h._deleted,k=g&&g._deleted,j=void 0;if(v&&(j=r.get(b)),j){var D=j._rev;if(!g||g&&D!==g._rev){var _={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:j};return d.push(_),1}var R=c?We(n):n;c&&(w?g&&Object.keys(g._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.ZN)(g)._attachments[e].digest})})):(Object.entries(h._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:j,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(h._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&y.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?d.push(e):(c?(u.push(We(R)),s&&s(h)):(u.push(R),s&&s(h)),o=R);var S=null,E=null,C=null;if(k&&!w)C="INSERT",S=c?He(h):h;else if(!g||k||w){if(!w)throw I("SNH",{args:{writeRow:n}});C="DELETE",S=(0,le.ZN)(h),E=g}else C="UPDATE",S=c?He(h):h,E=g;var P={documentId:b,documentData:S,previousDocumentData:E,operation:C};m.push(P)}else{var O=!!w;if(c&&Object.entries(h._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},d.push(e))})),e||(c?(l.push(We(n)),i&&i(h)):(l.push(n),i&&i(h)),o=n),!O){var N={documentId:b,operation:"INSERT",documentData:c?He(h):h,previousDocumentData:c&&g?He(g):g};m.push(N)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,le.ZN)(r)).eventBulk.events.length>0){var s=(0,le.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ae(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=Ne(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ae(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(Z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[z]:"++sequence, id",[K]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[K],booleanIndexes:se(n)}})();return Z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw I("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw I("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw I("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=q(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw I("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}])}();function lt(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=F(e);a=function(e){return o(e,!0)}(a),k.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ut=r(7708),dt=r(8146),ht=r(3356),mt=r(5520),pt=r(8609),ft=r(1753);function yt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=N(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 ")}function vt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=$e(i._rev).height,n.forEach((e=>{var t=$e(e._rev).height;t>s&&(i=e,s=t)})),i),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(d){u.reject(d),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(d){return void a.forEach((e=>e.reject(d)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=S(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.ZN)(o.documentInDb),(0,le.ZN)(c).unshift(e)}))}else{var l=I("COL20",{name:E[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={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.$.pipe((0,ut.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,dt.p)((e=>e.documentId===this.primary)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.t)(le.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(k.isDevMode()){if(e.includes(".item."))throw I("DOC1",{path:e});if(e===this.primaryPath)throw I("DOC2");if(this.collection.schema.finalFields.includes(e))throw I("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw I("DOC4",{path:e})}return this.$.pipe((0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.$A;if(!t)throw I("DOC5",{path:e});if(!t.ref)throw I("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw I("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=y(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return k.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(A(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(A(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(A(e+"."+o))}return r.get(A(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return k.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,k.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw yt("update")},incrementalUpdate(e){throw yt("update")},updateCRDT(e){throw yt("crdt")},putAttachment(){throw yt("attachments")},getAttachment(){throw yt("attachments")},allAttachments(){throw yt("attachments")},get allAttachments$(){throw yt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw I("DOC11",{id:this.primary,document:this});await kt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Qe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(I("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Qe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw I("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function kt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),k.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var jt=r(2198),Dt=r(511),_t=r(4157),It=r(2442),Rt=r(6114);function St(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Et=new WeakMap;function Ct(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Et,e,(()=>{var t=e.collection,r=Se(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ee(t.schema.jsonSchema,r),i=Ce(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:St(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.ZN)(e._result).docsData.slice(0),n=(0,le.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:k.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Rt.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Rt.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var Pt=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Nt(e){return e.refCount$.observers.length}var At,$t,Bt=(At=100,$t=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Ot(t,e)))}}),Mt=new WeakSet;var Tt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=vt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=k.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],l=Be(o._rev),u=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),d=u.byRev,h=d.get(l),m=h?h.deref():void 0;return m||(o=n(o),m=s(o),d.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Be(e.revision)})})))}))))),m};return o}(this))}}])}();function qt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Ft=function(){return(0,b.A)((function(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=qt(this.collection._docCache,t)}),[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Ft(this.collection,e,e.length);this._result=t}else this._result=new Ft(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw I("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw I("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,Dt._)(this.$))).then((t=>{if(!t&&e)throw I("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Se(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw yt("update")},t.where=function(e){throw yt("query-builder")},t.sort=function(e){throw yt("query-builder")},t.skip=function(e){throw yt("query-builder")},t.limit=function(e){throw yt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,ht.Z)(null),(0,It.Z)((()=>Kt(this))),(0,ut.T)((()=>this._result)),(0,pt.t)(le.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,le.ZN)(t).time))),(0,dt.p)((e=>!!e)),(0,ut.T)((e=>{var t=(0,le.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,_t.h)(e,this.refCount$.pipe((0,dt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Ce(0,Se(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}])}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,ft.dY)().then((()=>(0,ft.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function zt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||zt(e)?ft.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||zt(e))return ft.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,le.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=Ct(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:k.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var u=o.map((e=>{var t=ze(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,dt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>wt(sr(e))))}(e),e,k.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],dr=!1,hr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Bt),void 0===u&&(u={}),void 0===d&&(d=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Pt,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=d,function(e){if(dr)return;dr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+N(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>kt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,dt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,It.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Tt(this.schema.primaryPath,this.$.pipe((0,dt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Fe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.em},t.cleanup=function(e){throw yt("cleanup")},t.migrationNeeded=function(){throw yt("migration-schema")},t.getMigrationState=function(){throw yt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Qe(this,e[this.schema.primaryPath],e,r),(0,le.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=qt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw I("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));i.push(l)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Qe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw I("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw I("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw I("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.insertCRDT=function(e){throw yt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!ur.includes(t))throw I("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw I("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.em;var i=n.series.map((e=>()=>e(r,a)));return(0,ft.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,dt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,dt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,dt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}])}();var mr=r(7635),pr=r(1007);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.sc)(e))},yr=r(5525),vr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d,h){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,It.Z)((e=>e.events))),this.storageToken=ft.Dr,this.storageTokenDocument=ft.Dr,this.emittedEventBulkIds=new yr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=d,this.reactivity=h,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:B(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,le.ZN)(n.error[0]);if(i.isError&&S(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw I("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw I("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,le.ZN)(o)}var c,l;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw I("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await qe(this.internalStore,Gt(tr(e,t),Zt));if(!r)throw I("SNH",{name:e,schema:t});var a=ze(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[i])throw I("DB3",{name:i});var d=tr(i,l),h={id:Gt(d,Zt),key:d,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:B(),_rev:"",_attachments:{}};a.push({document:h});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=s(o);p.database=this,p.name=i,st("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw I("DB12",{database:this.name,writeError:e});var a=(0,le.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw I("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,le.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:d=!1,cacheReplacementPolicy:h=Bt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:k.isDevMode()};return st("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new hr(t,r,a,e,n,i,c,l,u,h,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.em;return s&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:l,options:u,cacheReplacementPolicy:h,localDocuments:d,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw yt("json-dump")},t.addState=function(e){throw yt("state")},t.importJSON=function(e){throw yt("json-dump")},t.backup=function(e){throw yt("backup")},t.leaderElector=function(){throw yt("leader-election")},t.isLeader=function(){throw yt("leader-election")},t.waitForLeadership=function(){throw yt("leader-election")},t.migrationStates=function(){throw yt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>vr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}])}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Te,schema:Jt,options:a,multiInstance:n,password:i,devMode:k.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:d=!1,hashFunction:h=fr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}),o||function(e,t){var r=t.name+"|"+e;if(vr.has(r))throw I("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),vr.add(t.name+"|"+a);var p=O(10);return br(p,t,a,r,i,n).catch((e=>{throw vr.delete(t.name+"|"+a),e})).then((e=>{var f=new gr(a,p,t,r,n,i,s,c,e,h,l,u,m);return ot("createRxDatabase",{database:f,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}}).then((()=>f))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Wt.prototype,RxCollection:hr.prototype,RxDatabase:gr.prototype},kr=new Set,jr=new Set;var Dr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.A)(t,e),t}(wt()),_r={get isLocal(){return!0},get allAttachments$(){throw I("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,dt.p)((e=>e.documentId===this.primary)),(0,dt.p)((e=>e.isLocal)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.t)(le.bz))},get $$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=y(this._data,e);return t=k.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,k.isDevMode()){if(e.includes(".item."))throw I("LD3",{objPath:e});if(e===this.primaryPath)throw I("LD4")}return this.$.pipe((0,ut.T)((e=>e._data)),(0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){return Sr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:B(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Ir=!1,Rr=()=>{if(!Ir){Ir=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(_r,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(_r,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>_r[e]=(e=>()=>{throw I("LD6",{functionName:e})})(e)))}};function Sr(e){var t=e.parent;return t instanceof gr?t:t.database}var Er=new WeakMap,Cr=new WeakMap;function Pr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Nr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Mr);var n=new Tt("id",e.$.pipe((0,dt.p)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new Dr(e.id,e,t);return Object.setPrototypeOf(r,_r),r.prototype=_r,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Fe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw I("LD8",{database:r.name,collection:a})}return t}function Nr(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Br(a),schema:Mr,options:n,multiInstance:i,devMode:k.isDevMode()})}function Ar(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function $r(e,t,r){var a=O(10),n=await Nr(a,e,t,r,{},!1);await n.remove()}function Br(e){return"plugin-local-documents-"+e}var Mr=F({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Tr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:B(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function qr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):qe(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Fr(e){return this.$.pipe((0,ht.Z)(null),(0,It.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,It.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,dt.p)((e=>e.use)),(0,ut.T)((e=>e.doc)))}var Qr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr},RxDatabase:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Pr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Pr(e.collection)}},preDestroyRxDatabase:{after:e=>Ar(e)},postDestroyRxCollection:{after:e=>Ar(e)},postRemoveRxDatabase:{after:e=>$r(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>$r(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function zr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:kr}),!kr.has(e)){if(jr.has(e.name))throw I("PL3",{name:e.name,plugin:e});if(kr.add(e),jr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(k,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Qr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Kr=["#e6008d","#8d2089","#5f2688"]},1527:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{h:()=>a})},5607:(e,t,r)=>{r.r(t),r.d(t,{FORM_VALUE_DOCUMENT_ID:()=>v,default:()=>g});var a=r(4586),n=r(1595),i=r(5260),s=r(6540),o=r(3337),c=r(7810);const l=[{name:"Antigua and Barbuda",code:"AG",salary:49527},{name:"Argentina",code:"AR",salary:17158},{name:"Australia",code:"AU",salary:76036},{name:"Austria",code:"AT",salary:59383},{name:"Bahamas",code:"BS",salary:62024},{name:"Belarus",code:"BY",salary:5749},{name:"Belgium",code:"BE",salary:63749},{name:"Bermuda",code:"BM",salary:86590},{name:"Bosnia and Herzegovina",code:"BA",salary:11992},{name:"Brazil",code:"BR",salary:26464},{name:"Bulgaria",code:"BG",salary:23384},{name:"Cambodia",code:"KH",salary:18e3},{name:"Canada",code:"CA",salary:71554},{name:"Chile",code:"CL",salary:31073},{name:"China",code:"CN",salary:40611},{name:"Colombia",code:"CO",salary:12894},{name:"Costa Rica",code:"CR",salary:40256},{name:"Croatia",code:"HR",salary:22566},{name:"Czech Republic",code:"CZ",salary:33760},{name:"Denmark",code:"DK",salary:68778},{name:"Ecuador",code:"EC",salary:35016},{name:"Egypt",code:"EG",salary:7758},{name:"Estonia",code:"EE",salary:26728},{name:"Finland",code:"FI",salary:64198},{name:"France",code:"FR",salary:58137},{name:"Georgia",code:"GE",salary:40315},{name:"Germany",code:"DE",salary:72138},{name:"Greece",code:"GR",salary:36824},{name:"Guatemala",code:"GT",salary:49612},{name:"Holy See (Vatican City State)",code:"VA",salary:51474},{name:"Hong Kong",code:"HK",salary:71970},{name:"Hungary",code:"HU",salary:22341},{name:"Iceland",code:"IS",salary:66512},{name:"India",code:"IN",salary:35420},{name:"Indonesia",code:"ID",salary:20978},{name:"Iraq",code:"IQ",salary:21029},{name:"Ireland",code:"IE",salary:66281},{name:"Israel",code:"IL",salary:57466},{name:"Italy",code:"IT",salary:50900},{name:"Jamaica",code:"JM",salary:21048},{name:"Japan",code:"JP",salary:57793},{name:"Kazakhstan",code:"KZ",salary:12243},{name:"Republic of Korea",code:"KR",salary:45957},{name:"Latvia",code:"LV",salary:26728},{name:"Luxembourg",code:"LU",salary:84663},{name:"Malaysia",code:"MY",salary:26117},{name:"Malta",code:"MT",salary:41971},{name:"Mexico",code:"MX",salary:24050},{name:"Morocco",code:"MA",salary:17903},{name:"Netherlands",code:"NL",salary:62661},{name:"New Zealand",code:"NZ",salary:63948},{name:"Norway",code:"NO",salary:69498},{name:"Pakistan",code:"PK",salary:9066},{name:"Panama",code:"PA",salary:39143},{name:"Peru",code:"PE",salary:17469},{name:"Philippines",code:"PH",salary:11088},{name:"Poland",code:"PL",salary:30236},{name:"Portugal",code:"PT",salary:37959},{name:"Romania",code:"RO",salary:22319},{name:"Russian Federation",code:"RU",salary:20492},{name:"Saudi Arabia",code:"SA",salary:47336},{name:"Singapore",code:"SG",salary:66023},{name:"Slovakia",code:"SK",salary:29650},{name:"South Africa",code:"ZA",salary:40336},{name:"Spain",code:"ES",salary:47819},{name:"Sweden",code:"SE",salary:49361},{name:"Switzerland",code:"CH",salary:92820},{name:"Taiwan",code:"TW",salary:47737},{name:"Thailand",code:"TH",salary:21772},{name:"Turkey",code:"TR",salary:8788},{name:"Ukraine",code:"UA",salary:14139},{name:"United Arab Emirates",code:"AE",salary:66381},{name:"United Kingdom",code:"GB",salary:61188},{name:"United States",code:"US",salary:91935},{name:"Uruguay",code:"UY",salary:23754},{name:"Vietnam",code:"VN",salary:19058}],u={browser:.4,native:.4,performance:.35,sourcecode:0,perpetual:0},d=.05;var h=r(1527),m=r(2658),p=r(2303),f=r(4848);function y(e){let{children:t,fallback:r}=e;return(0,p.A)()?(0,f.jsx)(f.Fragment,{children:t?.()}):r??null}const v="premium-price-form-value";function g(){const{siteConfig:e}=(0,a.A)(),t=(0,p.A)();return(0,s.useEffect)((()=>{t&&window.trigger("open_pricing_page",1),(async()=>{if(!t||!(0,m.IA)())return;const e=await(0,m.C3)(),r=await e.getLocal(v);r&&(console.log("formValueDoc:"),console.dir(r),b("home-country",r._data.data.homeCountry),b("company-size",r._data.data.companySize),b("project-amount",r._data.data.projectAmount),b("license-period",r._data.data.licensePeriod),Object.keys(u).forEach((e=>{b("package-"+e,!1)})),r._data.data.packages.forEach((e=>{b("package-"+e,!0)})),document.getElementById("price-calculator-submit").click())})()})),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.A,{children:(0,f.jsx)("body",{className:"homepage"})}),(0,f.jsx)(n.A,{title:`Premium Plugins - ${e.title}`,description:"RxDB plugins for professionals. FAQ, pricing and license",children:(0,f.jsxs)("main",{children:[(0,f.jsx)("div",{className:"block first",children:(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:[(0,f.jsx)("b",{className:"underline",children:"RxDB"})," Premium Plugins"]}),(0,f.jsxs)("p",{style:{width:"80%"},children:["RxDB's premium plugins offer advanced features and optimizations that enhance application ",(0,f.jsx)("b",{children:"performance"})," ","and are backed by dedicated support and regular updates. Using the premium plugins is recommended for users that use RxDB in a professional context."]}),(0,f.jsxs)("div",{className:"premium-blocks",children:[(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage IndexedDB"}),(0,f.jsxs)("p",{children:["A storage for browsers based on ",(0,f.jsx)("b",{children:"IndexedDB"}),". Has the best latency on writes and smallest build size."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage OPFS"}),(0,f.jsxs)("p",{children:["Currently the RxStorage with best data throughput that can be used in the browser. Based on the ",(0,f.jsx)("b",{children:"OPFS File System Access API"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SQLite"}),(0,f.jsxs)("p",{children:["A fast storage based on ",(0,f.jsx)("b",{children:"SQLite"})," for Servers and Hybrid Apps. Can be used with"," ",(0,f.jsx)("b",{children:"Node.js"}),", ",(0,f.jsx)("b",{children:"Electron"}),", ",(0,f.jsx)("b",{children:"React Native"}),", ",(0,f.jsx)("b",{children:"Capacitor"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SharedWorker"}),(0,f.jsxs)("p",{children:["A RxStorage wrapper to run the storage inside of a SharedWorker which improves the performance by taking CPU load away from the main process. Used in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Worker"}),(0,f.jsx)("p",{children:"A RxStorage wrapper to run the storage inside of a Worker which improves the performance by taking CPU load away from the main process."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Sharding"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that improves performance by applying the sharding technique."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Memory Synced"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that creates a synced in-memory copy which improves performance for the initial page load time and write & read operations."})]})})}),(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Query Optimizer"}),(0,f.jsx)("p",{children:"A tool to find the best index for a given query. You can use this during build time to find the best index and then use that index during runtime."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Localstorage Meta Optimizer"}),(0,f.jsxs)("p",{children:["A wrapper around any other storage which optimizes the initial page load one by using localstorage for meta key-value document. Only works in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"WebCrypto Encryption"}),(0,f.jsx)("p",{children:"A faster and more secure encryption plugin based on the Web Crypto API."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Filesystem Node"}),(0,f.jsxs)("p",{children:["A fast RxStorage based on the ",(0,f.jsx)("b",{children:"Node.js"})," Filesystem."]})]})})}),(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Logger"}),(0,f.jsx)("p",{children:"A logging plugin useful to debug performance problems and for monitoring with Application Performance Monitoring (APM) tools like Bugsnag, Datadog, Elastic, Sentry and others"})]})})})]})]})}),(0,f.jsx)("div",{className:"block dark",id:"faq",children:(0,f.jsxs)("div",{className:"content centered premium-faq",children:[(0,f.jsxs)("h2",{children:["F.A.Q. ",(0,f.jsx)("b",{children:"(click to toggle)"})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Do I need the Premium Plugins?"}),"RxDB Core is open source and many use cases can be implemented with the Open Core part of RxDB. There are many"," ",(0,f.jsx)("a",{href:"/rx-storage.html",target:"_blank",children:"RxStorage"})," ","options and all core plugins that are required for replication, schema validation, encryption and so on, are totally free. As soon as your application is more then a side project you can consider using the premium plugins as an easy way to improve your applications performance and reduce the build size.",(0,f.jsx)("br",{}),"The main benefit of the Premium Plugins is ",(0,f.jsx)("b",{children:"performance"}),". The Premium RxStorage implementations have a better performance so reading and writing data is much faster especially on low-end devices. You can find a performance comparison"," ",(0,f.jsx)("a",{href:"/rx-storage-performance.html",target:"_blank",children:"here"}),". Also there are additional Premium Plugins that can be used to further optimize the performance of your application like the"," ",(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})," ","or the"," ",(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"Sharding"})," ","plugin."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not for free?"}),"The development of RxDB started in 2016 and after all these years it became clear that big implementation and improvement steps will not be done by the RxDB community. While the community submits valuable pull requests, they are mostly small improvements or bugfixes for specific edge case. Big rewrites and optimizations that require a big effort have only be done by the RxDB maintainer.",(0,f.jsx)("br",{}),"Selling RxDB Premium ensures that there will be always an incentive for someone to add features, keep everything up to date and to further improve and optimize the codebase. This gives the user the confidence that RxDB is a ",(0,f.jsx)("b",{children:"future proof"})," tech stack to build on which lets RxDB stand out compared to similar technologies."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is there no free trial period?"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:"RxDB is written in JavaScript and the code of the Premium Plugins does not contain any tracking or measurement code that would send information from your application to our servers in production mode. As soon as someone has the code on his computer, the maintainer has no chance to really ensure that after a free trial period the code is no longer used and deleted."}),(0,f.jsxs)("li",{children:["Before you can use the Premium Plugins you have to debate and sign a license agreement with the maintainer. This is a sophisticated process that creates overhead which distracts the maintainer from writing RxDB code. So handling trial period users is just not manageable. For this reason there is also no monthly subscriptions. Premium access must be paid ",(0,f.jsx)("b",{children:"per year"}),"."]})]})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not cheaper?"}),"The price of the Premium Plugins is chosen in way that ensures that there can be always one person that develops RxDB ",(0,f.jsx)("b",{children:"full time"}),". Compared to other JavaScript frameworks and developer tools, RxDB satisfies an edge use case for people that want to store data inside of their application on the users device. Most web developers do not need to do that and rely on the traditional client-server stack. So RxDB cannot be sold to that many people which increases the price."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I install/build the premium plugins in my CI?"}),(0,f.jsx)("b",{children:"Yes"})," you can safely install and use the Premium Plugins in your CI without additional payment."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Which payment methods are accepted?"}),(0,f.jsx)("b",{children:"Stripe.com"})," is used as payment processor so most known payment options like credit card, PayPal, SEPA transfer and others are available. A list of all options can be found"," ",(0,f.jsx)("a",{href:"https://stripe.com/docs/payments/payment-methods/overview",title:"stripe payment options",target:"_blank",children:"here"}),"."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I get a discount?"}),"Discounts are provided for people that have made a significant contribution to RxDB or one of RxDB's dependencies or to the Open Source Community overall. Also for private personal projects there is the option to solve one of the",(0,f.jsx)("a",{href:"https://github.com/pubkey/rxdb/blob/master/orga/premium-tasks.md",target:"_blank",children:"Premium Tasks"}),"to get 2 years access to the Premium Plugins."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Is there any tracking code inside of the premium plugins?"}),"No, the premium plugins themself do not contain any tracking code. When you build your application with RxDB and deploy it to production, it will not make requests from your users to any RxDB server."]})]})}),(0,f.jsxs)("div",{className:"block",children:[(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["RxDB Premium ",(0,f.jsx)("b",{className:"underline",children:"Price Calculator"})]}),(0,f.jsx)("div",{className:"price-calculator",children:(0,f.jsx)("div",{className:"price-calculator-inner",children:(0,f.jsxs)("form",{id:"price-calculator-form",children:[(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"home-country",children:"Company Home Country:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{list:"home-country",name:"home-country",pattern:"[A-Za-z \\-\\,]{2,}",required:!0,style:{width:"100%",maxWidth:240},autoComplete:"off",placeholder:"Company Home Country"}),(0,f.jsx)("datalist",{id:"home-country",children:l.sort(((e,t)=>e.name>=t.name?1:-1)).map(((e,t)=>(0,f.jsx)("option",{value:e.name,children:e.name},t)))})]})]}),(0,f.jsx)("br",{}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"company-size",children:"Company Size:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{type:"number",name:"company-size",min:1,max:1e6,required:!0,onKeyDown:()=>{const e=(0,o.ZN)(event);return 69!==e.keyCode&&189!==e.keyCode&&190!==e.keyCode},placeholder:"Company Size"}),(0,f.jsx)("div",{className:"suffix",children:"employee(s)"})]})]}),(0,f.jsxs)("div",{className:"packages",children:[(0,f.jsx)("h3",{children:"Packages:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-browser",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Browser Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:"RxStorage OPFS"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:"RxStorage IndexedDB"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:"RxStorage Worker"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:"WebCrypto Encryption"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-native",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Native Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:"RxStorage SQLite"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:"RxStorage Filesystem Node"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-performance",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Performance Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"RxStorage Sharding"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:"RxStorage Memory Synced"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:"RxStorage Shared Worker"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-utilities",type:"checkbox",className:"package-checkbox",defaultChecked:!0,disabled:!0}),(0,f.jsxs)("h4",{children:["Utilities Package ",(0,f.jsx)("b",{children:"always included"})]}),(0,f.jsx)("ul",{children:(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:"Logger"})})})]})}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("div",{className:"button",id:"price-calculator-submit",onClick:async()=>{(0,h.h)("calculate_premium_price",3);const e=(0,o.ZN)(document.getElementById("price-calculator-form"));if(!e.reportValidity())return void console.log("form not valid");const t=new FormData(e),r=Object.fromEntries(t.entries());console.log("formData:"),console.dir(r);const a=l.find((e=>e.name.toLowerCase()===r["home-country"].toLowerCase()));if(!a)return;const n=Object.entries(r).filter((e=>{let[t,r]=e;return t.startsWith("package-")})).map((e=>{let[t]=e;return(0,c.dG)(t.split("-"))})),i={companySize:parseInt(r["company-size"],10),teamSize:r["developer-count"],projectAmount:"1",licensePeriod:1,homeCountryCode:a.code,packages:n},s=function(e){if(console.log("calculatePrice:"),console.dir(e),"number"!=typeof e.licensePeriod)throw new Error("not a number "+typeof e.licensePeriod);const t=(0,o.ZN)(l.find((t=>t.code===e.homeCountryCode))).salary;let r=0;e.packages.forEach((e=>{const t=u[e];r+=t})),console.log("aimInPercent: "+r);let a=350+1.4*t*(r/100);if(2===e.packages.length&&(a*=.9),e.packages.length>2&&(a*=.8),e.companySize>1){let t=1+Math.pow(1*e.companySize-1,.45)/100*4.5;const r=6;t>r&&(t=r),console.log("input.companySize "+e.companySize+" - "+t),a*=t}if(e.packages.includes("sourcecode")){a*=1.75;const e=1520;a1200?100*Math.floor(a/100):50*Math.floor(a/50),{totalPrice:a}}(i);console.log("priceResult:"),console.log(JSON.stringify(s,null,4));const p=(0,o.ZN)(document.getElementById("price-calculator-result")),f=(0,o.ZN)(document.getElementById("total-per-project-per-month")),y=(e,t)=>{console.log("setPrice:"),console.dir(t),e.innerHTML=Math.ceil(t).toString()},g=s.totalPrice/i.licensePeriod;y(f,"infinity"!==i.projectAmount?g/parseInt(i.projectAmount,10)/12:0);const b=await(0,m.C3)();await b.upsertLocal(v,{companySize:r["company-size"],projectAmount:r["project-amount"],licensePeriod:r["license-period"],homeCountry:a.name,packages:n,price:s.totalPrice,formSubmitted:!1}),p.style.display="block"},children:"Estimate Price"})]})})}),(0,f.jsx)("div",{className:"price-calculator",style:{marginBottom:90},children:(0,f.jsxs)("div",{className:"price-calculator-inner",id:"price-calculator-result",style:{display:"none"},children:[(0,f.jsx)("h4",{children:"Estimated Price:"}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"inner",children:[(0,f.jsx)("span",{className:"price-label",children:"\u20ac"}),(0,f.jsx)("span",{id:"total-per-project-per-month",children:"84"}),(0,f.jsx)("span",{className:"per-month",children:"/month"}),(0,f.jsx)("span",{className:"clear"})]}),(0,f.jsx)("br",{}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"proceed-hint",children:["Fill out the ",(0,f.jsx)("b",{children:"form below \u2193"})," to proceed."]})]})})]}),(0,f.jsx)("div",{className:"block dark",id:"premium-request-form-block",children:(0,f.jsxs)("div",{className:"content centered premium-request",children:[(0,f.jsxs)("h2",{children:["Request Premium ",(0,f.jsx)("b",{className:"underline",children:"Form"})]}),(0,f.jsx)("p",{}),(0,f.jsx)(y,{fallback:(0,f.jsx)("span",{children:"Loading form iframe..."}),children:()=>(0,f.jsxs)("iframe",{id:"request-premium-form",src:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",children:["Your browser doesn't support iframes, ",(0,f.jsx)("a",{href:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",target:"_blank",rel:"nofollow",children:"go here"})]})})]})})]})]})})]})}function b(e,t){if(void 0===t)return;const r=document.querySelector("[name="+e+"]");r&&(r.type&&"checkbox"===r.type?r.checked=t:r.value=t)}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>l,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>u,dY:()=>a,em:()=>o,h$:()=>d,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function d(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/0e268d20.aead1a7b.js b/docs/assets/js/0e268d20.aead1a7b.js deleted file mode 100644 index 83eef96eab1..00000000000 --- a/docs/assets/js/0e268d20.aead1a7b.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[2584],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Kr,C3:()=>zr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},d=new Set(["__proto__","prototype","constructor"]),h=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(d.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(d.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!h.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(d.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function y(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function j(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=j(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,w.A)(Error)),_=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=j(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,w.A)(TypeError));function I(e,t){return new D(e,k.tunnelErrorMessage(e),t)}function R(e,t){return new _(e,k.tunnelErrorMessage(e),t)}function S(e){return!(!e||409!==e.status)&&e}var E={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var C=/\./g,P="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=y(t,e);if(void 0===r)throw I("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function F(e){var t=q((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=Q,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var Q={type:"object",properties:{lwt:{type:"number",minimum:$,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=q(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",z="changes",K="attachments",U="dexie",Z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=q(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),le=r(3337),ue=String.fromCharCode(65535),de=Number.MIN_SAFE_INTEGER;function he(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:l?de:ue,endKey:a?ue:de,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=de),void 0===i.endKey&&(i.endKey=ue),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),l&&!i.inclusiveStart&&(l=!1),a&&!i.inclusiveEnd&&(a=!1),i})),d=u.map((e=>e.startKey)),h=u.map((e=>e.endKey)),m={index:e,startKeys:d,endKeys:h,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ye(e,t.selector,d,h)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==de&&e!==ue));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==ue&&e!==de));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,s=m)})),!s)throw I("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ye(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&s.add(o),"$eq"!==u){if(i.length>0)return!1;i.push(u)}}var d=[],h=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var y=f[0];if(y&&h.add(m),"$eq"!==y){if(d.length>0)return!1;d.push(y)}}var v=0;for(var g of e){for(var b of[s,h]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[v]!==a[v]&&s.size>0&&h.size>0)return!1;v++}return!0}var ve=r(744),ge=r(2779),be=r(1692),xe=r(4903),we=r(7705),ke=r(2403),je=r(6776),De=r(6950),_e=r(6823),Ie=!1;function Re(e){return Ie||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:xe.xF,$project:xe.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:we.a6,$eq:ke.XV,$elemMatch:De.Jy,$exists:_e.P,$gt:ke.MR,$gte:ke.fy,$in:ke.oZ,$lt:ke.NV,$lte:ke.Q_,$ne:ke.C5,$nin:ke.GU,$mod:je.Pp,$nor:we.q3,$not:we.En,$or:we.sU,$regex:je.WP,$size:De.Ig,$type:_e.T}),Ie=!0),new be.X(e)}function Se(e,t){var r=q(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ee(e,t){if(!t.sort)throw I("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Pe(e){return e===de?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Ne(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ae(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=Ce(e.schema,t.query));var c=Ne(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),l=s.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),s.sortSatisfiedByIndex&&u.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var d=Ee(e.schema,t.query);u=u.sort(d)}return{documents:u=u.slice(n,i)}}function $e(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Be(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?$e(r).height:0)+1+"-"+e}var Te="_rxdb_internal";async function qe(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Fe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:k.deepFreezeWhenDevMode(a),previousDocumentData:k.deepFreezeWhenDevMode(n)}}function Qe(e,t,r,a){if(a)throw 409===a.status?I("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?I("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function ze(e){var t=s(e);return t._meta=s(e._meta),t}function Ke(e,t,r){k.deepFreezeWhenDevMode(r);var a=q(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),k.isDevMode()){i=T(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw I("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw I("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:B(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(3561),Ze=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ze.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ue.X)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),u()};var d=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),d()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=q(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw I("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,l=[],u=[],d=[],h={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=h.events,p=[],f=[],y=[],v=r.size>0,g=a.length,b=function(){var e,n=a[x],h=n.document,g=n.previous,b=h[t],w=h._deleted,k=g&&g._deleted,j=void 0;if(v&&(j=r.get(b)),j){var D=j._rev;if(!g||g&&D!==g._rev){var _={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:j};return d.push(_),1}var R=c?We(n):n;c&&(w?g&&Object.keys(g._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.ZN)(g)._attachments[e].digest})})):(Object.entries(h._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:j,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(h._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&y.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?d.push(e):(c?(u.push(We(R)),s&&s(h)):(u.push(R),s&&s(h)),o=R);var S=null,E=null,C=null;if(k&&!w)C="INSERT",S=c?He(h):h;else if(!g||k||w){if(!w)throw I("SNH",{args:{writeRow:n}});C="DELETE",S=(0,le.ZN)(h),E=g}else C="UPDATE",S=c?He(h):h,E=g;var P={documentId:b,documentData:S,previousDocumentData:E,operation:C};m.push(P)}else{var O=!!w;if(c&&Object.entries(h._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},d.push(e))})),e||(c?(l.push(We(n)),i&&i(h)):(l.push(n),i&&i(h)),o=n),!O){var N={documentId:b,operation:"INSERT",documentData:c?He(h):h,previousDocumentData:c&&g?He(g):g};m.push(N)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,le.ZN)(r)).eventBulk.events.length>0){var s=(0,le.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ae(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=Ne(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ae(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(Z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[z]:"++sequence, id",[K]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[K],booleanIndexes:se(n)}})();return Z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw I("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw I("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw I("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=q(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw I("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function lt(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=F(e);a=function(e){return o(e,!0)}(a),k.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ut=r(7708),dt=r(8146),ht=r(3356),mt=r(5520),pt=r(8609),ft=r(1753);function yt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=N(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 ")}function vt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=$e(i._rev).height,n.forEach((e=>{var t=$e(e._rev).height;t>s&&(i=e,s=t)})),i),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(d){u.reject(d),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(d){return void a.forEach((e=>e.reject(d)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=S(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.ZN)(o.documentInDb),(0,le.ZN)(c).unshift(e)}))}else{var l=I("COL20",{name:E[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={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.$.pipe((0,ut.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,dt.p)((e=>e.documentId===this.primary)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.t)(le.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(k.isDevMode()){if(e.includes(".item."))throw I("DOC1",{path:e});if(e===this.primaryPath)throw I("DOC2");if(this.collection.schema.finalFields.includes(e))throw I("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw I("DOC4",{path:e})}return this.$.pipe((0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.$A;if(!t)throw I("DOC5",{path:e});if(!t.ref)throw I("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw I("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=y(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return k.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(A(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(A(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(A(e+"."+o))}return r.get(A(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return k.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,k.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw yt("update")},incrementalUpdate(e){throw yt("update")},updateCRDT(e){throw yt("crdt")},putAttachment(){throw yt("attachments")},getAttachment(){throw yt("attachments")},allAttachments(){throw yt("attachments")},get allAttachments$(){throw yt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw I("DOC11",{id:this.primary,document:this});await kt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Qe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(I("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Qe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw I("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function kt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),k.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var jt=r(2198),Dt=r(511),_t=r(4157),It=r(2442),Rt=r(6114);function St(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Et=new WeakMap;function Ct(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Et,e,(()=>{var t=e.collection,r=Se(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ee(t.schema.jsonSchema,r),i=Ce(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:St(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.ZN)(e._result).docsData.slice(0),n=(0,le.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:k.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Rt.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Rt.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var Pt=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Nt(e){return e.refCount$.observers.length}var At,$t,Bt=(At=100,$t=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Ot(t,e)))}}),Mt=new WeakSet;var Tt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=vt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=k.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],l=Be(o._rev),u=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),d=u.byRev,h=d.get(l),m=h?h.deref():void 0;return m||(o=n(o),m=s(o),d.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Be(e.revision)})})))}))))),m};return o}(this))}}]),e}();function qt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Ft=function(){function e(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=qt(this.collection._docCache,t)}return(0,b.A)(e,[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Ft(this.collection,e,e.length);this._result=t}else this._result=new Ft(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw I("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw I("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,Dt._)(this.$))).then((t=>{if(!t&&e)throw I("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Se(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw yt("update")},t.where=function(e){throw yt("query-builder")},t.sort=function(e){throw yt("query-builder")},t.skip=function(e){throw yt("query-builder")},t.limit=function(e){throw yt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,ht.Z)(null),(0,It.Z)((()=>Kt(this))),(0,ut.T)((()=>this._result)),(0,pt.t)(le.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,le.ZN)(t).time))),(0,dt.p)((e=>!!e)),(0,ut.T)((e=>{var t=(0,le.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,_t.h)(e,this.refCount$.pipe((0,dt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Ce(0,Se(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,ft.dY)().then((()=>(0,ft.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function zt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||zt(e)?ft.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||zt(e))return ft.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,le.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=Ct(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:k.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var u=o.map((e=>{var t=ze(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,dt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>wt(sr(e))))}(e),e,k.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],dr=!1,hr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Bt),void 0===u&&(u={}),void 0===d&&(d=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Pt,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=d,function(e){if(dr)return;dr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+N(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>kt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,dt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,It.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Tt(this.schema.primaryPath,this.$.pipe((0,dt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Fe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.em},t.cleanup=function(e){throw yt("cleanup")},t.migrationNeeded=function(){throw yt("migration-schema")},t.getMigrationState=function(){throw yt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Qe(this,e[this.schema.primaryPath],e,r),(0,le.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=qt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw I("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));i.push(l)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Qe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw I("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw I("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw I("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.insertCRDT=function(e){throw yt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!ur.includes(t))throw I("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw I("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.em;var i=n.series.map((e=>()=>e(r,a)));return(0,ft.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,dt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,dt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,dt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7635),pr=r(1007);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.sc)(e))},yr=r(5525),vr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d,h){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,It.Z)((e=>e.events))),this.storageToken=ft.Dr,this.storageTokenDocument=ft.Dr,this.emittedEventBulkIds=new yr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=d,this.reactivity=h,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:B(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,le.ZN)(n.error[0]);if(i.isError&&S(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw I("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw I("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,le.ZN)(o)}var c,l;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw I("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await qe(this.internalStore,Gt(tr(e,t),Zt));if(!r)throw I("SNH",{name:e,schema:t});var a=ze(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[i])throw I("DB3",{name:i});var d=tr(i,l),h={id:Gt(d,Zt),key:d,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:B(),_rev:"",_attachments:{}};a.push({document:h});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=s(o);p.database=this,p.name=i,st("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw I("DB12",{database:this.name,writeError:e});var a=(0,le.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw I("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,le.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:d=!1,cacheReplacementPolicy:h=Bt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:k.isDevMode()};return st("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new hr(t,r,a,e,n,i,c,l,u,h,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.em;return s&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:l,options:u,cacheReplacementPolicy:h,localDocuments:d,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw yt("json-dump")},t.addState=function(e){throw yt("state")},t.importJSON=function(e){throw yt("json-dump")},t.backup=function(e){throw yt("backup")},t.leaderElector=function(){throw yt("leader-election")},t.isLeader=function(){throw yt("leader-election")},t.waitForLeadership=function(){throw yt("leader-election")},t.migrationStates=function(){throw yt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>vr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Te,schema:Jt,options:a,multiInstance:n,password:i,devMode:k.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:d=!1,hashFunction:h=fr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}),o||function(e,t){var r=t.name+"|"+e;if(vr.has(r))throw I("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),vr.add(t.name+"|"+a);var p=O(10);return br(p,t,a,r,i,n).catch((e=>{throw vr.delete(t.name+"|"+a),e})).then((e=>{var f=new gr(a,p,t,r,n,i,s,c,e,h,l,u,m);return ot("createRxDatabase",{database:f,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}}).then((()=>f))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Wt.prototype,RxCollection:hr.prototype,RxDatabase:gr.prototype},kr=new Set,jr=new Set;var Dr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.A)(t,e),t}(wt()),_r={get isLocal(){return!0},get allAttachments$(){throw I("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,dt.p)((e=>e.documentId===this.primary)),(0,dt.p)((e=>e.isLocal)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.t)(le.bz))},get $$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=y(this._data,e);return t=k.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,k.isDevMode()){if(e.includes(".item."))throw I("LD3",{objPath:e});if(e===this.primaryPath)throw I("LD4")}return this.$.pipe((0,ut.T)((e=>e._data)),(0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){return Sr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:B(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Ir=!1,Rr=()=>{if(!Ir){Ir=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(_r,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(_r,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>_r[e]=(e=>()=>{throw I("LD6",{functionName:e})})(e)))}};function Sr(e){var t=e.parent;return t instanceof gr?t:t.database}var Er=new WeakMap,Cr=new WeakMap;function Pr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Nr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Mr);var n=new Tt("id",e.$.pipe((0,dt.p)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new Dr(e.id,e,t);return Object.setPrototypeOf(r,_r),r.prototype=_r,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Fe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw I("LD8",{database:r.name,collection:a})}return t}function Nr(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Br(a),schema:Mr,options:n,multiInstance:i,devMode:k.isDevMode()})}function Ar(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function $r(e,t,r){var a=O(10),n=await Nr(a,e,t,r,{},!1);await n.remove()}function Br(e){return"plugin-local-documents-"+e}var Mr=F({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Tr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:B(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function qr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):qe(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Fr(e){return this.$.pipe((0,ht.Z)(null),(0,It.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,It.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,dt.p)((e=>e.use)),(0,ut.T)((e=>e.doc)))}var Qr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr},RxDatabase:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Pr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Pr(e.collection)}},preDestroyRxDatabase:{after:e=>Ar(e)},postDestroyRxCollection:{after:e=>Ar(e)},postRemoveRxDatabase:{after:e=>$r(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>$r(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function zr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:kr}),!kr.has(e)){if(jr.has(e.name))throw I("PL3",{name:e.name,plugin:e});if(kr.add(e),jr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(k,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Qr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Kr=["#e6008d","#8d2089","#5f2688"]},1527:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{h:()=>a})},5607:(e,t,r)=>{r.r(t),r.d(t,{FORM_VALUE_DOCUMENT_ID:()=>v,default:()=>g});var a=r(4586),n=r(1595),i=r(5260),s=r(6540),o=r(3337),c=r(7810);const l=[{name:"Antigua and Barbuda",code:"AG",salary:49527},{name:"Argentina",code:"AR",salary:17158},{name:"Australia",code:"AU",salary:76036},{name:"Austria",code:"AT",salary:59383},{name:"Bahamas",code:"BS",salary:62024},{name:"Belarus",code:"BY",salary:5749},{name:"Belgium",code:"BE",salary:63749},{name:"Bermuda",code:"BM",salary:86590},{name:"Bosnia and Herzegovina",code:"BA",salary:11992},{name:"Brazil",code:"BR",salary:26464},{name:"Bulgaria",code:"BG",salary:23384},{name:"Cambodia",code:"KH",salary:18e3},{name:"Canada",code:"CA",salary:71554},{name:"Chile",code:"CL",salary:31073},{name:"China",code:"CN",salary:40611},{name:"Colombia",code:"CO",salary:12894},{name:"Costa Rica",code:"CR",salary:40256},{name:"Croatia",code:"HR",salary:22566},{name:"Czech Republic",code:"CZ",salary:33760},{name:"Denmark",code:"DK",salary:68778},{name:"Ecuador",code:"EC",salary:35016},{name:"Egypt",code:"EG",salary:7758},{name:"Estonia",code:"EE",salary:26728},{name:"Finland",code:"FI",salary:64198},{name:"France",code:"FR",salary:58137},{name:"Georgia",code:"GE",salary:40315},{name:"Germany",code:"DE",salary:72138},{name:"Greece",code:"GR",salary:36824},{name:"Guatemala",code:"GT",salary:49612},{name:"Holy See (Vatican City State)",code:"VA",salary:51474},{name:"Hong Kong",code:"HK",salary:71970},{name:"Hungary",code:"HU",salary:22341},{name:"Iceland",code:"IS",salary:66512},{name:"India",code:"IN",salary:35420},{name:"Indonesia",code:"ID",salary:20978},{name:"Iraq",code:"IQ",salary:21029},{name:"Ireland",code:"IE",salary:66281},{name:"Israel",code:"IL",salary:57466},{name:"Italy",code:"IT",salary:50900},{name:"Jamaica",code:"JM",salary:21048},{name:"Japan",code:"JP",salary:57793},{name:"Kazakhstan",code:"KZ",salary:12243},{name:"Republic of Korea",code:"KR",salary:45957},{name:"Latvia",code:"LV",salary:26728},{name:"Luxembourg",code:"LU",salary:84663},{name:"Malaysia",code:"MY",salary:26117},{name:"Malta",code:"MT",salary:41971},{name:"Mexico",code:"MX",salary:24050},{name:"Morocco",code:"MA",salary:17903},{name:"Netherlands",code:"NL",salary:62661},{name:"New Zealand",code:"NZ",salary:63948},{name:"Norway",code:"NO",salary:69498},{name:"Pakistan",code:"PK",salary:9066},{name:"Panama",code:"PA",salary:39143},{name:"Peru",code:"PE",salary:17469},{name:"Philippines",code:"PH",salary:11088},{name:"Poland",code:"PL",salary:30236},{name:"Portugal",code:"PT",salary:37959},{name:"Romania",code:"RO",salary:22319},{name:"Russian Federation",code:"RU",salary:20492},{name:"Saudi Arabia",code:"SA",salary:47336},{name:"Singapore",code:"SG",salary:66023},{name:"Slovakia",code:"SK",salary:29650},{name:"South Africa",code:"ZA",salary:40336},{name:"Spain",code:"ES",salary:47819},{name:"Sweden",code:"SE",salary:49361},{name:"Switzerland",code:"CH",salary:92820},{name:"Taiwan",code:"TW",salary:47737},{name:"Thailand",code:"TH",salary:21772},{name:"Turkey",code:"TR",salary:8788},{name:"Ukraine",code:"UA",salary:14139},{name:"United Arab Emirates",code:"AE",salary:66381},{name:"United Kingdom",code:"GB",salary:61188},{name:"United States",code:"US",salary:91935},{name:"Uruguay",code:"UY",salary:23754},{name:"Vietnam",code:"VN",salary:19058}],u={browser:.4,native:.4,performance:.35,sourcecode:0,perpetual:0},d=.05;var h=r(1527),m=r(2658),p=r(2303),f=r(4848);function y(e){let{children:t,fallback:r}=e;return(0,p.A)()?(0,f.jsx)(f.Fragment,{children:t?.()}):r??null}const v="premium-price-form-value";function g(){const{siteConfig:e}=(0,a.A)(),t=(0,p.A)();return(0,s.useEffect)((()=>{t&&window.trigger("open_pricing_page",1),(async()=>{if(!t||!(0,m.IA)())return;const e=await(0,m.C3)(),r=await e.getLocal(v);r&&(console.log("formValueDoc:"),console.dir(r),b("home-country",r._data.data.homeCountry),b("company-size",r._data.data.companySize),b("project-amount",r._data.data.projectAmount),b("license-period",r._data.data.licensePeriod),Object.keys(u).forEach((e=>{b("package-"+e,!1)})),r._data.data.packages.forEach((e=>{b("package-"+e,!0)})),document.getElementById("price-calculator-submit").click())})()})),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.A,{children:(0,f.jsx)("body",{className:"homepage"})}),(0,f.jsx)(n.A,{title:`Premium Plugins - ${e.title}`,description:"RxDB plugins for professionals. FAQ, pricing and license",children:(0,f.jsxs)("main",{children:[(0,f.jsx)("div",{className:"block first",children:(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:[(0,f.jsx)("b",{className:"underline",children:"RxDB"})," Premium Plugins"]}),(0,f.jsxs)("p",{style:{width:"80%"},children:["RxDB's premium plugins offer advanced features and optimizations that enhance application ",(0,f.jsx)("b",{children:"performance"})," ","and are backed by dedicated support and regular updates. Using the premium plugins is recommended for users that use RxDB in a professional context."]}),(0,f.jsxs)("div",{className:"premium-blocks",children:[(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage IndexedDB"}),(0,f.jsxs)("p",{children:["A storage for browsers based on ",(0,f.jsx)("b",{children:"IndexedDB"}),". Has the best latency on writes and smallest build size."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage OPFS"}),(0,f.jsxs)("p",{children:["Currently the RxStorage with best data throughput that can be used in the browser. Based on the ",(0,f.jsx)("b",{children:"OPFS File System Access API"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SQLite"}),(0,f.jsxs)("p",{children:["A fast storage based on ",(0,f.jsx)("b",{children:"SQLite"})," for Servers and Hybrid Apps. Can be used with"," ",(0,f.jsx)("b",{children:"Node.js"}),", ",(0,f.jsx)("b",{children:"Electron"}),", ",(0,f.jsx)("b",{children:"React Native"}),", ",(0,f.jsx)("b",{children:"Capacitor"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SharedWorker"}),(0,f.jsxs)("p",{children:["A RxStorage wrapper to run the storage inside of a SharedWorker which improves the performance by taking CPU load away from the main process. Used in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Worker"}),(0,f.jsx)("p",{children:"A RxStorage wrapper to run the storage inside of a Worker which improves the performance by taking CPU load away from the main process."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Sharding"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that improves performance by applying the sharding technique."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Memory Synced"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that creates a synced in-memory copy which improves performance for the initial page load time and write & read operations."})]})})}),(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Query Optimizer"}),(0,f.jsx)("p",{children:"A tool to find the best index for a given query. You can use this during build time to find the best index and then use that index during runtime."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Localstorage Meta Optimizer"}),(0,f.jsxs)("p",{children:["A wrapper around any other storage which optimizes the initial page load one by using localstorage for meta key-value document. Only works in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"WebCrypto Encryption"}),(0,f.jsx)("p",{children:"A faster and more secure encryption plugin based on the Web Crypto API."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Filesystem Node"}),(0,f.jsxs)("p",{children:["A fast RxStorage based on the ",(0,f.jsx)("b",{children:"Node.js"})," Filesystem."]})]})})}),(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Logger"}),(0,f.jsx)("p",{children:"A logging plugin useful to debug performance problems and for monitoring with Application Performance Monitoring (APM) tools like Bugsnag, Datadog, Elastic, Sentry and others"})]})})})]})]})}),(0,f.jsx)("div",{className:"block dark",id:"faq",children:(0,f.jsxs)("div",{className:"content centered premium-faq",children:[(0,f.jsxs)("h2",{children:["F.A.Q. ",(0,f.jsx)("b",{children:"(click to toggle)"})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Do I need the Premium Plugins?"}),"RxDB Core is open source and many use cases can be implemented with the Open Core part of RxDB. There are many"," ",(0,f.jsx)("a",{href:"/rx-storage.html",target:"_blank",children:"RxStorage"})," ","options and all core plugins that are required for replication, schema validation, encryption and so on, are totally free. As soon as your application is more then a side project you can consider using the premium plugins as an easy way to improve your applications performance and reduce the build size.",(0,f.jsx)("br",{}),"The main benefit of the Premium Plugins is ",(0,f.jsx)("b",{children:"performance"}),". The Premium RxStorage implementations have a better performance so reading and writing data is much faster especially on low-end devices. You can find a performance comparison"," ",(0,f.jsx)("a",{href:"/rx-storage-performance.html",target:"_blank",children:"here"}),". Also there are additional Premium Plugins that can be used to further optimize the performance of your application like the"," ",(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})," ","or the"," ",(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"Sharding"})," ","plugin."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not for free?"}),"The development of RxDB started in 2016 and after all these years it became clear that big implementation and improvement steps will not be done by the RxDB community. While the community submits valuable pull requests, they are mostly small improvements or bugfixes for specific edge case. Big rewrites and optimizations that require a big effort have only be done by the RxDB maintainer.",(0,f.jsx)("br",{}),"Selling RxDB Premium ensures that there will be always an incentive for someone to add features, keep everything up to date and to further improve and optimize the codebase. This gives the user the confidence that RxDB is a ",(0,f.jsx)("b",{children:"future proof"})," tech stack to build on which lets RxDB stand out compared to similar technologies."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is there no free trial period?"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:"RxDB is written in JavaScript and the code of the Premium Plugins does not contain any tracking or measurement code that would send information from your application to our servers in production mode. As soon as someone has the code on his computer, the maintainer has no chance to really ensure that after a free trial period the code is no longer used and deleted."}),(0,f.jsxs)("li",{children:["Before you can use the Premium Plugins you have to debate and sign a license agreement with the maintainer. This is a sophisticated process that creates overhead which distracts the maintainer from writing RxDB code. So handling trial period users is just not manageable. For this reason there is also no monthly subscriptions. Premium access must be paid ",(0,f.jsx)("b",{children:"per year"}),"."]})]})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not cheaper?"}),"The price of the Premium Plugins is chosen in way that ensures that there can be always one person that develops RxDB ",(0,f.jsx)("b",{children:"full time"}),". Compared to other JavaScript frameworks and developer tools, RxDB satisfies an edge use case for people that want to store data inside of their application on the users device. Most web developers do not need to do that and rely on the traditional client-server stack. So RxDB cannot be sold to that many people which increases the price."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I install/build the premium plugins in my CI?"}),(0,f.jsx)("b",{children:"Yes"})," you can safely install and use the Premium Plugins in your CI without additional payment."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Which payment methods are accepted?"}),(0,f.jsx)("b",{children:"Stripe.com"})," is used as payment processor so most known payment options like credit card, PayPal, SEPA transfer and others are available. A list of all options can be found"," ",(0,f.jsx)("a",{href:"https://stripe.com/docs/payments/payment-methods/overview",title:"stripe payment options",target:"_blank",children:"here"}),"."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I get a discount?"}),"Discounts are provided for people that have made a significant contribution to RxDB or one of RxDB's dependencies or to the Open Source Community overall. Also for private personal projects there is the option to solve one of the",(0,f.jsx)("a",{href:"https://github.com/pubkey/rxdb/blob/master/orga/premium-tasks.md",target:"_blank",children:"Premium Tasks"}),"to get 2 years access to the Premium Plugins."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Is there any tracking code inside of the premium plugins?"}),"No, the premium plugins themself do not contain any tracking code. When you build your application with RxDB and deploy it to production, it will not make requests from your users to any RxDB server."]})]})}),(0,f.jsxs)("div",{className:"block",children:[(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["RxDB Premium ",(0,f.jsx)("b",{className:"underline",children:"Price Calculator"})]}),(0,f.jsx)("div",{className:"price-calculator",children:(0,f.jsx)("div",{className:"price-calculator-inner",children:(0,f.jsxs)("form",{id:"price-calculator-form",children:[(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"home-country",children:"Company Home Country:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{list:"home-country",name:"home-country",pattern:"[A-Za-z \\-\\,]{2,}",required:!0,style:{width:"100%",maxWidth:240},autoComplete:"off",placeholder:"Company Home Country"}),(0,f.jsx)("datalist",{id:"home-country",children:l.sort(((e,t)=>e.name>=t.name?1:-1)).map(((e,t)=>(0,f.jsx)("option",{value:e.name,children:e.name},t)))})]})]}),(0,f.jsx)("br",{}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"company-size",children:"Company Size:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{type:"number",name:"company-size",min:1,max:1e6,required:!0,onKeyDown:()=>{const e=(0,o.ZN)(event);return 69!==e.keyCode&&189!==e.keyCode&&190!==e.keyCode},placeholder:"Company Size"}),(0,f.jsx)("div",{className:"suffix",children:"employee(s)"})]})]}),(0,f.jsxs)("div",{className:"packages",children:[(0,f.jsx)("h3",{children:"Packages:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-browser",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Browser Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:"RxStorage OPFS"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:"RxStorage IndexedDB"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:"RxStorage Worker"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:"WebCrypto Encryption"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-native",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Native Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:"RxStorage SQLite"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:"RxStorage Filesystem Node"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-performance",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Performance Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"RxStorage Sharding"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:"RxStorage Memory Synced"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:"RxStorage Shared Worker"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-utilities",type:"checkbox",className:"package-checkbox",defaultChecked:!0,disabled:!0}),(0,f.jsxs)("h4",{children:["Utilities Package ",(0,f.jsx)("b",{children:"always included"})]}),(0,f.jsx)("ul",{children:(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:"Logger"})})})]})}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("div",{className:"button",id:"price-calculator-submit",onClick:async()=>{(0,h.h)("calculate_premium_price",3);const e=(0,o.ZN)(document.getElementById("price-calculator-form"));if(!e.reportValidity())return void console.log("form not valid");const t=new FormData(e),r=Object.fromEntries(t.entries());console.log("formData:"),console.dir(r);const a=l.find((e=>e.name.toLowerCase()===r["home-country"].toLowerCase()));if(!a)return;const n=Object.entries(r).filter((e=>{let[t,r]=e;return t.startsWith("package-")})).map((e=>{let[t]=e;return(0,c.dG)(t.split("-"))})),i={companySize:parseInt(r["company-size"],10),teamSize:r["developer-count"],projectAmount:"1",licensePeriod:1,homeCountryCode:a.code,packages:n},s=function(e){if(console.log("calculatePrice:"),console.dir(e),"number"!=typeof e.licensePeriod)throw new Error("not a number "+typeof e.licensePeriod);const t=(0,o.ZN)(l.find((t=>t.code===e.homeCountryCode))).salary;let r=0;e.packages.forEach((e=>{const t=u[e];r+=t})),console.log("aimInPercent: "+r);let a=350+1.4*t*(r/100);if(2===e.packages.length&&(a*=.8),e.packages.length>2&&(a*=.7),e.companySize>1){let t=1+Math.pow(1*e.companySize-1,.85)/100*4.5;const r=6;t>r&&(t=r),console.log("input.companySize "+e.companySize+" - "+t),a*=t}if(e.packages.includes("sourcecode")){a*=1.75;const e=1520;a1200?100*Math.floor(a/100):50*Math.floor(a/50),{totalPrice:a}}(i);console.log("priceResult:"),console.log(JSON.stringify(s,null,4));const p=(0,o.ZN)(document.getElementById("price-calculator-result")),f=(0,o.ZN)(document.getElementById("total-per-project-per-month")),y=(e,t)=>{console.log("setPrice:"),console.dir(t),e.innerHTML=Math.ceil(t).toString()},g=s.totalPrice/i.licensePeriod;y(f,"infinity"!==i.projectAmount?g/parseInt(i.projectAmount,10)/12:0);const b=await(0,m.C3)();await b.upsertLocal(v,{companySize:r["company-size"],projectAmount:r["project-amount"],licensePeriod:r["license-period"],homeCountry:a.name,packages:n,price:s.totalPrice,formSubmitted:!1}),p.style.display="block"},children:"Estimate Price"})]})})}),(0,f.jsx)("div",{className:"price-calculator",style:{marginBottom:90},children:(0,f.jsxs)("div",{className:"price-calculator-inner",id:"price-calculator-result",style:{display:"none"},children:[(0,f.jsx)("h4",{children:"Estimated Price:"}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"inner",children:[(0,f.jsx)("span",{className:"price-label",children:"\u20ac"}),(0,f.jsx)("span",{id:"total-per-project-per-month",children:"84"}),(0,f.jsx)("span",{className:"per-month",children:"/month"}),(0,f.jsx)("span",{className:"clear"})]}),(0,f.jsx)("br",{}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"proceed-hint",children:["Fill out the ",(0,f.jsx)("b",{children:"form below \u2193"})," to proceed."]})]})})]}),(0,f.jsx)("div",{className:"block dark",id:"premium-request-form-block",children:(0,f.jsxs)("div",{className:"content centered premium-request",children:[(0,f.jsxs)("h2",{children:["Request Premium ",(0,f.jsx)("b",{className:"underline",children:"Form"})]}),(0,f.jsx)("p",{}),(0,f.jsx)(y,{fallback:(0,f.jsx)("span",{children:"Loading form iframe..."}),children:()=>(0,f.jsxs)("iframe",{id:"request-premium-form",src:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",children:["Your browser doesn't support iframes, ",(0,f.jsx)("a",{href:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",target:"_blank",rel:"nofollow",children:"go here"})]})})]})})]})]})})]})}function b(e,t){if(void 0===t)return;const r=document.querySelector("[name="+e+"]");r&&(r.type&&"checkbox"===r.type?r.checked=t:r.value=t)}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>l,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>u,dY:()=>a,em:()=>o,h$:()=>d,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function d(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/1df93b7f.0b65e8f2.js b/docs/assets/js/1df93b7f.0b65e8f2.js deleted file mode 100644 index 4a17e07e351..00000000000 --- a/docs/assets/js/1df93b7f.0b65e8f2.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[4583],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Kr,C3:()=>Hr,IA:()=>zr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function s(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function i(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var s in t)n[s]=e(t[s]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var d=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},h=new Set(["__proto__","prototype","constructor"]),u=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var s of e)switch(s){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=s),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=s;break}if(h.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=s;break}if("property"===a){if(h.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!u.has(s))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=s}switch(n&&(r+="\\"),a){case"property":if(h.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!d(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var _=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,j.A)(Error)),N=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,j.A)(TypeError));function D(e,t){return new _(e,w.tunnelErrorMessage(e),t)}function R(e,t){return new N(e,w.tunnelErrorMessage(e),t)}function I(e){return!(!e||409!==e.status)&&e}var E={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var C=/\./g,S="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw D("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function W(e){var t=q((e=i(e)).primaryKey);e.properties=i(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=F,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=Q(e);(0,y.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,y.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var F={type:"object",properties:{lwt:{type:"number",minimum:T,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function Q(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=q(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var z="docs",H="changes",K="attachments",Z="dexie",U=new Map,J=new Map;var V="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return V+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(V)?"|"+e.substring(V.length):e}function X(e,t){return t?(t=te(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=q(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,y.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function se(e,t){return e+"||"+t}function ie(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,y.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===A(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,y.jw)(r)):r}var oe=r(9092),ce=r(5734),le=r(3337),de=String.fromCharCode(65535),he=Number.MIN_SAFE_INTEGER;function ue(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),s=new Set;Object.keys(r).forEach((t=>{var a=A(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&s.add(t)}));var i,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!s.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,d=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],s={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);s=Object.assign(s,r)}})):s={startKey:l?he:de,endKey:a?de:he,inclusiveStart:!0,inclusiveEnd:!0};return void 0===s.startKey&&(s.startKey=he),void 0===s.endKey&&(s.endKey=de),void 0===s.inclusiveStart&&(s.inclusiveStart=!0),void 0===s.inclusiveEnd&&(s.inclusiveEnd=!0),l&&!s.inclusiveStart&&(l=!1),a&&!s.inclusiveEnd&&(a=!1),s})),h=d.map((e=>e.startKey)),u=d.map((e=>e.endKey)),m={index:e,startKeys:h,endKeys:u,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!s.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,h,u)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},s=10,i=(0,y.Sd)(r.startKeys,(e=>e!==he&&e!==de));n(i*s);var o=(0,y.Sd)(r.startKeys,(e=>e!==de&&e!==he));n(o*s);var c=(0,y.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*s*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,i=m)})),!i)throw D("SNH",{query:t});return i}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var s=[],i=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var d=l[0];if(d&&i.add(o),"$eq"!==d){if(s.length>0)return!1;s.push(d)}}var h=[],u=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var v=f[0];if(v&&u.add(m),"$eq"!==v){if(h.length>0)return!1;h.push(v)}}var g=0;for(var y of e){for(var b of[i,u]){if(!b.has(y)&&b.size>0)return!1;b.delete(y)}if(r[g]!==a[g]&&i.size>0&&u.size>0)return!1;g++}return!0}var ge=r(744),ye=r(2779),be=r(1692),xe=r(4903),je=r(7705),we=r(2403),ke=r(6776),_e=r(6950),Ne=r(6823),De=!1;function Re(e){return De||((0,ye.DZ)(ye.hu.PIPELINE,{$sort:xe.xF,$project:xe.C2}),(0,ye.DZ)(ye.hu.QUERY,{$and:je.a6,$eq:we.XV,$elemMatch:_e.Jy,$exists:Ne.P,$gt:we.MR,$gte:we.fy,$in:we.oZ,$lt:we.NV,$lte:we.Q_,$ne:we.C5,$nin:we.GU,$mod:ke.Pp,$nor:je.q3,$not:je.En,$or:je.sU,$regex:ke.WP,$size:_e.Ig,$type:Ne.T}),De=!0),new be.X(e)}function Ie(e,t){var r=q(e.primaryKey);t=i(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,y.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var s=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&s.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,y.k_)(e)?e:[e],r=t.findIndex((e=>!s.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ee(e,t){if(!t.sort)throw D("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,s=Object.keys(e)[0],i=Object.values(e)[0];r.push({key:s,direction:i,getValueFn:(t=s,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Se(e){return e===he?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===de||!0===r?"1":"0":r}function Pe(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Se),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Se);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function $e(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,s=n+(a.limit?a.limit:1/0),i=t.queryPlan,o=!1;i.selectorSatisfiedByIndex||(o=Ce(e.schema,t.query));var c=Pe(r.booleanIndexes,i,r.dexieDb._options.IDBKeyRange),l=i.index,d=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(z);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||d.push(n),i.sortSatisfiedByIndex&&d.length===s?e():a.continue()}else e()}}))})),!i.sortSatisfiedByIndex){var h=Ee(e.schema,t.query);d=d.sort(h)}return{documents:d=d.slice(n,s)}}function Te(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Be(e){return parseInt(e.split("-")[0],10)}function Ae(e,t){var r=t?t._rev:null;return(r?Te(r).height:0)+1+"-"+e}var Me="_rxdb_internal";async function qe(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function We(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:w.deepFreezeWhenDevMode(a),previousDocumentData:w.deepFreezeWhenDevMode(n)}}function Fe(e,t,r,a){if(a)throw 409===a.status?D("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?D("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function Qe(e){return{previous:e.previous,document:ze(e.document)}}function ze(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=i(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,s,i;t._attachments[r]=(i=(n=a).data)?{length:(s=i,atob(s).length),digest:n.digest,type:n.type}:n})),t}function He(e){var t=i(e);return t._meta=i(e._meta),t}function Ke(e,t,r){w.deepFreezeWhenDevMode(r);var a=q(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,s){var o=n.map((n=>function(n){var s=i(n.document);if(s._meta=i(s._meta),w.isDevMode()){s=M(a,r,s);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw D("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw D("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return s._meta.lwt=(0,ce.t)(),s._rev=Ae(e.token,n.previous),{document:s,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,s))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var i=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Ae(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(i,s))).then((e=>((0,y.Hb)(a.error,e.error),(0,y.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=i(Object.assign({},e.output.documentData,{_meta:B(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ze=r(3561),Ue=r(703),Je=new Map;function Ve(e,t){var r=Je.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Je.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Je.get(t);return n||(n={bc:new Ue.X2(["RxDB:",e,r].join("|")),refs:new Set},Je.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),s=new oe.B,i=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&s.next(r.eventBulk)};n.addEventListener("message",i);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return s.asObservable().pipe((0,Ze.X)(o))};var d=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),d()};var h=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),h()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,s,i){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=s,this.settings=i,this.primaryPath=q(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw D("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},s=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var i=new Map;(await ne(this.internals,s)).forEach((e=>{var t=e;return t&&i.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,s,i){for(var o,c=!!e.schema.attachments,l=[],d=[],h=[],u={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=u.events,p=[],f=[],v=[],g=r.size>0,y=a.length,b=function(){var e,n=a[x],u=n.document,y=n.previous,b=u[t],j=u._deleted,w=y&&y._deleted,k=void 0;if(g&&(k=r.get(b)),k){var _=k._rev;if(!y||y&&_!==y._rev){var N={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return h.push(N),1}var R=c?Qe(n):n;c&&(j?y&&Object.keys(y._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.ZN)(y)._attachments[e].digest})})):(Object.entries(u._attachments).find((t=>{let[r,a]=t;return(y?y._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(u._attachments).forEach((e=>{let[t,r]=e;var a=y?y._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?h.push(e):(c?(d.push(Qe(R)),i&&i(u)):(d.push(R),i&&i(u)),o=R);var I=null,E=null,C=null;if(w&&!j)C="INSERT",I=c?ze(u):u;else if(!y||w||j){if(!j)throw D("SNH",{args:{writeRow:n}});C="DELETE",I=(0,le.ZN)(u),E=y}else C="UPDATE",I=c?ze(u):u,E=y;var S={documentId:b,documentData:I,previousDocumentData:E,operation:C};m.push(S)}else{var O=!!j;if(c&&Object.entries(u._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},h.push(e))})),e||(c?(l.push(Qe(n)),s&&s(u)):(l.push(n),s&&s(u)),o=n),!O){var P={documentId:b,operation:"INSERT",documentData:c?ze(u):u,previousDocumentData:c&&y?ze(y):y};m.push(P)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>se(e.documentId,e.attachmentId))))})),(r=(0,le.ZN)(r)).eventBulk.events.length>0){var i=(0,le.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:i[this.primaryPath],lwt:i._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),$e(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,s=Pe(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),i=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(z);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(s);i=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),i}(this,e);return{count:t,mode:"fast"}}return{count:(await $e(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=se(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=J.get(e)-1;0===r?(t.dexieDb.close(),J.delete(e)):J.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=s(U,o,(()=>{var e=(async()=>{var e=i(r);e.autoOpen=!1;var t=new a.cf(o,e),s={[z]:ae(n),[H]:"++sequence, id",[K]:"id"};return t.version(1).stores(s),await t.open(),{dexieDb:t,dexieTable:t[z],dexieAttachmentsTable:t[K],booleanIndexes:ie(n)}})();return U.set(o,c),J.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(Z,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=Z,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw D("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw D("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw D("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var s=n[a];if(!nt(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}var st={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function it(e,t){st[e]&&st[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(st[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,y.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=q(this.jsonSchema.primaryKey),this.finalFields=Q(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw D("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=A(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function lt(e,t,r){void 0===r&&(r=!0),r&&it("preCreateRxSchema",e);var a=W(e);a=function(e){return o(e,!0)}(a),w.deepFreezeWhenDevMode(a);var n=new ct(a,t);return it("createRxSchema",n),n}var dt=r(7708),ht=r(8146),ut=r(3356),mt=r(5520),pt=r(8609),ft=r(1753);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((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 ")}function gt(e){return e.documentData?e.documentData:e.previousDocumentData}var yt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=s(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var s={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.ZN)(a).push(s),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,s,i,o=(n=a.map((e=>e.lastKnownDocumentState)),s=n[0],i=Te(s._rev).height,n.forEach((e=>{var t=Te(e._rev).height;t>i&&(s=e,i=t)})),s),l=o;for(var d of a)try{l=await d.modifier(c(l))}catch(h){d.reject(h),d.reject=()=>{},d.resolve=()=>{}}try{await this.preWrite(l,o)}catch(h){return void a.forEach((e=>e.reject(h)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,i=n(t,a),o=I(e);if(o){var c=s(this.queueByDocId,a,(()=>[]));i.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.ZN)(o.documentInDb),(0,le.ZN)(c).unshift(e)}))}else{var l=D("COL20",{name:E[(r=e).status],document:r.documentId,writeError:r});i.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={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.$.pipe((0,dt.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,ht.p)((e=>!e.isLocal)),(0,ht.p)((e=>e.documentId===this.primary)),(0,dt.T)((e=>gt(e))),(0,ut.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,dt.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.t)(le.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(w.isDevMode()){if(e.includes(".item."))throw D("DOC1",{path:e});if(e===this.primaryPath)throw D("DOC2");if(this.collection.schema.finalFields.includes(e))throw D("DOC3",{path:e});if(!A(this.collection.schema.jsonSchema,e))throw D("DOC4",{path:e})}return this.$.pipe((0,dt.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=A(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.$A;if(!t)throw D("DOC5",{path:e});if(!t.ref)throw D("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw D("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return s(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return w.deepFreezeWhenDevMode(t);var r=this;return new Proxy(i(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var s=a.slice(0,-2);return r.get$$($(e+"."+s))}if("$"===n){var i=a.slice(0,-1);return r.get$($(e+"."+i))}if("_"===n){var o=a.slice(0,-1);return r.populate($(e+"."+o))}return r.get($(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return w.deepFreezeWhenDevMode(this._data);var t=i(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,w.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=i(e),this._data._deleted)throw D("DOC11",{id:this.primary,document:this});await wt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Fe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(D("DOC13",{document:this,id:this.primary}));var t,r=i(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Fe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw D("DOC14")}};function jt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function wt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),w.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(2198),_t=r(511),Nt=r(4157),Dt=r(2442),Rt=r(6114);function It(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Et=new WeakMap;function Ct(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return s(Et,e,(()=>{var t=e.collection,r=Ie(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ee(t.schema.jsonSchema,r),s=Ce(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:It(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>s({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.ZN)(e._result).docsData.slice(0),n=(0,le.ZN)(e._result).docsDataMap,i=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:w.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(y.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},s=(0,Rt.kC)(t);return"runFullQueryAgain"===s||("doNothing"!==s?(i=!0,(0,Rt.Cs)(s,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:i,newResults:a}}var St=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return s(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Pt(e){return e.refCount$.observers.length}var $t,Tt,Bt=($t=100,Tt=3e4,(e,t)=>{if(!(t._map.size<$t)){var r=(0,ce.t)()-Tt,a=[],n=Array.from(t._map.values());for(var s of n)Pt(s)>0||(0===s._lastEnsureEqual&&s._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,i).forEach((e=>Ot(t,e)))}}),At=new WeakSet;var Mt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=gt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=w.deepFreezeWhenDevMode,i=e.documentCreator,o=o=>{var c=o[t],l=Be(o._rev),d=s(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),h=d.byRev,u=h.get(l),m=u?u.deref():void 0;return m||(o=n(o),m=i(o),h.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Be(e.revision)})})))}))))),m};return o}(this))}}]),e}();function qt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Wt=function(){function e(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=qt(this.collection._docCache,t)}return(0,b.A)(e,[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Wt(this.collection,e,e.length);this._result=t}else this._result=new Wt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw D("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var s=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,y.Hb)(t,n)}}else{var s=e.isFindOneByIdQuery,i=e.collection._docCache.getLatestDocumentDataIfExists(s);if(!i){var o=await r.storageInstance.findDocumentsById([s],!1);o[0]&&(i=o[0])}i&&!i._deleted&&t.push(i)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return s.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw D("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,_t._)(this.$))).then((t=>{if(!t&&e)throw D("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Ie(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),it("prePrepareQuery",e);var t=Zt(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,ht.p)((e=>!e.isLocal)),(0,ut.Z)(null),(0,Dt.Z)((()=>Kt(this))),(0,dt.T)((()=>this._result)),(0,pt.t)(le.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,le.ZN)(t).time))),(0,ht.p)((e=>!!e)),(0,dt.T)((e=>{var t=(0,le.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,Nt.h)(e,this.refCount$.pipe((0,ht.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Ce(0,Ie(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function zt(e,t,r,a){it("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,s,i=new Qt(e,t,r,a);return i=(n=i).collection._queryCache.getByQuery(n),s=r,At.has(s)||(At.add(s),(0,ft.dY)().then((()=>(0,ft.Ve)(200))).then((()=>{s.destroyed||s.cacheReplacementPolicy(s,s._queryCache),At.delete(s)}))),i}function Ht(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||Ht(e)?ft.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||Ht(e))return ft.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var s=(0,le.ZN)(e._result).count,i=s;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&i++,r&&!a&&i--})),i!==s&&(t=!0,e._setResultData(i))}else{var o=Ct(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var i=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:s,devMode:w.isDevMode()});await i.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),i){var d=o.map((e=>{var t=He(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Ae(r,e),{previous:e,document:t}}));await t.bulkWrite(d,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,ht.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var sr=new WeakMap;function ir(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return it("createRxDocument",a),a}(function(e){return s(sr,e,(()=>jt(ir(e))))}(e),e,w.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),it("postCreateRxDocument",r),r}var cr=function(e,t){return nt(ze(e.newDocumentState),ze(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],dr=["insert","save","remove","create"],hr=!1,ur=function(){function e(e,t,r,a,n,s,i,o,c,l,d,h){void 0===n&&(n={}),void 0===s&&(s={}),void 0===i&&(i={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Bt),void 0===d&&(d={}),void 0===h&&(h=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new St,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=s,this.methods=i,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=d,this.conflictHandler=h,function(e){if(hr)return;hr=!0;var t=Object.getPrototypeOf(e);dr.forEach((e=>{lr.map((r=>{var a=r+P(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new yt(this.storageInstance,this.schema.primaryPath,((e,t)=>wt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,ht.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Dt.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,dt.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Mt(this.schema.primaryPath,this.$.pipe((0,ht.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>We(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.em},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration-schema")},t.getMigrationState=function(){throw vt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Fe(this,e[this.schema.primaryPath],e,r),(0,le.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),s=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),i=qt(this._docCache,s.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(i.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:i,error:s.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],s=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),s.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=i(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",s.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw D("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),s=a.success.slice(0),i=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)i.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));s.push(l)}}))),{error:i,success:s}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Fe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw D("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw D("COL5",{queryObj:e});return e||(e={selector:{}}),zt("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=zt("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw D("QU6");(e=i(e)).limit=1,t=zt("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),zt("count",e,this)},t.findByIds=function(e){return zt("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!dr.includes(t))throw D("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw D("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),s=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][s].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.em;var s=n.series.map((e=>()=>e(r,a)));return(0,ft.h$)(s).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,ht.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,ht.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,ht.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7635),pr=r(1007);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.sc)(e))},vr=r(5525),gr=new Set,yr=function(){function e(e,t,r,a,n,s,i,o,c,l,d,h,u){void 0===i&&(i=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,Dt.Z)((e=>e.events))),this.storageToken=ft.Dr,this.storageTokenDocument=ft.Dr,this.emittedEventBulkIds=new vr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=s,this.eventReduce=i,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=d,this.allowSlowCount=h,this.reactivity=u,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Vt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Jt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:B(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var s=(0,le.ZN)(n.error[0]);if(s.isError&&I(s)){var i=s;if(c=i.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw D("DM5",{args:{database:e.name,databaseStateVersion:i.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==i.documentInDb.data.passwordHash)throw D("DB1",{passwordHash:r,existingPasswordHash:i.documentInDb.data.passwordHash});var o=i.documentInDb;return(0,le.ZN)(o)}var c,l;throw s}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw D("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await qe(this.internalStore,Gt(tr(e,t),Ut));if(!r)throw D("SNH",{name:e,schema:t});var a=He(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[s,o]=e;var c=s,l=o.schema;t[c]=l;var d=lt(l,this.hashFunction);if(r[c]=d,this.collections[s])throw D("DB3",{name:s});var h=tr(s,l),u={id:Gt(h,Ut),key:h,context:Ut,data:{name:c,schemaHash:await d.hash,schema:d.jsonSchema,version:d.version,connectedStorages:[]},_deleted:!1,_meta:B(),_rev:"",_attachments:{}};a.push({document:u});var m=Object.assign({},o,{name:c,schema:d,database:this}),p=i(o);p.database=this,p.name=s,it("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var s=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(s.error.map((async e=>{if(409!==e.status)throw D("DB12",{database:this.name,writeError:e});var a=(0,le.ZN)(e.documentInDb),n=a.data.name,s=r[n];if(a.data.schemaHash!==await s.hash)throw D("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await s.hash,previousSchema:a.data.schema,schema:(0,le.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:s={},autoMigrate:i=!0,statics:o={},methods:c={},attachments:l={},options:d={},localDocuments:h=!1,cacheReplacementPolicy:u=Bt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:w.isDevMode()};return it("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new ur(t,r,a,e,n,s,c,l,d,u,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.em;return i&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(it("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:s,methods:c,attachments:l,options:d,cacheReplacementPolicy:u,localDocuments:h,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.addState=function(e){throw vt("state")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>gr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),s=await Yt(n),i=new Set;s.forEach((e=>i.add(e.data.name)));var o=Array.from(i);return await Promise.all(o.map((s=>ar(t,n,a,e,s,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,s){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Me,schema:Vt,options:a,multiInstance:n,password:s,devMode:w.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s=!0,eventReduce:i=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:d=!1,localDocuments:h=!1,hashFunction:u=fr,reactivity:m}=e;it("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}),o||function(e,t){var r=t.name+"|"+e;if(gr.has(r))throw D("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),gr.add(t.name+"|"+a);var p=O(10);return br(p,t,a,r,s,n).catch((e=>{throw gr.delete(t.name+"|"+a),e})).then((e=>{var f=new yr(a,p,t,r,n,s,i,c,e,u,l,d,m);return ot("createRxDatabase",{database:f,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}}).then((()=>f))}))}var jr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Qt.prototype,RxCollection:ur.prototype,RxDatabase:yr.prototype},wr=new Set,kr=new Set;var _r=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.A)(t,e),t}(jt()),Nr={get isLocal(){return!0},get allAttachments$(){throw D("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,ht.p)((e=>e.documentId===this.primary)),(0,ht.p)((e=>e.isLocal)),(0,dt.T)((e=>gt(e))),(0,ut.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,dt.T)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.t)(le.bz))},get $$(){var e=this;return Ir(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Ir(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=v(this._data,e);return t=w.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,w.isDevMode()){if(e.includes(".item."))throw D("LD3",{objPath:e});if(e===this.primaryPath)throw D("LD4")}return this.$.pipe((0,dt.T)((e=>e._data)),(0,dt.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){return Ir(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=i(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:B(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Dr=!1,Rr=()=>{if(!Dr){Dr=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Nr,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Nr,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Nr[e]=(e=>()=>{throw D("LD6",{functionName:e})})(e)))}};function Ir(e){var t=e.parent;return t instanceof yr?t:t.database}var Er=new WeakMap,Cr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Pr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Ar);var n=new Mt("id",e.$.pipe((0,ht.p)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new _r(e.id,e,t);return Object.setPrototypeOf(r,Nr),r.prototype=Nr,r}(t,e))),s=new yt(a,"id",(()=>{}),(()=>{})),i=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:i,events:r.events.map((t=>We(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:s};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw D("LD8",{database:r.name,collection:a})}return t}function Pr(e,t,r,a,n,s){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Br(a),schema:Ar,options:n,multiInstance:s,devMode:w.isDevMode()})}function $r(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function Tr(e,t,r){var a=O(10),n=await Pr(a,e,t,r,{},!1);await n.remove()}function Br(e){return"plugin-local-documents-"+e}var Ar=W({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Mr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:B(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function qr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):qe(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Wr(e){return this.$.pipe((0,ut.Z)(null),(0,Dt.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Dt.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,ht.p)((e=>e.use)),(0,dt.T)((e=>e.doc)))}var Fr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Mr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Wr},RxDatabase:e=>{e.insertLocal=Mr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Wr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>$r(e)},postDestroyRxCollection:{after:e=>$r(e)},postRemoveRxDatabase:{after:e=>Tr(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Tr(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Qr;function zr(){return"undefined"!=typeof window&&window.indexedDB}function Hr(){return Qr||(Qr=(async()=>{!function(e){if(it("preAddRxPlugin",{plugin:e,plugins:wr}),!wr.has(e)){if(kr.has(e.name))throw D("PL3",{name:e.name,plugin:e});if(wr.add(e),kr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(jr[t])})),e.overwritable&&Object.assign(w,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&st[t].push(r.after),r.before&&st[t].unshift(r.before)}))}}(Fr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Qr}const Kr=["#e6008d","#8d2089","#5f2688"]},1527:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{h:()=>a})},6866:(e,t,r)=>{r.r(t),r.d(t,{default:()=>x});var a=r(4586),n=r(1595),s=r(5260),i=(r(6879),r(4157)),o=r(943),c=r(7708),l=r(5520),d=r(3337),h=r(1753),u=r(5734),m=r(2658),p=r(6540),f=r(1527),v=r(4589),g=r(4848);let y=!1;async function b(){if(y)return;y=!0,console.log("start animation");if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return void console.log("reducedMotion is set to true");if(!(0,m.IA)())return;const e=await(0,m.C3)();try{await e.insertLocal("beatingvalues",{beatPeriod:0,text1:"JavaScript",text2:"you deserve",color:m.Tj[0]})}catch(N){}const t=(0,d.ZN)(await e.getLocal("beatingvalues"));(async()=>{for(await(0,h.ND)(k);y;){const e=_(),r=(0,h.ND)(e.timeToNextPeriod);if(e.period%2==0)try{await t.incrementalModify((t=>(t.beatPeriod>=e.period||(t.beatPeriod=e.period,t.color=m.Tj[e.period%3],e.period%4==0?t.text1=E(j,e.period)[0]:t.text2=E(w,e.period)[0]),t)))}catch(N){}await r}})();const r=await e.upsertLocal("mousepos",{x:0,y:0,time:0});let a=[];window.addEventListener("mousemove",(e=>{a=[e.clientX,e.clientY]})),(0,i.h)((0,o.R)(window,"mousemove"),(0,o.R)(window,"scroll"),(0,o.R)(window,"resize")).subscribe((()=>{r.incrementalPatch({x:a[0],y:a[1],time:(0,u.t)()})})),function(e){const t=document.getElementsByClassName("tilt-to-mouse"),r=100;function a(e,t,a){const n=a.getBoundingClientRect(),s=-(t-n.y-n.height/2)/r,i=(e-n.x-n.width/2)/r;return`perspective(150px) rotateX(${R(s)}deg) rotateY(${R(i)}deg) `}function n(e,t){e.style.transform=a.apply(null,t)}e.$.subscribe((e=>{e._data.data.time&&Array.from(t).forEach((t=>{if(!S(t))return;n(t,(0,d.ZN)([e._data.data.x,e._data.data.y]).concat([t]))}))}))}(r),function(e){const t=document.getElementsByClassName("enlarge-on-mouse");function r(e){const t=e.getBoundingClientRect();return{centerX:t.left+t.width/2,centerY:t.top+t.height/2,width:t.width,height:t.height}}function a(e,t){const r=`scale(${t})`;e.style.transform=r}e.$.pipe((0,c.T)((e=>e._data))).subscribe((e=>{e.data.time&&e.data.x&&e.data.y&&Array.from(t).forEach((t=>{if(!S(t))return;const n=r(t),s=e.data.x-n.centerX,i=e.data.y-n.centerY,o=Math.sqrt(s*s+i*i);function c(e){return 1.9^e}let l=1+n.width/2/c(o+300);l>1.5&&(l=1.5),l<1.01&&(l=1),a(t,l)}))}))}(r);const n=document.getElementsByClassName("beating"),s=document.getElementsByClassName("beating-first"),p=document.getElementsByClassName("beating-second"),f=document.getElementsByClassName("beating-number"),v=document.getElementsByClassName("beating-color"),g=document.getElementsByClassName("beating-color-string"),b=[];let x=0;_(),t.$.pipe((0,c.T)((e=>e._data.data)),(0,l.F)(((e,t)=>JSON.stringify(e)===JSON.stringify(t)))).subscribe((e=>{b.forEach((function(e){e(x)})),x+=1;const t=e.color;Array.from(v).forEach((function(e){e.style.backgroundColor=t})),Array.from(g).forEach((function(e){e.innerHTML=t}))})),b.push((function(){Array.from(n).forEach((function(e){e.style.animationDuration=k+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(s).forEach((function(e){e.style.animationDuration=k+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(p).forEach((function(e){e.style.animationDuration=k+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")}))})),b.push((function(){Array.from(f).forEach((function(e){I()&&I()&&setTimeout((function(){const t=parseFloat(e.innerHTML)+1;e.innerHTML=t+""}),105)}))}))}function x(){const{siteConfig:e}=(0,a.A)();(0,p.useEffect)((()=>(b(),()=>{console.log("stop animation"),y=!1})));return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(s.A,{children:(0,g.jsx)("body",{className:"homepage"})}),(0,g.jsx)(n.A,{title:`${e.title}`,description:"RxDB is a fast, local-first NoSQL-database for JavaScript Applications like Websites, hybrid Apps, Electron-Apps, Progressive Web Apps and Node.js",children:(0,g.jsxs)("main",{children:[(0,g.jsx)("div",{className:"block first centered dark",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h1",{children:["The local ",(0,g.jsx)("b",{className:"underline",children:"Database"})," for"," ",(0,g.jsx)("b",{className:"underline",children:"JavaScript"})," Applications"]}),(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("div",{className:"half left",children:[(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("ul",{className:"checked",children:[(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Realtime Queries"}),": From results of queries to single document fields, with RxDB you can observe everything which makes building ",(0,g.jsx)("u",{children:"realtime applications"})," effortless."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Realtime Replication"}),": Run a two-way realtime replication with one of the many replication plugins. Also making your ",(0,g.jsx)("u",{children:"custom backend compatible"})," is pretty simple."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Offline Support"}),": Store data locally on your clients device to build applications that still work when there is ",(0,g.jsx)("u",{children:"no internet access"}),". Running queries locally also improves your user experience."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Supports all JavaScript runtimes"}),": With the flexible RxDB storage layer you can run the same code in ",(0,g.jsx)("u",{children:"Browsers"}),", ",(0,g.jsx)("u",{children:"Node.js"}),", ",(0,g.jsx)("u",{children:"Electron"}),","," ",(0,g.jsx)("u",{children:"React-Native"}),", ",(0,g.jsx)("u",{children:"Capacitor"}),", ",(0,g.jsx)("u",{children:"Bun"})," and ",(0,g.jsx)("u",{children:"Deno"}),"."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Great Performance"}),": Years of performance optimization made RxDB one of the ",(0,g.jsx)("u",{children:"fastest"})," ways to store and query data inside of JavaScript."]})]}),(0,g.jsx)("a",{className:"button",href:"/quickstart.html",target:"_blank",onClick:()=>(0,f.h)("start_now",.4),children:"Quickstart \xbb"}),(0,g.jsxs)("a",{className:"button light",href:"/code",target:"_blank",children:[(0,g.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",className:"star-icon","aria-hidden":"true",fill:"currentColor",style:{width:14,marginRight:8,marginLeft:-6,float:"left",marginTop:2},children:(0,g.jsx)("path",{d:"M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"})}),"Star (20,172)"]}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"half right",style:{display:"flex",alignItems:"center",justifyContent:"center"},children:(0,g.jsxs)("div",{className:"content-canvas",style:{marginTop:0,marginBottom:30,marginLeft:20},children:[(0,g.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,g.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,g.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms"}})})}),(0,g.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,g.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,g.jsx)("img",{src:"/files/logo/logo_text.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms",width:"52%"}})})}),(0,g.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,g.jsx)("div",{className:"beating-color one",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,g.jsx)("div",{className:"beating-color two",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,g.jsx)("div",{className:"beating-color three",style:{backgroundColor:"rgb(141, 32, 137)"}})]})]})})]})]})}),(0,g.jsx)("a",{href:"/chat",target:"_blank",children:(0,g.jsxs)("div",{className:"trophy discord",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/discord.svg",alt:"RxDB Discord chat"}),(0,g.jsxs)("div",{style:{flex:1},children:[(0,g.jsx)("div",{className:"subtitle",children:"Chat on"}),(0,g.jsx)("div",{className:"title",children:"Discord"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:"valuetitle",children:"members"}),(0,g.jsxs)("div",{className:"value",children:["747",(0,g.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,g.jsxs)("div",{className:"block reviews",children:[(0,g.jsx)("div",{className:"content centered",children:(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("h2",{children:["Our ",(0,g.jsx)("b",{className:"underline",children:"Success Stories"})]}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{})]})}),(0,g.jsxs)(v.A,{dots:!0,centerMode:!0,centerPadding:"10px",infinite:!0,arrows:!1,adaptiveHeight:!0,speed:500,slidesToShow:4,slidesToScroll:1,initialSlide:0,responsive:[{breakpoint:1250,settings:{slidesToShow:3,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:1024,settings:{slidesToShow:3,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:900,settings:{slidesToShow:2,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:600,settings:{slidesToShow:2,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:480,settings:{slidesToShow:1.1,centerPadding:"15px",slidesToScroll:1,infinite:!1,dots:!1}}],children:[(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"We use RxDB to create applications capable of being used in the most remote areas where Internet access is really a challenge."'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-white lazyload","data-src":"./files/companies/altgras.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"ALTGRAS"}),(0,g.jsx)("a",{href:"https://altgras.com/",target:"_blank",className:"company-link",children:"https://altgras.com/"})]})]})]}),(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"We provide a mobile app that is used by people in the field to fill in valuable information like inspections, surveys and audits"'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-black lazyload","data-src":"./files/companies/moreapp.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"MoreApp"}),(0,g.jsx)("a",{href:"https://moreapp.com/",target:"_blank",className:"company-link",children:"https://moreapp.com/"})]})]})]}),(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"We use RxDB to provide an offline first, cross platform point of sale system"'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-black lazyload","data-src":"./files/companies/woopos.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"WooCommerce POS"}),(0,g.jsx)("a",{href:"https://wcpos.com/",target:"_blank",className:"company-link",children:"https://wcpos.com/"})]})]})]}),(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"RxDB is a main component in building offline-ready multichannel apps. It has become our default stack for this kind of apps."'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-black lazyload","data-src":"./files/companies/atroo.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"atroo GmbH"}),(0,g.jsx)("a",{href:"https://atroo.de/",target:"_blank",className:"company-link",children:"https://atroo.de/"})]})]})]})]})]}),(0,g.jsx)("div",{className:"block second dark",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h2",{children:["Realtime applications ",(0,g.jsx)("b",{className:"underline",children:"made easy"})]}),(0,g.jsxs)("p",{children:["From the results of a query, to a single field of a document, with RxDB you can ",(0,g.jsx)("b",{children:"observe everything"}),". This enables you to build realtime applications ",(0,g.jsx)("b",{children:"fast"})," and ",(0,g.jsx)("b",{children:"reliable"}),". It does not matter if the data was changed by"," ",(0,g.jsx)("b",{children:"a user event"}),", ",(0,g.jsx)("b",{children:"another browser tab"})," or by the",(0,g.jsx)("b",{children:" replication"}),"."," ","Whenever your data changes, your UI reflects the new state. You can either use ",(0,g.jsx)("b",{children:"RxJS"})," or add ",(0,g.jsx)("a",{href:"/reactivity.html",target:"_blank",children:"custom reactiveness libraries"})," like signals or other state management."]}),(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("div",{className:"code half",children:[(0,g.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,g.jsx)("legend",{children:"Write"}),(0,g.jsxs)("samp",{children:[(0,g.jsx)("span",{className:"cm-keyword",children:"await "}),(0,g.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,g.jsx)("span",{className:"cm-method",children:"upsert"}),"(","{",(0,g.jsx)("br",{}),(0,g.jsx)("span",{className:"cm-property",children:"\xa0 id"}),": ",(0,g.jsx)("span",{className:"cm-string",children:"'foobar'"}),",",(0,g.jsx)("br",{}),(0,g.jsx)("span",{className:"cm-property",children:"\xa0 color"}),": ",(0,g.jsxs)("span",{className:"cm-string",children:["'",(0,g.jsx)("span",{className:"beating-color-string beating-color",children:"#e6008d"}),"'"]}),(0,g.jsx)("br",{}),"}",");"]})]}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,g.jsx)("legend",{children:"Observe"}),(0,g.jsxs)("samp",{style:{backgroundColor:"var(--bg-color)"},children:[(0,g.jsx)("span",{className:"cm-keyword",children:"await "}),(0,g.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,g.jsxs)("span",{className:"cm-method",children:["findOne(",(0,g.jsx)("span",{className:"cm-string",children:"'foobar'"}),")"]}),(0,g.jsx)("br",{}),"\xa0.",(0,g.jsx)("span",{className:"cm-property",children:"$"}),(0,g.jsx)("span",{className:"cm-comment",children:" // get observable"}),(0,g.jsx)("br",{}),"\xa0.",(0,g.jsx)("span",{className:"cm-method",children:"subscribe"}),"(",(0,g.jsx)("span",{className:"cm-def",children:"d"}),(0,g.jsx)("span",{className:"cm-operator",children:" =>"})," ","{",(0,g.jsx)("br",{}),(0,g.jsx)("span",{className:"cm-variable",children:"\xa0\xa0 screen"}),".",(0,g.jsx)("span",{className:"cm-property",children:"backgroundColor"}),(0,g.jsx)("span",{className:"cm-operator",children:" = "}),(0,g.jsx)("span",{className:"cm-variable",children:"d"}),".",(0,g.jsx)("span",{className:"cm-property beating-color",children:"color"}),";",(0,g.jsx)("br",{}),"\xa0","}",");"]})]})]}),(0,g.jsx)("div",{className:"canvas half",children:(0,g.jsxs)("div",{className:"content-canvas",children:[(0,g.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,g.jsx)("div",{className:"beating-color",children:(0,g.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,g.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,g.jsx)("div",{className:"beating-color",children:(0,g.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,g.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,g.jsx)("div",{className:"beating-color one"}),(0,g.jsx)("div",{className:"beating-color two"}),(0,g.jsx)("div",{className:"beating-color three"})]})]})})]})]})}),(0,g.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",onClick:()=>(0,f.h)("twitter_trophy_click",.2),target:"_blank",children:(0,g.jsxs)("div",{className:"trophy twitter",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/twitter-blue.svg",alt:"RxDB Twitter"}),(0,g.jsxs)("div",{style:{flex:1},children:[(0,g.jsx)("div",{className:"subtitle",children:"Follow on"}),(0,g.jsx)("div",{className:"title",children:"Twitter"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:"valuetitle",children:"followers"}),(0,g.jsxs)("div",{className:"value",children:["2843",(0,g.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,g.jsx)("div",{className:"block replication",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("div",{className:"half left",children:[(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("h2",{children:["Replicate ",(0,g.jsx)("b",{children:"with your existing infrastructure"})]}),(0,g.jsxs)("p",{children:["RxDB supports replication with a"," ",(0,g.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:"CouchDB"})," ","server or any custom"," ",(0,g.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:"GraphQL"})," ","endpoint which smoothly integrates with your existing infrastructure. Also you can use the replication primitives plugin to create custom replications over any protocol like"," ",(0,g.jsx)("a",{href:"/replication-http.html",target:"_blank",children:"HTTP"}),","," ",(0,g.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:"Websocket"}),","," ",(0,g.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:"WebRTC"})," ","or"," ",(0,g.jsx)("a",{href:"/replication-firestore.html",target:"_blank",children:"Firestore"}),"."]})]}),(0,g.jsx)("div",{className:"half right",children:(0,g.jsxs)("div",{className:"replication-icons",children:[(0,g.jsx)("img",{"data-src":"./files/logo/logo.svg",alt:"RxDB",className:"replicate-logo tilt-to-mouse lazyload"}),(0,g.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xl centered replicate-graphql enlarge-on-mouse",children:(0,g.jsx)("img",{"data-src":"./files/icons/graphql-text.svg",alt:"GraphQL",className:"protocol lazyload"})})}),(0,g.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xl centered replicate-couchdb enlarge-on-mouse",children:(0,g.jsx)("img",{"data-src":"./files/icons/couchdb-text.svg",alt:"CouchDB",className:"protocol lazyload"})})}),(0,g.jsx)("a",{href:"/replication-http.html",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-xs centered replicate-rest enlarge-on-mouse",children:["{"," HTTP ","}"]})}),(0,g.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xs centered replicate-websocket enlarge-on-mouse",children:"websocket"})}),(0,g.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xs centered replicate-webrtc enlarge-on-mouse",children:"WebRTC"})})]})}),(0,g.jsx)("div",{className:"clear"})]})}),(0,g.jsx)("a",{href:"/code",target:"_blank",children:(0,g.jsxs)("div",{className:"trophy",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/github-star-with-logo.svg",alt:"RxDB github star"}),(0,g.jsxs)("div",{style:{flex:1},children:[(0,g.jsx)("div",{className:"subtitle",children:"Open Source on"}),(0,g.jsx)("div",{className:"title",children:"GitHub"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:"valuetitle",children:"stars"}),(0,g.jsxs)("div",{className:"value",children:["20172",(0,g.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,g.jsxs)("div",{className:"block offline-first dark",children:[(0,g.jsx)("div",{className:"offline-image-wrapper",children:(0,g.jsx)("img",{"data-src":"files/icons/wifi/wifi_1a202c.svg",className:"offline-image beating-second lazyload",alt:"offline"})}),(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h2",{children:["Online ",(0,g.jsx)("b",{className:"underline",children:"is optional"})]}),(0,g.jsxs)("div",{className:"full-width",children:[(0,g.jsx)("div",{className:"half left",children:(0,g.jsxs)("p",{children:["RxDB follows the"," ",(0,g.jsx)("a",{href:"/offline-first.html",target:"_blank",children:"Offline First"})," ","paradigm where an application must work as well offline as it does online. This is done by persisting data locally on the client side and replicating it in the background. RxDB can even be used solely on the client side, with no backend at all."]})}),(0,g.jsx)("div",{className:"half right",children:(0,g.jsxs)("ul",{className:"checked",children:[(0,g.jsxs)("li",{children:["Your application still ",(0,g.jsx)("b",{children:"works offline"})]}),(0,g.jsxs)("li",{children:["Increases ",(0,g.jsx)("b",{children:"perceived performance"})]}),(0,g.jsxs)("li",{children:["Easier and ",(0,g.jsx)("b",{children:"faster implementation"})]}),(0,g.jsxs)("li",{children:["Needs less backend resources and ",(0,g.jsx)("b",{children:"scales better"})]})]})})]})]})]}),(0,g.jsx)("div",{className:"block frameworks",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/angular",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-10%",left:"10%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/angular.svg",alt:"angular"}),"Angular"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"10%",left:"58%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/capacitor.svg",alt:"capacitor"}),"Capacitor"]}),(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"-4%",left:"44%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/deno.svg",alt:"deno"}),"Deno"]}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/node",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-5%",left:"85%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/nodejs.svg",alt:"Node.js"}),"Node.js"]})}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"4%",left:"26%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/react.svg",alt:"React"}),"React"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"15%",left:"90%",marginLeft:"-35px"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/svelte.svg",alt:"Svelte"}),"Svelte"]}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("h2",{children:["Flexible ",(0,g.jsx)("b",{className:"underline",children:"storage layer"})]}),(0,g.jsxs)("p",{children:["RxDB is based on a storage interface that enables you to swap out the underlying storage engine. This increases code reuse because the same database code can be used in ",(0,g.jsx)("b",{children:"any JavaScript runtime"})," ","by just switching out the storage settings.",(0,g.jsx)("br",{})]}),(0,g.jsxs)("div",{className:"below-text",children:[(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/electron",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"18%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/electron.svg",alt:"electron"}),"Electron"]})}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/vue",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"3%",left:"45%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/vuejs.svg",alt:"Vue.js"}),"Vue.js"]})}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/ionic2",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"71%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/ionic.svg",alt:"ionic"}),"Ionic"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"46%",left:"11%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/nativescript.svg",alt:"NativeScript"}),"NativeScript"]}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react-native",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"35%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/react.svg",alt:"React Native"}),"React Native"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"62%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/nextjs.svg",alt:"Next.js"}),"Next.js"]}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/flutter",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"40%",left:"86%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/flutter.svg",alt:"Flutter"}),"Flutter"]})})]})]})}),(0,g.jsx)("div",{className:"block fifth dark",children:(0,g.jsx)("div",{className:"content centered",children:(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("h2",{children:["Trusted and ",(0,g.jsx)("b",{className:"underline",children:"open source"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/github-star.svg",alt:"github star"}),(0,g.jsx)("div",{className:"label",children:"Github Stars"}),(0,g.jsx)("a",{className:"value",href:"/code",rel:"noopener",target:"_blank",children:"20172"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/download.svg",alt:"npm downloads"}),(0,g.jsx)("div",{className:"label",children:"npm downloads"}),(0,g.jsx)("a",{className:"value beating-number",href:"https://www.npmjs.com/package/rxdb",rel:"noopener",target:"_blank",children:"238572"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"clear"}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/person.svg",alt:"contributor"}),(0,g.jsx)("div",{className:"label",children:"Contributors"}),(0,g.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/graphs/contributors",rel:"noopener",target:"_blank",children:"211"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/commit.svg",alt:"commit"}),(0,g.jsx)("div",{className:"label",children:"Commits"}),(0,g.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/commits/master",rel:"noopener",target:"_blank",children:"10409"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"clear"}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/gear.svg",alt:"gear"}),(0,g.jsx)("div",{className:"label",children:"RxDB made Projects"}),(0,g.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/network/dependents?package_id=UGFja2FnZS0xODM0NzAyMw%3D%3D",rel:"noopener",target:"_blank",children:"1402"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/twitter.svg",alt:"twitter"}),(0,g.jsx)("div",{className:"label",children:"Twitter followers"}),(0,g.jsx)("a",{className:"value",href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",children:"2925"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"clear"})]})})}),(0,g.jsx)("div",{className:"block sixth",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsx)("h2",{children:"Pricing Models"}),(0,g.jsx)("div",{className:"inner",children:(0,g.jsxs)("div",{className:"buy-options",children:[(0,g.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,g.jsxs)("div",{className:"buy-option-inner",children:[(0,g.jsxs)("div",{className:"buy-option-title",children:[(0,g.jsx)("h2",{children:"RxDB Basics"}),(0,g.jsx)("div",{className:"price",children:"Free & Open Source"})]}),(0,g.jsx)("div",{className:"buy-option-features",children:(0,g.jsxs)("ul",{children:[(0,g.jsx)("li",{children:"Basic RxStorages"}),(0,g.jsx)("li",{children:"Realtime Replication"}),(0,g.jsx)("li",{children:"Live Queries"}),(0,g.jsx)("li",{children:"Schema Validation"}),(0,g.jsx)("li",{children:"Multi-Tab Support"}),(0,g.jsx)("li",{children:"Encryption"}),(0,g.jsx)("li",{children:"Compression"})]})}),(0,g.jsx)("a",{href:"/code",target:"_blank",rel:"noopener",onClick:()=>(0,f.h)("get_the_code_main_page",.8),children:(0,g.jsx)("div",{className:"buy-option-action bg-top hover-shadow-top",children:"Get the Code"})})]})}),(0,g.jsx)("div",{className:"buy-option bg-gradient-right-top",children:(0,g.jsxs)("div",{className:"buy-option-inner",children:[(0,g.jsxs)("div",{className:"buy-option-title",children:[(0,g.jsx)("h2",{children:"Premium Plugins"}),(0,g.jsx)("div",{className:"price",children:"for professionals to get the most out of RxDB"})]}),(0,g.jsx)("div",{className:"buy-option-features",children:(0,g.jsxs)("ul",{children:[(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-sqlite.html",target:"_blank",children:"SQLite RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-opfs.html",target:"_blank",children:"OPFS RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-indexeddb.html",target:"_blank",children:"IndexedDB RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-memory-synced.html",target:"_blank",children:"Memory-Synced RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-sharding.html",target:"_blank",children:"Sharding Plugin"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/migration-storage.html",target:"_blank",children:"Storage Migrator"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-shared-worker.html",target:"_blank",children:"Shared Worker"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-worker.html",target:"_blank",children:"Worker"})})]})}),(0,g.jsx)("a",{href:"/premium",onClick:()=>(0,f.h)("request_premium_main_page",3),children:(0,g.jsx)("div",{className:"buy-option-action bg-middle hover-shadow-middle",children:"Request Premium"})})]})}),(0,g.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,g.jsxs)("div",{className:"buy-option-inner",children:[(0,g.jsxs)("div",{className:"buy-option-title",children:[(0,g.jsx)("h2",{children:"Consulting Session"}),(0,g.jsx)("div",{className:"price",children:"fast in person consulting"})]}),(0,g.jsx)("div",{className:"buy-option-features",children:(0,g.jsxs)("p",{children:["Book a one hour consulting session with the RxDB maintainer. I will answer all your questions, give proposals for your use case and we can even do a pair programming session if you have a specific problem in your source code.",(0,g.jsx)("br",{}),"You can book this by doing a one-time donation via github sponsors."]})}),(0,g.jsx)("a",{href:"https://github.com/sponsors/pubkey?frequency=one-time&sponsor=pubkey",target:"_blank",onClick:()=>(0,f.h)("consulting_session_request_main_page",4),children:(0,g.jsx)("div",{className:"buy-option-action bg-bottom hover-shadow-bottom",children:"Book Now"})})]})})]})})]})}),(0,g.jsx)("div",{className:"block last dark",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h2",{children:["Start using ",(0,g.jsx)("b",{className:"underline",children:"RxDB"})," today"]}),(0,g.jsxs)("div",{className:"buttons full-width",children:[(0,g.jsx)("a",{href:"/quickstart.html",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("start_now_main_bottom",.4),children:(0,g.jsx)("div",{className:"button get-premium",style:{left:"50%",top:"20%",marginLeft:"-122px"},children:"Start now"})}),(0,g.jsx)("a",{href:"/newsletter",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("newsletter_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{left:"25%",marginLeft:"-90px"},children:"Get the Newsletter"})}),(0,g.jsx)("a",{href:"/chat",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("join_chat_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{left:"77%",top:"6%",marginLeft:"-70.5px"},children:"Join the Chat"})}),(0,g.jsx)("a",{href:"/premium",onClick:()=>(0,f.h)("get_premium_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{top:"40%",left:"20%",marginLeft:"-70.5px"},children:"Get Premium"})}),(0,g.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("follow_twitter_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{top:"44%",left:"73%",marginLeft:"-85px"},children:"Follow on Twitter"})}),(0,g.jsx)("a",{href:"/code",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("get_code_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{top:"54%",left:"32%",marginLeft:"-70px"},children:"Get the Code"})})]})]})})]})})]})}const j=["NoSQL","OfflineFirst","JavaScript","observable","reactive","realtime","client side","fast"],w=["for the Web","for Node.js","for Browsers","for Capacitor","for Electron","for hybrid apps","for PWAs","for React Native","for NativeScript","for UI apps","you deserve","that syncs"],k=851;function _(){const e=((new Date).getTime()-196e7)/k,t=Math.floor(e);return{ratio:e,period:t,timeToNextPeriod:(e-t)*k}}const N=22,D=-1*N;function R(e){return eN?N:e}function I(){return Math.random()<.5}function E(e,t){let r,a,n=(e=e.slice(0)).length;for(;n;)a=Math.floor(C(t)*n--),r=e[n],e[n]=e[a],e[a]=r,++t;return e}function C(e){const t=1e4*Math.sin(e++);return t-Math.floor(t)}function S(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function s(e){return Array.isArray(e)}function i(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>i,Sd:()=>o,dG:()=>a,jw:()=>l,k_:()=>s})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>i,Dr:()=>s,ND:()=>n,Ve:()=>d,dY:()=>a,em:()=>o,h$:()=>h,vN:()=>c});Promise.resolve(!0);var s=Promise.resolve(!1),i=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function d(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function h(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/1df93b7f.acfb5901.js b/docs/assets/js/1df93b7f.acfb5901.js new file mode 100644 index 00000000000..c84b3252bb8 --- /dev/null +++ b/docs/assets/js/1df93b7f.acfb5901.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[4583],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Kr,C3:()=>Hr,IA:()=>zr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function s(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function i(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var s in t)n[s]=e(t[s]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var d=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},h=new Set(["__proto__","prototype","constructor"]),u=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var s of e)switch(s){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=s),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=s;break}if(h.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=s;break}if("property"===a){if(h.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!u.has(s))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=s}switch(n&&(r+="\\"),a){case"property":if(h.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!d(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var _=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])}((0,j.A)(Error)),N=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}])}((0,j.A)(TypeError));function D(e,t){return new _(e,w.tunnelErrorMessage(e),t)}function R(e,t){return new N(e,w.tunnelErrorMessage(e),t)}function I(e){return!(!e||409!==e.status)&&e}var E={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var C=/\./g,S="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw D("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function W(e){var t=q((e=i(e)).primaryKey);e.properties=i(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=F,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=Q(e);(0,y.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,y.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var F={type:"object",properties:{lwt:{type:"number",minimum:T,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function Q(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=q(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var z="docs",H="changes",K="attachments",Z="dexie",U=new Map,J=new Map;var V="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return V+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(V)?"|"+e.substring(V.length):e}function X(e,t){return t?(t=te(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=q(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,y.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function se(e,t){return e+"||"+t}function ie(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,y.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===A(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,y.jw)(r)):r}var oe=r(9092),ce=r(5734),le=r(3337),de=String.fromCharCode(65535),he=Number.MIN_SAFE_INTEGER;function ue(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),s=new Set;Object.keys(r).forEach((t=>{var a=A(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&s.add(t)}));var i,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!s.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,d=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],s={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);s=Object.assign(s,r)}})):s={startKey:l?he:de,endKey:a?de:he,inclusiveStart:!0,inclusiveEnd:!0};return void 0===s.startKey&&(s.startKey=he),void 0===s.endKey&&(s.endKey=de),void 0===s.inclusiveStart&&(s.inclusiveStart=!0),void 0===s.inclusiveEnd&&(s.inclusiveEnd=!0),l&&!s.inclusiveStart&&(l=!1),a&&!s.inclusiveEnd&&(a=!1),s})),h=d.map((e=>e.startKey)),u=d.map((e=>e.endKey)),m={index:e,startKeys:h,endKeys:u,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!s.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,h,u)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},s=10,i=(0,y.Sd)(r.startKeys,(e=>e!==he&&e!==de));n(i*s);var o=(0,y.Sd)(r.startKeys,(e=>e!==de&&e!==he));n(o*s);var c=(0,y.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*s*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,i=m)})),!i)throw D("SNH",{query:t});return i}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var s=[],i=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var d=l[0];if(d&&i.add(o),"$eq"!==d){if(s.length>0)return!1;s.push(d)}}var h=[],u=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var v=f[0];if(v&&u.add(m),"$eq"!==v){if(h.length>0)return!1;h.push(v)}}var g=0;for(var y of e){for(var b of[i,u]){if(!b.has(y)&&b.size>0)return!1;b.delete(y)}if(r[g]!==a[g]&&i.size>0&&u.size>0)return!1;g++}return!0}var ge=r(744),ye=r(2779),be=r(1692),xe=r(4903),je=r(7705),we=r(2403),ke=r(6776),_e=r(6950),Ne=r(6823),De=!1;function Re(e){return De||((0,ye.DZ)(ye.hu.PIPELINE,{$sort:xe.xF,$project:xe.C2}),(0,ye.DZ)(ye.hu.QUERY,{$and:je.a6,$eq:we.XV,$elemMatch:_e.Jy,$exists:Ne.P,$gt:we.MR,$gte:we.fy,$in:we.oZ,$lt:we.NV,$lte:we.Q_,$ne:we.C5,$nin:we.GU,$mod:ke.Pp,$nor:je.q3,$not:je.En,$or:je.sU,$regex:ke.WP,$size:_e.Ig,$type:Ne.T}),De=!0),new be.X(e)}function Ie(e,t){var r=q(e.primaryKey);t=i(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,y.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var s=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&s.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,y.k_)(e)?e:[e],r=t.findIndex((e=>!s.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ee(e,t){if(!t.sort)throw D("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,s=Object.keys(e)[0],i=Object.values(e)[0];r.push({key:s,direction:i,getValueFn:(t=s,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Se(e){return e===he?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===de||!0===r?"1":"0":r}function Pe(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Se),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Se);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function $e(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,s=n+(a.limit?a.limit:1/0),i=t.queryPlan,o=!1;i.selectorSatisfiedByIndex||(o=Ce(e.schema,t.query));var c=Pe(r.booleanIndexes,i,r.dexieDb._options.IDBKeyRange),l=i.index,d=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(z);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||d.push(n),i.sortSatisfiedByIndex&&d.length===s?e():a.continue()}else e()}}))})),!i.sortSatisfiedByIndex){var h=Ee(e.schema,t.query);d=d.sort(h)}return{documents:d=d.slice(n,s)}}function Te(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Be(e){return parseInt(e.split("-")[0],10)}function Ae(e,t){var r=t?t._rev:null;return(r?Te(r).height:0)+1+"-"+e}var Me="_rxdb_internal";async function qe(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function We(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:w.deepFreezeWhenDevMode(a),previousDocumentData:w.deepFreezeWhenDevMode(n)}}function Fe(e,t,r,a){if(a)throw 409===a.status?D("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?D("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function Qe(e){return{previous:e.previous,document:ze(e.document)}}function ze(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=i(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,s,i;t._attachments[r]=(i=(n=a).data)?{length:(s=i,atob(s).length),digest:n.digest,type:n.type}:n})),t}function He(e){var t=i(e);return t._meta=i(e._meta),t}function Ke(e,t,r){w.deepFreezeWhenDevMode(r);var a=q(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,s){var o=n.map((n=>function(n){var s=i(n.document);if(s._meta=i(s._meta),w.isDevMode()){s=M(a,r,s);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw D("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw D("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return s._meta.lwt=(0,ce.t)(),s._rev=Ae(e.token,n.previous),{document:s,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,s))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var i=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Ae(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(i,s))).then((e=>((0,y.Hb)(a.error,e.error),(0,y.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=i(Object.assign({},e.output.documentData,{_meta:B(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ze=r(3561),Ue=r(703),Je=new Map;function Ve(e,t){var r=Je.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Je.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Je.get(t);return n||(n={bc:new Ue.X2(["RxDB:",e,r].join("|")),refs:new Set},Je.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),s=new oe.B,i=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&s.next(r.eventBulk)};n.addEventListener("message",i);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return s.asObservable().pipe((0,Ze.X)(o))};var d=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),d()};var h=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),h()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,s,i){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=s,this.settings=i,this.primaryPath=q(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw D("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},s=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var i=new Map;(await ne(this.internals,s)).forEach((e=>{var t=e;return t&&i.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,s,i){for(var o,c=!!e.schema.attachments,l=[],d=[],h=[],u={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=u.events,p=[],f=[],v=[],g=r.size>0,y=a.length,b=function(){var e,n=a[x],u=n.document,y=n.previous,b=u[t],j=u._deleted,w=y&&y._deleted,k=void 0;if(g&&(k=r.get(b)),k){var _=k._rev;if(!y||y&&_!==y._rev){var N={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return h.push(N),1}var R=c?Qe(n):n;c&&(j?y&&Object.keys(y._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.ZN)(y)._attachments[e].digest})})):(Object.entries(u._attachments).find((t=>{let[r,a]=t;return(y?y._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(u._attachments).forEach((e=>{let[t,r]=e;var a=y?y._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?h.push(e):(c?(d.push(Qe(R)),i&&i(u)):(d.push(R),i&&i(u)),o=R);var I=null,E=null,C=null;if(w&&!j)C="INSERT",I=c?ze(u):u;else if(!y||w||j){if(!j)throw D("SNH",{args:{writeRow:n}});C="DELETE",I=(0,le.ZN)(u),E=y}else C="UPDATE",I=c?ze(u):u,E=y;var S={documentId:b,documentData:I,previousDocumentData:E,operation:C};m.push(S)}else{var O=!!j;if(c&&Object.entries(u._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},h.push(e))})),e||(c?(l.push(Qe(n)),s&&s(u)):(l.push(n),s&&s(u)),o=n),!O){var P={documentId:b,operation:"INSERT",documentData:c?ze(u):u,previousDocumentData:c&&y?ze(y):y};m.push(P)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>se(e.documentId,e.attachmentId))))})),(r=(0,le.ZN)(r)).eventBulk.events.length>0){var i=(0,le.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:i[this.primaryPath],lwt:i._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),$e(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,s=Pe(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),i=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(z);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(s);i=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),i}(this,e);return{count:t,mode:"fast"}}return{count:(await $e(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=se(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=J.get(e)-1;0===r?(t.dexieDb.close(),J.delete(e)):J.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=s(U,o,(()=>{var e=(async()=>{var e=i(r);e.autoOpen=!1;var t=new a.cf(o,e),s={[z]:ae(n),[H]:"++sequence, id",[K]:"id"};return t.version(1).stores(s),await t.open(),{dexieDb:t,dexieTable:t[z],dexieAttachmentsTable:t[K],booleanIndexes:ie(n)}})();return U.set(o,c),J.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(Z,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=Z,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw D("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw D("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw D("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var s=n[a];if(!nt(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}var st={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function it(e,t){st[e]&&st[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(st[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,y.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=q(this.jsonSchema.primaryKey),this.finalFields=Q(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw D("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=A(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}])}();function lt(e,t,r){void 0===r&&(r=!0),r&&it("preCreateRxSchema",e);var a=W(e);a=function(e){return o(e,!0)}(a),w.deepFreezeWhenDevMode(a);var n=new ct(a,t);return it("createRxSchema",n),n}var dt=r(7708),ht=r(8146),ut=r(3356),mt=r(5520),pt=r(8609),ft=r(1753);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((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 ")}function gt(e){return e.documentData?e.documentData:e.previousDocumentData}var yt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=s(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var s={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.ZN)(a).push(s),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,s,i,o=(n=a.map((e=>e.lastKnownDocumentState)),s=n[0],i=Te(s._rev).height,n.forEach((e=>{var t=Te(e._rev).height;t>i&&(s=e,i=t)})),s),l=o;for(var d of a)try{l=await d.modifier(c(l))}catch(h){d.reject(h),d.reject=()=>{},d.resolve=()=>{}}try{await this.preWrite(l,o)}catch(h){return void a.forEach((e=>e.reject(h)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,i=n(t,a),o=I(e);if(o){var c=s(this.queueByDocId,a,(()=>[]));i.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.ZN)(o.documentInDb),(0,le.ZN)(c).unshift(e)}))}else{var l=D("COL20",{name:E[(r=e).status],document:r.documentId,writeError:r});i.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={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.$.pipe((0,dt.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,ht.p)((e=>!e.isLocal)),(0,ht.p)((e=>e.documentId===this.primary)),(0,dt.T)((e=>gt(e))),(0,ut.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,dt.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.t)(le.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(w.isDevMode()){if(e.includes(".item."))throw D("DOC1",{path:e});if(e===this.primaryPath)throw D("DOC2");if(this.collection.schema.finalFields.includes(e))throw D("DOC3",{path:e});if(!A(this.collection.schema.jsonSchema,e))throw D("DOC4",{path:e})}return this.$.pipe((0,dt.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=A(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.$A;if(!t)throw D("DOC5",{path:e});if(!t.ref)throw D("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw D("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return s(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return w.deepFreezeWhenDevMode(t);var r=this;return new Proxy(i(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var s=a.slice(0,-2);return r.get$$($(e+"."+s))}if("$"===n){var i=a.slice(0,-1);return r.get$($(e+"."+i))}if("_"===n){var o=a.slice(0,-1);return r.populate($(e+"."+o))}return r.get($(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return w.deepFreezeWhenDevMode(this._data);var t=i(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,w.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=i(e),this._data._deleted)throw D("DOC11",{id:this.primary,document:this});await wt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Fe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(D("DOC13",{document:this,id:this.primary}));var t,r=i(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Fe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw D("DOC14")}};function jt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function wt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),w.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(2198),_t=r(511),Nt=r(4157),Dt=r(2442),Rt=r(6114);function It(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Et=new WeakMap;function Ct(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return s(Et,e,(()=>{var t=e.collection,r=Ie(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ee(t.schema.jsonSchema,r),s=Ce(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:It(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>s({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.ZN)(e._result).docsData.slice(0),n=(0,le.ZN)(e._result).docsDataMap,i=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:w.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(y.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},s=(0,Rt.kC)(t);return"runFullQueryAgain"===s||("doNothing"!==s?(i=!0,(0,Rt.Cs)(s,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:i,newResults:a}}var St=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return s(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Pt(e){return e.refCount$.observers.length}var $t,Tt,Bt=($t=100,Tt=3e4,(e,t)=>{if(!(t._map.size<$t)){var r=(0,ce.t)()-Tt,a=[],n=Array.from(t._map.values());for(var s of n)Pt(s)>0||(0===s._lastEnsureEqual&&s._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,i).forEach((e=>Ot(t,e)))}}),At=new WeakSet;var Mt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=gt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=w.deepFreezeWhenDevMode,i=e.documentCreator,o=o=>{var c=o[t],l=Be(o._rev),d=s(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),h=d.byRev,u=h.get(l),m=u?u.deref():void 0;return m||(o=n(o),m=i(o),h.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Be(e.revision)})})))}))))),m};return o}(this))}}])}();function qt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Wt=function(){return(0,b.A)((function(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=qt(this.collection._docCache,t)}),[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Wt(this.collection,e,e.length);this._result=t}else this._result=new Wt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw D("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var s=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,y.Hb)(t,n)}}else{var s=e.isFindOneByIdQuery,i=e.collection._docCache.getLatestDocumentDataIfExists(s);if(!i){var o=await r.storageInstance.findDocumentsById([s],!1);o[0]&&(i=o[0])}i&&!i._deleted&&t.push(i)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return s.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw D("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,_t._)(this.$))).then((t=>{if(!t&&e)throw D("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Ie(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),it("prePrepareQuery",e);var t=Zt(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,ht.p)((e=>!e.isLocal)),(0,ut.Z)(null),(0,Dt.Z)((()=>Kt(this))),(0,dt.T)((()=>this._result)),(0,pt.t)(le.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,le.ZN)(t).time))),(0,ht.p)((e=>!!e)),(0,dt.T)((e=>{var t=(0,le.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,Nt.h)(e,this.refCount$.pipe((0,ht.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Ce(0,Ie(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}])}();function zt(e,t,r,a){it("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,s,i=new Qt(e,t,r,a);return i=(n=i).collection._queryCache.getByQuery(n),s=r,At.has(s)||(At.add(s),(0,ft.dY)().then((()=>(0,ft.Ve)(200))).then((()=>{s.destroyed||s.cacheReplacementPolicy(s,s._queryCache),At.delete(s)}))),i}function Ht(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||Ht(e)?ft.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||Ht(e))return ft.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var s=(0,le.ZN)(e._result).count,i=s;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&i++,r&&!a&&i--})),i!==s&&(t=!0,e._setResultData(i))}else{var o=Ct(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var i=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:s,devMode:w.isDevMode()});await i.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),i){var d=o.map((e=>{var t=He(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Ae(r,e),{previous:e,document:t}}));await t.bulkWrite(d,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,ht.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var sr=new WeakMap;function ir(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return it("createRxDocument",a),a}(function(e){return s(sr,e,(()=>jt(ir(e))))}(e),e,w.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),it("postCreateRxDocument",r),r}var cr=function(e,t){return nt(ze(e.newDocumentState),ze(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],dr=["insert","save","remove","create"],hr=!1,ur=function(){function e(e,t,r,a,n,s,i,o,c,l,d,h){void 0===n&&(n={}),void 0===s&&(s={}),void 0===i&&(i={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Bt),void 0===d&&(d={}),void 0===h&&(h=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new St,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=s,this.methods=i,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=d,this.conflictHandler=h,function(e){if(hr)return;hr=!0;var t=Object.getPrototypeOf(e);dr.forEach((e=>{lr.map((r=>{var a=r+P(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new yt(this.storageInstance,this.schema.primaryPath,((e,t)=>wt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,ht.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Dt.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,dt.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Mt(this.schema.primaryPath,this.$.pipe((0,ht.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>We(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.em},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration-schema")},t.getMigrationState=function(){throw vt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Fe(this,e[this.schema.primaryPath],e,r),(0,le.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),s=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),i=qt(this._docCache,s.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(i.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:i,error:s.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],s=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),s.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=i(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",s.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw D("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),s=a.success.slice(0),i=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)i.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));s.push(l)}}))),{error:i,success:s}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Fe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw D("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw D("COL5",{queryObj:e});return e||(e={selector:{}}),zt("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=zt("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw D("QU6");(e=i(e)).limit=1,t=zt("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),zt("count",e,this)},t.findByIds=function(e){return zt("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!dr.includes(t))throw D("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw D("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),s=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][s].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.em;var s=n.series.map((e=>()=>e(r,a)));return(0,ft.h$)(s).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,ht.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,ht.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,ht.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}])}();var mr=r(7635),pr=r(1007);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.sc)(e))},vr=r(5525),gr=new Set,yr=function(){function e(e,t,r,a,n,s,i,o,c,l,d,h,u){void 0===i&&(i=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,Dt.Z)((e=>e.events))),this.storageToken=ft.Dr,this.storageTokenDocument=ft.Dr,this.emittedEventBulkIds=new vr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=s,this.eventReduce=i,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=d,this.allowSlowCount=h,this.reactivity=u,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Vt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Jt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:B(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var s=(0,le.ZN)(n.error[0]);if(s.isError&&I(s)){var i=s;if(c=i.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw D("DM5",{args:{database:e.name,databaseStateVersion:i.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==i.documentInDb.data.passwordHash)throw D("DB1",{passwordHash:r,existingPasswordHash:i.documentInDb.data.passwordHash});var o=i.documentInDb;return(0,le.ZN)(o)}var c,l;throw s}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw D("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await qe(this.internalStore,Gt(tr(e,t),Ut));if(!r)throw D("SNH",{name:e,schema:t});var a=He(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[s,o]=e;var c=s,l=o.schema;t[c]=l;var d=lt(l,this.hashFunction);if(r[c]=d,this.collections[s])throw D("DB3",{name:s});var h=tr(s,l),u={id:Gt(h,Ut),key:h,context:Ut,data:{name:c,schemaHash:await d.hash,schema:d.jsonSchema,version:d.version,connectedStorages:[]},_deleted:!1,_meta:B(),_rev:"",_attachments:{}};a.push({document:u});var m=Object.assign({},o,{name:c,schema:d,database:this}),p=i(o);p.database=this,p.name=s,it("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var s=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(s.error.map((async e=>{if(409!==e.status)throw D("DB12",{database:this.name,writeError:e});var a=(0,le.ZN)(e.documentInDb),n=a.data.name,s=r[n];if(a.data.schemaHash!==await s.hash)throw D("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await s.hash,previousSchema:a.data.schema,schema:(0,le.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:s={},autoMigrate:i=!0,statics:o={},methods:c={},attachments:l={},options:d={},localDocuments:h=!1,cacheReplacementPolicy:u=Bt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:w.isDevMode()};return it("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new ur(t,r,a,e,n,s,c,l,d,u,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.em;return i&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(it("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:s,methods:c,attachments:l,options:d,cacheReplacementPolicy:u,localDocuments:h,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.addState=function(e){throw vt("state")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>gr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),s=await Yt(n),i=new Set;s.forEach((e=>i.add(e.data.name)));var o=Array.from(i);return await Promise.all(o.map((s=>ar(t,n,a,e,s,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}])}();async function br(e,t,r,a,n,s){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Me,schema:Vt,options:a,multiInstance:n,password:s,devMode:w.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s=!0,eventReduce:i=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:d=!1,localDocuments:h=!1,hashFunction:u=fr,reactivity:m}=e;it("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}),o||function(e,t){var r=t.name+"|"+e;if(gr.has(r))throw D("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),gr.add(t.name+"|"+a);var p=O(10);return br(p,t,a,r,s,n).catch((e=>{throw gr.delete(t.name+"|"+a),e})).then((e=>{var f=new yr(a,p,t,r,n,s,i,c,e,u,l,d,m);return ot("createRxDatabase",{database:f,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}}).then((()=>f))}))}var jr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Qt.prototype,RxCollection:ur.prototype,RxDatabase:yr.prototype},wr=new Set,kr=new Set;var _r=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.A)(t,e),t}(jt()),Nr={get isLocal(){return!0},get allAttachments$(){throw D("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,ht.p)((e=>e.documentId===this.primary)),(0,ht.p)((e=>e.isLocal)),(0,dt.T)((e=>gt(e))),(0,ut.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,dt.T)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.t)(le.bz))},get $$(){var e=this;return Ir(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Ir(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=v(this._data,e);return t=w.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,w.isDevMode()){if(e.includes(".item."))throw D("LD3",{objPath:e});if(e===this.primaryPath)throw D("LD4")}return this.$.pipe((0,dt.T)((e=>e._data)),(0,dt.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){return Ir(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=i(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:B(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Dr=!1,Rr=()=>{if(!Dr){Dr=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Nr,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Nr,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Nr[e]=(e=>()=>{throw D("LD6",{functionName:e})})(e)))}};function Ir(e){var t=e.parent;return t instanceof yr?t:t.database}var Er=new WeakMap,Cr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Pr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Ar);var n=new Mt("id",e.$.pipe((0,ht.p)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new _r(e.id,e,t);return Object.setPrototypeOf(r,Nr),r.prototype=Nr,r}(t,e))),s=new yt(a,"id",(()=>{}),(()=>{})),i=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:i,events:r.events.map((t=>We(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:s};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw D("LD8",{database:r.name,collection:a})}return t}function Pr(e,t,r,a,n,s){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Br(a),schema:Ar,options:n,multiInstance:s,devMode:w.isDevMode()})}function $r(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function Tr(e,t,r){var a=O(10),n=await Pr(a,e,t,r,{},!1);await n.remove()}function Br(e){return"plugin-local-documents-"+e}var Ar=W({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Mr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:B(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function qr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):qe(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Wr(e){return this.$.pipe((0,ut.Z)(null),(0,Dt.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Dt.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,ht.p)((e=>e.use)),(0,dt.T)((e=>e.doc)))}var Fr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Mr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Wr},RxDatabase:e=>{e.insertLocal=Mr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Wr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>$r(e)},postDestroyRxCollection:{after:e=>$r(e)},postRemoveRxDatabase:{after:e=>Tr(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Tr(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Qr;function zr(){return"undefined"!=typeof window&&window.indexedDB}function Hr(){return Qr||(Qr=(async()=>{!function(e){if(it("preAddRxPlugin",{plugin:e,plugins:wr}),!wr.has(e)){if(kr.has(e.name))throw D("PL3",{name:e.name,plugin:e});if(wr.add(e),kr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(jr[t])})),e.overwritable&&Object.assign(w,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&st[t].push(r.after),r.before&&st[t].unshift(r.before)}))}}(Fr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Qr}const Kr=["#e6008d","#8d2089","#5f2688"]},1527:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{h:()=>a})},6866:(e,t,r)=>{r.r(t),r.d(t,{default:()=>x});var a=r(4586),n=r(1595),s=r(5260),i=(r(6879),r(4157)),o=r(943),c=r(7708),l=r(5520),d=r(3337),h=r(1753),u=r(5734),m=r(2658),p=r(6540),f=r(1527),v=r(4589),g=r(4848);let y=!1;async function b(){if(y)return;y=!0,console.log("start animation");if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return void console.log("reducedMotion is set to true");if(!(0,m.IA)())return;const e=await(0,m.C3)();try{await e.insertLocal("beatingvalues",{beatPeriod:0,text1:"JavaScript",text2:"you deserve",color:m.Tj[0]})}catch(N){}const t=(0,d.ZN)(await e.getLocal("beatingvalues"));(async()=>{for(await(0,h.ND)(k);y;){const e=_(),r=(0,h.ND)(e.timeToNextPeriod);if(e.period%2==0)try{await t.incrementalModify((t=>(t.beatPeriod>=e.period||(t.beatPeriod=e.period,t.color=m.Tj[e.period%3],e.period%4==0?t.text1=E(j,e.period)[0]:t.text2=E(w,e.period)[0]),t)))}catch(N){}await r}})();const r=await e.upsertLocal("mousepos",{x:0,y:0,time:0});let a=[];window.addEventListener("mousemove",(e=>{a=[e.clientX,e.clientY]})),(0,i.h)((0,o.R)(window,"mousemove"),(0,o.R)(window,"scroll"),(0,o.R)(window,"resize")).subscribe((()=>{r.incrementalPatch({x:a[0],y:a[1],time:(0,u.t)()})})),function(e){const t=document.getElementsByClassName("tilt-to-mouse"),r=100;function a(e,t,a){const n=a.getBoundingClientRect(),s=-(t-n.y-n.height/2)/r,i=(e-n.x-n.width/2)/r;return`perspective(150px) rotateX(${R(s)}deg) rotateY(${R(i)}deg) `}function n(e,t){e.style.transform=a.apply(null,t)}e.$.subscribe((e=>{e._data.data.time&&Array.from(t).forEach((t=>{if(!S(t))return;n(t,(0,d.ZN)([e._data.data.x,e._data.data.y]).concat([t]))}))}))}(r),function(e){const t=document.getElementsByClassName("enlarge-on-mouse");function r(e){const t=e.getBoundingClientRect();return{centerX:t.left+t.width/2,centerY:t.top+t.height/2,width:t.width,height:t.height}}function a(e,t){const r=`scale(${t})`;e.style.transform=r}e.$.pipe((0,c.T)((e=>e._data))).subscribe((e=>{e.data.time&&e.data.x&&e.data.y&&Array.from(t).forEach((t=>{if(!S(t))return;const n=r(t),s=e.data.x-n.centerX,i=e.data.y-n.centerY,o=Math.sqrt(s*s+i*i);function c(e){return 1.9^e}let l=1+n.width/2/c(o+300);l>1.5&&(l=1.5),l<1.01&&(l=1),a(t,l)}))}))}(r);const n=document.getElementsByClassName("beating"),s=document.getElementsByClassName("beating-first"),p=document.getElementsByClassName("beating-second"),f=document.getElementsByClassName("beating-number"),v=document.getElementsByClassName("beating-color"),g=document.getElementsByClassName("beating-color-string"),b=[];let x=0;_(),t.$.pipe((0,c.T)((e=>e._data.data)),(0,l.F)(((e,t)=>JSON.stringify(e)===JSON.stringify(t)))).subscribe((e=>{b.forEach((function(e){e(x)})),x+=1;const t=e.color;Array.from(v).forEach((function(e){e.style.backgroundColor=t})),Array.from(g).forEach((function(e){e.innerHTML=t}))})),b.push((function(){Array.from(n).forEach((function(e){e.style.animationDuration=k+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(s).forEach((function(e){e.style.animationDuration=k+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(p).forEach((function(e){e.style.animationDuration=k+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")}))})),b.push((function(){Array.from(f).forEach((function(e){I()&&I()&&setTimeout((function(){const t=parseFloat(e.innerHTML)+1;e.innerHTML=t+""}),105)}))}))}function x(){const{siteConfig:e}=(0,a.A)();(0,p.useEffect)((()=>(b(),()=>{console.log("stop animation"),y=!1})));return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(s.A,{children:(0,g.jsx)("body",{className:"homepage"})}),(0,g.jsx)(n.A,{title:`${e.title}`,description:"RxDB is a fast, local-first NoSQL-database for JavaScript Applications like Websites, hybrid Apps, Electron-Apps, Progressive Web Apps and Node.js",children:(0,g.jsxs)("main",{children:[(0,g.jsx)("div",{className:"block first centered dark",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h1",{children:["The local ",(0,g.jsx)("b",{className:"underline",children:"Database"})," for"," ",(0,g.jsx)("b",{className:"underline",children:"JavaScript"})," Applications"]}),(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("div",{className:"half left",children:[(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("ul",{className:"checked",children:[(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Realtime Queries"}),": From results of queries to single document fields, with RxDB you can observe everything which makes building ",(0,g.jsx)("u",{children:"realtime applications"})," effortless."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Realtime Replication"}),": Run a two-way realtime replication with one of the many replication plugins. Also making your ",(0,g.jsx)("u",{children:"custom backend compatible"})," is pretty simple."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Offline Support"}),": Store data locally on your clients device to build applications that still work when there is ",(0,g.jsx)("u",{children:"no internet access"}),". Running queries locally also improves your user experience."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Supports all JavaScript runtimes"}),": With the flexible RxDB storage layer you can run the same code in ",(0,g.jsx)("u",{children:"Browsers"}),", ",(0,g.jsx)("u",{children:"Node.js"}),", ",(0,g.jsx)("u",{children:"Electron"}),","," ",(0,g.jsx)("u",{children:"React-Native"}),", ",(0,g.jsx)("u",{children:"Capacitor"}),", ",(0,g.jsx)("u",{children:"Bun"})," and ",(0,g.jsx)("u",{children:"Deno"}),"."]}),(0,g.jsxs)("li",{children:[(0,g.jsx)("b",{children:"Great Performance"}),": Years of performance optimization made RxDB one of the ",(0,g.jsx)("u",{children:"fastest"})," ways to store and query data inside of JavaScript."]})]}),(0,g.jsx)("a",{className:"button",href:"/quickstart.html",target:"_blank",onClick:()=>(0,f.h)("start_now",.4),children:"Quickstart \xbb"}),(0,g.jsxs)("a",{className:"button light",href:"/code",target:"_blank",children:[(0,g.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",className:"star-icon","aria-hidden":"true",fill:"currentColor",style:{width:14,marginRight:8,marginLeft:-6,float:"left",marginTop:2},children:(0,g.jsx)("path",{d:"M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"})}),"Star (20,172)"]}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"half right",style:{display:"flex",alignItems:"center",justifyContent:"center"},children:(0,g.jsxs)("div",{className:"content-canvas",style:{marginTop:0,marginBottom:30,marginLeft:20},children:[(0,g.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,g.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,g.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms"}})})}),(0,g.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,g.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,g.jsx)("img",{src:"/files/logo/logo_text.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms",width:"52%"}})})}),(0,g.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,g.jsx)("div",{className:"beating-color one",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,g.jsx)("div",{className:"beating-color two",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,g.jsx)("div",{className:"beating-color three",style:{backgroundColor:"rgb(141, 32, 137)"}})]})]})})]})]})}),(0,g.jsx)("a",{href:"/chat",target:"_blank",children:(0,g.jsxs)("div",{className:"trophy discord",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/discord.svg",alt:"RxDB Discord chat"}),(0,g.jsxs)("div",{style:{flex:1},children:[(0,g.jsx)("div",{className:"subtitle",children:"Chat on"}),(0,g.jsx)("div",{className:"title",children:"Discord"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:"valuetitle",children:"members"}),(0,g.jsxs)("div",{className:"value",children:["747",(0,g.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,g.jsxs)("div",{className:"block reviews",children:[(0,g.jsx)("div",{className:"content centered",children:(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("h2",{children:["Our ",(0,g.jsx)("b",{className:"underline",children:"Success Stories"})]}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{})]})}),(0,g.jsxs)(v.A,{dots:!0,centerMode:!0,centerPadding:"10px",infinite:!0,arrows:!1,adaptiveHeight:!0,speed:500,slidesToShow:4,slidesToScroll:1,initialSlide:0,responsive:[{breakpoint:1250,settings:{slidesToShow:3,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:1024,settings:{slidesToShow:3,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:900,settings:{slidesToShow:2,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:600,settings:{slidesToShow:2,slidesToScroll:1,infinite:!0,dots:!0}},{breakpoint:480,settings:{slidesToShow:1.1,centerPadding:"15px",slidesToScroll:1,infinite:!1,dots:!1}}],children:[(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"We use RxDB to create applications capable of being used in the most remote areas where Internet access is really a challenge."'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-white lazyload","data-src":"./files/companies/altgras.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"ALTGRAS"}),(0,g.jsx)("a",{href:"https://altgras.com/",target:"_blank",className:"company-link",children:"https://altgras.com/"})]})]})]}),(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"We provide a mobile app that is used by people in the field to fill in valuable information like inspections, surveys and audits"'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-black lazyload","data-src":"./files/companies/moreapp.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"MoreApp"}),(0,g.jsx)("a",{href:"https://moreapp.com/",target:"_blank",className:"company-link",children:"https://moreapp.com/"})]})]})]}),(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"We use RxDB to provide an offline first, cross platform point of sale system"'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-black lazyload","data-src":"./files/companies/woopos.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"WooCommerce POS"}),(0,g.jsx)("a",{href:"https://wcpos.com/",target:"_blank",className:"company-link",children:"https://wcpos.com/"})]})]})]}),(0,g.jsxs)("div",{className:"slider-content",children:[(0,g.jsx)("h3",{children:'"RxDB is a main component in building offline-ready multichannel apps. It has become our default stack for this kind of apps."'}),(0,g.jsxs)("div",{className:"slider-profile",children:[(0,g.jsx)("img",{className:"slider-logo-black lazyload","data-src":"./files/companies/atroo.png"}),(0,g.jsxs)("div",{className:"slider-info",children:[(0,g.jsx)("p",{className:"developer",children:"atroo GmbH"}),(0,g.jsx)("a",{href:"https://atroo.de/",target:"_blank",className:"company-link",children:"https://atroo.de/"})]})]})]})]})]}),(0,g.jsx)("div",{className:"block second dark",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h2",{children:["Realtime applications ",(0,g.jsx)("b",{className:"underline",children:"made easy"})]}),(0,g.jsxs)("p",{children:["From the results of a query, to a single field of a document, with RxDB you can ",(0,g.jsx)("b",{children:"observe everything"}),". This enables you to build realtime applications ",(0,g.jsx)("b",{children:"fast"})," and ",(0,g.jsx)("b",{children:"reliable"}),". It does not matter if the data was changed by"," ",(0,g.jsx)("b",{children:"a user event"}),", ",(0,g.jsx)("b",{children:"another browser tab"})," or by the",(0,g.jsx)("b",{children:" replication"}),"."," ","Whenever your data changes, your UI reflects the new state. You can either use ",(0,g.jsx)("b",{children:"RxJS"})," or add ",(0,g.jsx)("a",{href:"/reactivity.html",target:"_blank",children:"custom reactiveness libraries"})," like signals or other state management."]}),(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("div",{className:"code half",children:[(0,g.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,g.jsx)("legend",{children:"Write"}),(0,g.jsxs)("samp",{children:[(0,g.jsx)("span",{className:"cm-keyword",children:"await "}),(0,g.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,g.jsx)("span",{className:"cm-method",children:"upsert"}),"(","{",(0,g.jsx)("br",{}),(0,g.jsx)("span",{className:"cm-property",children:"\xa0 id"}),": ",(0,g.jsx)("span",{className:"cm-string",children:"'foobar'"}),",",(0,g.jsx)("br",{}),(0,g.jsx)("span",{className:"cm-property",children:"\xa0 color"}),": ",(0,g.jsxs)("span",{className:"cm-string",children:["'",(0,g.jsx)("span",{className:"beating-color-string beating-color",children:"#e6008d"}),"'"]}),(0,g.jsx)("br",{}),"}",");"]})]}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,g.jsx)("legend",{children:"Observe"}),(0,g.jsxs)("samp",{style:{backgroundColor:"var(--bg-color)"},children:[(0,g.jsx)("span",{className:"cm-keyword",children:"await "}),(0,g.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,g.jsxs)("span",{className:"cm-method",children:["findOne(",(0,g.jsx)("span",{className:"cm-string",children:"'foobar'"}),")"]}),(0,g.jsx)("br",{}),"\xa0.",(0,g.jsx)("span",{className:"cm-property",children:"$"}),(0,g.jsx)("span",{className:"cm-comment",children:" // get observable"}),(0,g.jsx)("br",{}),"\xa0.",(0,g.jsx)("span",{className:"cm-method",children:"subscribe"}),"(",(0,g.jsx)("span",{className:"cm-def",children:"d"}),(0,g.jsx)("span",{className:"cm-operator",children:" =>"})," ","{",(0,g.jsx)("br",{}),(0,g.jsx)("span",{className:"cm-variable",children:"\xa0\xa0 screen"}),".",(0,g.jsx)("span",{className:"cm-property",children:"backgroundColor"}),(0,g.jsx)("span",{className:"cm-operator",children:" = "}),(0,g.jsx)("span",{className:"cm-variable",children:"d"}),".",(0,g.jsx)("span",{className:"cm-property beating-color",children:"color"}),";",(0,g.jsx)("br",{}),"\xa0","}",");"]})]})]}),(0,g.jsx)("div",{className:"canvas half",children:(0,g.jsxs)("div",{className:"content-canvas",children:[(0,g.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,g.jsx)("div",{className:"beating-color",children:(0,g.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,g.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,g.jsx)("div",{className:"beating-color",children:(0,g.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,g.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,g.jsx)("div",{className:"beating-color one"}),(0,g.jsx)("div",{className:"beating-color two"}),(0,g.jsx)("div",{className:"beating-color three"})]})]})})]})]})}),(0,g.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",onClick:()=>(0,f.h)("twitter_trophy_click",.2),target:"_blank",children:(0,g.jsxs)("div",{className:"trophy twitter",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/twitter-blue.svg",alt:"RxDB Twitter"}),(0,g.jsxs)("div",{style:{flex:1},children:[(0,g.jsx)("div",{className:"subtitle",children:"Follow on"}),(0,g.jsx)("div",{className:"title",children:"Twitter"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:"valuetitle",children:"followers"}),(0,g.jsxs)("div",{className:"value",children:["2843",(0,g.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,g.jsx)("div",{className:"block replication",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("div",{className:"half left",children:[(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("h2",{children:["Replicate ",(0,g.jsx)("b",{children:"with your existing infrastructure"})]}),(0,g.jsxs)("p",{children:["RxDB supports replication with a"," ",(0,g.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:"CouchDB"})," ","server or any custom"," ",(0,g.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:"GraphQL"})," ","endpoint which smoothly integrates with your existing infrastructure. Also you can use the replication primitives plugin to create custom replications over any protocol like"," ",(0,g.jsx)("a",{href:"/replication-http.html",target:"_blank",children:"HTTP"}),","," ",(0,g.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:"Websocket"}),","," ",(0,g.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:"WebRTC"})," ","or"," ",(0,g.jsx)("a",{href:"/replication-firestore.html",target:"_blank",children:"Firestore"}),"."]})]}),(0,g.jsx)("div",{className:"half right",children:(0,g.jsxs)("div",{className:"replication-icons",children:[(0,g.jsx)("img",{"data-src":"./files/logo/logo.svg",alt:"RxDB",className:"replicate-logo tilt-to-mouse lazyload"}),(0,g.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xl centered replicate-graphql enlarge-on-mouse",children:(0,g.jsx)("img",{"data-src":"./files/icons/graphql-text.svg",alt:"GraphQL",className:"protocol lazyload"})})}),(0,g.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xl centered replicate-couchdb enlarge-on-mouse",children:(0,g.jsx)("img",{"data-src":"./files/icons/couchdb-text.svg",alt:"CouchDB",className:"protocol lazyload"})})}),(0,g.jsx)("a",{href:"/replication-http.html",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-xs centered replicate-rest enlarge-on-mouse",children:["{"," HTTP ","}"]})}),(0,g.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xs centered replicate-websocket enlarge-on-mouse",children:"websocket"})}),(0,g.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:(0,g.jsx)("div",{className:"neumorphism-circle-xs centered replicate-webrtc enlarge-on-mouse",children:"WebRTC"})})]})}),(0,g.jsx)("div",{className:"clear"})]})}),(0,g.jsx)("a",{href:"/code",target:"_blank",children:(0,g.jsxs)("div",{className:"trophy",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/github-star-with-logo.svg",alt:"RxDB github star"}),(0,g.jsxs)("div",{style:{flex:1},children:[(0,g.jsx)("div",{className:"subtitle",children:"Open Source on"}),(0,g.jsx)("div",{className:"title",children:"GitHub"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:"valuetitle",children:"stars"}),(0,g.jsxs)("div",{className:"value",children:["20172",(0,g.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,g.jsxs)("div",{className:"block offline-first dark",children:[(0,g.jsx)("div",{className:"offline-image-wrapper",children:(0,g.jsx)("img",{"data-src":"files/icons/wifi/wifi_1a202c.svg",className:"offline-image beating-second lazyload",alt:"offline"})}),(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h2",{children:["Online ",(0,g.jsx)("b",{className:"underline",children:"is optional"})]}),(0,g.jsxs)("div",{className:"full-width",children:[(0,g.jsx)("div",{className:"half left",children:(0,g.jsxs)("p",{children:["RxDB follows the"," ",(0,g.jsx)("a",{href:"/offline-first.html",target:"_blank",children:"Offline First"})," ","paradigm where an application must work as well offline as it does online. This is done by persisting data locally on the client side and replicating it in the background. RxDB can even be used solely on the client side, with no backend at all."]})}),(0,g.jsx)("div",{className:"half right",children:(0,g.jsxs)("ul",{className:"checked",children:[(0,g.jsxs)("li",{children:["Your application still ",(0,g.jsx)("b",{children:"works offline"})]}),(0,g.jsxs)("li",{children:["Increases ",(0,g.jsx)("b",{children:"perceived performance"})]}),(0,g.jsxs)("li",{children:["Easier and ",(0,g.jsx)("b",{children:"faster implementation"})]}),(0,g.jsxs)("li",{children:["Needs less backend resources and ",(0,g.jsx)("b",{children:"scales better"})]})]})})]})]})]}),(0,g.jsx)("div",{className:"block frameworks",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/angular",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-10%",left:"10%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/angular.svg",alt:"angular"}),"Angular"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"10%",left:"58%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/capacitor.svg",alt:"capacitor"}),"Capacitor"]}),(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"-4%",left:"44%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/deno.svg",alt:"deno"}),"Deno"]}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/node",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-5%",left:"85%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/nodejs.svg",alt:"Node.js"}),"Node.js"]})}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"4%",left:"26%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/react.svg",alt:"React"}),"React"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"15%",left:"90%",marginLeft:"-35px"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/svelte.svg",alt:"Svelte"}),"Svelte"]}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsx)("br",{}),(0,g.jsxs)("h2",{children:["Flexible ",(0,g.jsx)("b",{className:"underline",children:"storage layer"})]}),(0,g.jsxs)("p",{children:["RxDB is based on a storage interface that enables you to swap out the underlying storage engine. This increases code reuse because the same database code can be used in ",(0,g.jsx)("b",{children:"any JavaScript runtime"})," ","by just switching out the storage settings.",(0,g.jsx)("br",{})]}),(0,g.jsxs)("div",{className:"below-text",children:[(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/electron",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"18%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/electron.svg",alt:"electron"}),"Electron"]})}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/vue",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"3%",left:"45%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/vuejs.svg",alt:"Vue.js"}),"Vue.js"]})}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/ionic2",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"71%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/ionic.svg",alt:"ionic"}),"Ionic"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"46%",left:"11%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/nativescript.svg",alt:"NativeScript"}),"NativeScript"]}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react-native",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"35%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/react.svg",alt:"React Native"}),"React Native"]})}),(0,g.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"62%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/nextjs.svg",alt:"Next.js"}),"Next.js"]}),(0,g.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/flutter",target:"_blank",children:(0,g.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"40%",left:"86%"},children:[(0,g.jsx)("img",{className:"lazyload","data-src":"./files/icons/flutter.svg",alt:"Flutter"}),"Flutter"]})})]})]})}),(0,g.jsx)("div",{className:"block fifth dark",children:(0,g.jsx)("div",{className:"content centered",children:(0,g.jsxs)("div",{className:"inner",children:[(0,g.jsxs)("h2",{children:["Trusted and ",(0,g.jsx)("b",{className:"underline",children:"open source"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/github-star.svg",alt:"github star"}),(0,g.jsx)("div",{className:"label",children:"Github Stars"}),(0,g.jsx)("a",{className:"value",href:"/code",rel:"noopener",target:"_blank",children:"20172"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/download.svg",alt:"npm downloads"}),(0,g.jsx)("div",{className:"label",children:"npm downloads"}),(0,g.jsx)("a",{className:"value beating-number",href:"https://www.npmjs.com/package/rxdb",rel:"noopener",target:"_blank",children:"238572"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"clear"}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/person.svg",alt:"contributor"}),(0,g.jsx)("div",{className:"label",children:"Contributors"}),(0,g.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/graphs/contributors",rel:"noopener",target:"_blank",children:"211"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/commit.svg",alt:"commit"}),(0,g.jsx)("div",{className:"label",children:"Commits"}),(0,g.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/commits/master",rel:"noopener",target:"_blank",children:"10409"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"clear"}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/gear.svg",alt:"gear"}),(0,g.jsx)("div",{className:"label",children:"RxDB made Projects"}),(0,g.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/network/dependents?package_id=UGFja2FnZS0xODM0NzAyMw%3D%3D",rel:"noopener",target:"_blank",children:"1402"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsxs)("div",{className:"box dark",children:[(0,g.jsx)("img",{className:"lazyload","data-src":"files/icons/twitter.svg",alt:"twitter"}),(0,g.jsx)("div",{className:"label",children:"Twitter followers"}),(0,g.jsx)("a",{className:"value",href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",children:"2925"}),(0,g.jsx)("div",{className:"clear"})]}),(0,g.jsx)("div",{className:"clear"})]})})}),(0,g.jsx)("div",{className:"block sixth",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsx)("h2",{children:"Pricing Models"}),(0,g.jsx)("div",{className:"inner",children:(0,g.jsxs)("div",{className:"buy-options",children:[(0,g.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,g.jsxs)("div",{className:"buy-option-inner",children:[(0,g.jsxs)("div",{className:"buy-option-title",children:[(0,g.jsx)("h2",{children:"RxDB Basics"}),(0,g.jsx)("div",{className:"price",children:"Free & Open Source"})]}),(0,g.jsx)("div",{className:"buy-option-features",children:(0,g.jsxs)("ul",{children:[(0,g.jsx)("li",{children:"Basic RxStorages"}),(0,g.jsx)("li",{children:"Realtime Replication"}),(0,g.jsx)("li",{children:"Live Queries"}),(0,g.jsx)("li",{children:"Schema Validation"}),(0,g.jsx)("li",{children:"Multi-Tab Support"}),(0,g.jsx)("li",{children:"Encryption"}),(0,g.jsx)("li",{children:"Compression"})]})}),(0,g.jsx)("a",{href:"/code",target:"_blank",rel:"noopener",onClick:()=>(0,f.h)("get_the_code_main_page",.8),children:(0,g.jsx)("div",{className:"buy-option-action bg-top hover-shadow-top",children:"Get the Code"})})]})}),(0,g.jsx)("div",{className:"buy-option bg-gradient-right-top",children:(0,g.jsxs)("div",{className:"buy-option-inner",children:[(0,g.jsxs)("div",{className:"buy-option-title",children:[(0,g.jsx)("h2",{children:"Premium Plugins"}),(0,g.jsx)("div",{className:"price",children:"for professionals to get the most out of RxDB"})]}),(0,g.jsx)("div",{className:"buy-option-features",children:(0,g.jsxs)("ul",{children:[(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-sqlite.html",target:"_blank",children:"SQLite RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-opfs.html",target:"_blank",children:"OPFS RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-indexeddb.html",target:"_blank",children:"IndexedDB RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-memory-synced.html",target:"_blank",children:"Memory-Synced RxStorage"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-sharding.html",target:"_blank",children:"Sharding Plugin"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/migration-storage.html",target:"_blank",children:"Storage Migrator"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-shared-worker.html",target:"_blank",children:"Shared Worker"})}),(0,g.jsx)("li",{children:(0,g.jsx)("a",{href:"https://rxdb.info/rx-storage-worker.html",target:"_blank",children:"Worker"})})]})}),(0,g.jsx)("a",{href:"/premium",onClick:()=>(0,f.h)("request_premium_main_page",3),children:(0,g.jsx)("div",{className:"buy-option-action bg-middle hover-shadow-middle",children:"Request Premium"})})]})}),(0,g.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,g.jsxs)("div",{className:"buy-option-inner",children:[(0,g.jsxs)("div",{className:"buy-option-title",children:[(0,g.jsx)("h2",{children:"Consulting Session"}),(0,g.jsx)("div",{className:"price",children:"fast in person consulting"})]}),(0,g.jsx)("div",{className:"buy-option-features",children:(0,g.jsxs)("p",{children:["Book a one hour consulting session with the RxDB maintainer. I will answer all your questions, give proposals for your use case and we can even do a pair programming session if you have a specific problem in your source code.",(0,g.jsx)("br",{}),"You can book this by doing a one-time donation via github sponsors."]})}),(0,g.jsx)("a",{href:"https://github.com/sponsors/pubkey?frequency=one-time&sponsor=pubkey",target:"_blank",onClick:()=>(0,f.h)("consulting_session_request_main_page",4),children:(0,g.jsx)("div",{className:"buy-option-action bg-bottom hover-shadow-bottom",children:"Book Now"})})]})})]})})]})}),(0,g.jsx)("div",{className:"block last dark",children:(0,g.jsxs)("div",{className:"content",children:[(0,g.jsxs)("h2",{children:["Start using ",(0,g.jsx)("b",{className:"underline",children:"RxDB"})," today"]}),(0,g.jsxs)("div",{className:"buttons full-width",children:[(0,g.jsx)("a",{href:"/quickstart.html",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("start_now_main_bottom",.4),children:(0,g.jsx)("div",{className:"button get-premium",style:{left:"50%",top:"20%",marginLeft:"-122px"},children:"Start now"})}),(0,g.jsx)("a",{href:"/newsletter",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("newsletter_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{left:"25%",marginLeft:"-90px"},children:"Get the Newsletter"})}),(0,g.jsx)("a",{href:"/chat",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("join_chat_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{left:"77%",top:"6%",marginLeft:"-70.5px"},children:"Join the Chat"})}),(0,g.jsx)("a",{href:"/premium",onClick:()=>(0,f.h)("get_premium_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{top:"40%",left:"20%",marginLeft:"-70.5px"},children:"Get Premium"})}),(0,g.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("follow_twitter_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{top:"44%",left:"73%",marginLeft:"-85px"},children:"Follow on Twitter"})}),(0,g.jsx)("a",{href:"/code",rel:"noopener",target:"_blank",onClick:()=>(0,f.h)("get_code_main_bottom",.4),children:(0,g.jsx)("div",{className:"button",style:{top:"54%",left:"32%",marginLeft:"-70px"},children:"Get the Code"})})]})]})})]})})]})}const j=["NoSQL","OfflineFirst","JavaScript","observable","reactive","realtime","client side","fast"],w=["for the Web","for Node.js","for Browsers","for Capacitor","for Electron","for hybrid apps","for PWAs","for React Native","for NativeScript","for UI apps","you deserve","that syncs"],k=851;function _(){const e=((new Date).getTime()-196e7)/k,t=Math.floor(e);return{ratio:e,period:t,timeToNextPeriod:(e-t)*k}}const N=22,D=-1*N;function R(e){return eN?N:e}function I(){return Math.random()<.5}function E(e,t){let r,a,n=(e=e.slice(0)).length;for(;n;)a=Math.floor(C(t)*n--),r=e[n],e[n]=e[a],e[a]=r,++t;return e}function C(e){const t=1e4*Math.sin(e++);return t-Math.floor(t)}function S(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function s(e){return Array.isArray(e)}function i(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>i,Sd:()=>o,dG:()=>a,jw:()=>l,k_:()=>s})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>i,Dr:()=>s,ND:()=>n,Ve:()=>d,dY:()=>a,em:()=>o,h$:()=>h,vN:()=>c});Promise.resolve(!0);var s=Promise.resolve(!1),i=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function d(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function h(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/280a2389.2a5b1215.js b/docs/assets/js/280a2389.2a5b1215.js deleted file mode 100644 index b6dbccdea0e..00000000000 --- a/docs/assets/js/280a2389.2a5b1215.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[176],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Zr,C3:()=>Kr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function u(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var h=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},l=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(l.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(l.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(l.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function f(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function p(e,t){if(f(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!h(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function _(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var k=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,D.A)(Error)),I=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,D.A)(TypeError));function E(e,t){return new k(e,x.tunnelErrorMessage(e),t)}function O(e,t){return new I(e,x.tunnelErrorMessage(e),t)}function R(e){return!(!e||409!==e.status)&&e}var C={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var j=/\./g,S="abcdefghijklmnopqrstuvwxyz";function P(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw E("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function Q(e){var t=B((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=F,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var F={type:"object",properties:{lwt:{type:"number",minimum:A,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=B(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",K="changes",Z="attachments",z="dexie",U=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=B(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),ue=r(3337),he=String.fromCharCode(65535),le=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,u=!0,h=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:u?le:he,endKey:a?he:le,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=le),void 0===i.endKey&&(i.endKey=he),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),u&&!i.inclusiveStart&&(u=!1),a&&!i.inclusiveEnd&&(a=!1),i})),l=h.map((e=>e.startKey)),d=h.map((e=>e.endKey)),m={index:e,startKeys:l,endKeys:d,inclusiveEnd:a,inclusiveStart:u,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,l,d)},f=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==le&&e!==he));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==he&&e!==le));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var u=r.sortSatisfiedByIndex?5:0;return n(u),a}(0,0,m);(f>=c||t.index)&&(c=f,s=m)})),!s)throw E("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),fe=new Set(["$eq","$gt","$gte"]),pe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var u=Object.keys(c).filter((e=>fe.has(e)));if(u.length>1)return!1;var h=u[0];if(h&&s.add(o),"$eq"!==h){if(i.length>0)return!1;i.push(h)}}var l=[],d=new Set;for(var[m,f]of Object.entries(t)){if(!e.includes(m))return!1;var p=Object.keys(f).filter((e=>pe.has(e)));if(p.length>1)return!1;var v=p[0];if(v&&d.add(m),"$eq"!==v){if(l.length>0)return!1;l.push(v)}}var y=0;for(var g of e){for(var b of[s,d]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[y]!==a[y]&&s.size>0&&d.size>0)return!1;y++}return!0}var ye=r(744),ge=r(2779),be=r(1692),we=r(4903),De=r(7705),xe=r(2403),_e=r(6776),ke=r(6950),Ie=r(6823),Ee=!1;function Oe(e){return Ee||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:we.xF,$project:we.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:De.a6,$eq:xe.XV,$elemMatch:ke.Jy,$exists:Ie.P,$gt:xe.MR,$gte:xe.fy,$in:xe.oZ,$lt:xe.NV,$lte:xe.Q_,$ne:xe.C5,$nin:xe.GU,$mod:_e.Pp,$nor:De.q3,$not:De.En,$or:De.sU,$regex:_e.WP,$size:ke.Ig,$type:Ie.T}),Ee=!0),new be.X(e)}function Re(e,t){var r=B(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,u=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>u&&(u=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ce(e,t){if(!t.sort)throw E("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Se(e){return e===le?-1/0:e}function Pe(e,t,r){return e.includes(t)?r===he||!0===r?"1":"0":r}function $e(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ne(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=je(e.schema,t.query));var c=$e(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),u=s.index,h=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+u.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||h.push(n),s.sortSatisfiedByIndex&&h.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var l=Ce(e.schema,t.query);h=h.sort(l)}return{documents:h=h.slice(n,i)}}function Ae(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Te(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?Ae(r).height:0)+1+"-"+e}var qe="_rxdb_internal";async function Be(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Qe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:x.deepFreezeWhenDevMode(a),previousDocumentData:x.deepFreezeWhenDevMode(n)}}function Fe(e,t,r,a){if(a)throw 409===a.status?E("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?E("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function Ke(e){var t=s(e);return t._meta=s(e._meta),t}function Ze(e,t,r){x.deepFreezeWhenDevMode(r);var a=B(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),x.isDevMode()){i=q(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw E("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw E("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,ue.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,ue.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:T(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var ze=r(3561),Ue=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ue.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,u=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,ze.X)(o))};var h=r.close.bind(r);r.close=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),h()};var l=r.remove.bind(r);r.remove=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),l()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=B(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw E("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,u=[],h=[],l=[],d={id:P(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=d.events,f=[],p=[],v=[],y=r.size>0,g=a.length,b=function(){var e,n=a[w],d=n.document,g=n.previous,b=d[t],D=d._deleted,x=g&&g._deleted,_=void 0;if(y&&(_=r.get(b)),_){var k=_._rev;if(!g||g&&k!==g._rev){var I={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:_};return l.push(I),1}var O=c?We(n):n;c&&(D?g&&Object.keys(g._attachments).forEach((e=>{p.push({documentId:b,attachmentId:e,digest:(0,ue.ZN)(g)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:_,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=O.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else f.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?l.push(e):(c?(h.push(We(O)),s&&s(d)):(h.push(O),s&&s(d)),o=O);var R=null,C=null,j=null;if(x&&!D)j="INSERT",R=c?He(d):d;else if(!g||x||D){if(!D)throw E("SNH",{args:{writeRow:n}});j="DELETE",R=(0,ue.ZN)(d),C=g}else j="UPDATE",R=c?He(d):d,C=g;var S={documentId:b,documentData:R,previousDocumentData:C,operation:j};m.push(S)}else{var P=!!D;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?f.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},l.push(e))})),e||(c?(u.push(We(n)),i&&i(d)):(u.push(n),i&&i(d)),o=n),!P){var $={documentId:b,operation:"INSERT",documentData:c?He(d):d,previousDocumentData:c&&g?He(g):g};m.push($)}}},w=0;w{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,ue.ZN)(r)).eventBulk.events.length>0){var s=(0,ue.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ne(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=$e(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ne(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(U,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[K]:"++sequence, id",[Z]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[Z],booleanIndexes:se(n)}})();return U.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(z,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=z,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw E("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw E("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw E("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=B(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw E("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),u(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),u(this,"defaultValues",e)}},{key:"hash",get:function(){return u(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function ut(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=Q(e);a=function(e){return o(e,!0)}(a),x.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ht=r(7708),lt=r(8146),dt=r(3356),mt=r(5520),ft=r(8609),pt=r(1753);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=$(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 ")}function yt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,ue.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=Ae(i._rev).height,n.forEach((e=>{var t=Ae(e._rev).height;t>s&&(i=e,s=t)})),i),u=o;for(var h of a)try{u=await h.modifier(c(u))}catch(l){h.reject(l),h.reject=()=>{},h.resolve=()=>{}}try{await this.preWrite(u,o)}catch(l){return void a.forEach((e=>e.reject(l)))}e.push({previous:o,document:u})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=R(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,ue.ZN)(o.documentInDb),(0,ue.ZN)(c).unshift(e)}))}else{var u=E("COL20",{name:C[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(u)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var wt={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.$.pipe((0,ht.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,lt.p)((e=>e.documentId===this.primary)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,ft.t)(ue.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(x.isDevMode()){if(e.includes(".item."))throw E("DOC1",{path:e});if(e===this.primaryPath)throw E("DOC2");if(this.collection.schema.finalFields.includes(e))throw E("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw E("DOC4",{path:e})}return this.$.pipe((0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return pt.$A;if(!t)throw E("DOC5",{path:e});if(!t.ref)throw E("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw E("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return x.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(N(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(N(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(N(e+"."+o))}return r.get(N(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return x.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,x.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw E("DOC11",{id:this.primary,document:this});await xt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Fe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(E("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Fe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw E("DOC14")}};function Dt(e){void 0===e&&(e=wt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function xt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),x.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var _t=r(2198),kt=r(511),It=r(4157),Et=r(2442),Ot=r(6114);function Rt(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Ct=new WeakMap;function jt(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Ct,e,(()=>{var t=e.collection,r=Re(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ce(t.schema.jsonSchema,r),i=je(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Rt(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,ue.ZN)(e._result).docsData.slice(0),n=(0,ue.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:x.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Ot.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Ot.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var St=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Pt(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function $t(e){return e.refCount$.observers.length}var Nt,At,Tt=(Nt=100,At=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Pt(t,e)))}}),Mt=new WeakSet;var qt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=yt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return u(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=x.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],u=Te(o._rev),h=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),l=h.byRev,d=l.get(u),m=d?d.deref():void 0;return m||(o=n(o),m=s(o),l.set(u,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,pt.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Te(e.revision)})})))}))))),m};return o}(this))}}]),e}();function Bt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Qt=function(){function e(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=Bt(this.collection._docCache,t)}return(0,b.A)(e,[{key:"docsData",get:function(){return u(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),u(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Qt(this.collection,e,e.length);this._result=t}else this._result=new Qt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw E("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,ue.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),u=await r.storageInstance.query(c);t=u.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw E("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Zt(this).then((()=>(0,kt._)(this.$))).then((t=>{if(!t&&e)throw E("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Re(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=zt(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,dt.Z)(null),(0,Et.Z)((()=>Zt(this))),(0,ht.T)((()=>this._result)),(0,ft.t)(ue.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,ue.ZN)(t).time))),(0,lt.p)((e=>!!e)),(0,ht.T)((e=>{var t=(0,ue.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,It.h)(e,this.refCount$.pipe((0,lt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return u(this,"queryMatcher",je(0,Re(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,pt.dY)().then((()=>(0,pt.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function Kt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Zt(e){return e.collection.database.destroyed||Kt(e)?pt.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||Kt(e))return pt.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,ue.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=jt(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var u=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!u.has(t)&&(u.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:x.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var h=o.map((e=>{var t=Ke(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(h,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,lt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,wt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>Dt(sr(e))))}(e),e,x.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var ur=["pre","post"],hr=["insert","save","remove","create"],lr=!1,dr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===u&&(u=Tt),void 0===h&&(h={}),void 0===l&&(l=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new St,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=u,this.statics=h,this.conflictHandler=l,function(e){if(lr)return;lr=!0;var t=Object.getPrototypeOf(e);hr.forEach((e=>{ur.map((r=>{var a=r+$(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ze(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>xt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,lt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Et.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ht.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new qt(this.schema.primaryPath,this.$.pipe((0,lt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Qe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),pt.em},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration-schema")},t.getMigrationState=function(){throw vt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Fe(this,e[this.schema.primaryPath],e,r),(0,ue.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=Bt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),u=c.success.map((e=>e[t]));return await Promise.all(u.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:u.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw E("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,ue.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),u=await c.incrementalModify((()=>a));i.push(u)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Fe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw E("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=pt.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw E("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw O("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw E("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw O("COL7",{key:t,when:e});if(!ur.includes(e))throw O("COL8",{key:t,when:e});if(!hr.includes(t))throw E("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw E("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return pt.em;var i=n.series.map((e=>()=>e(r,a)));return(0,pt.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?pt.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,lt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,lt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,lt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7635),fr=r(1007);var pr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,fr.sc)(e))},vr=r(5525),yr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l,d){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,Et.Z)((e=>e.events))),this.storageToken=pt.Dr,this.storageTokenDocument=pt.Dr,this.emittedEventBulkIds=new vr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=u,this.cleanupPolicy=h,this.allowSlowCount=l,this.reactivity=d,"pseudoInstance"!==this.name&&(this.internalStore=Ze(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=P(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:T(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,ue.ZN)(n.error[0]);if(i.isError&&R(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,u=e.rxdbVersion,!c||u.includes("beta")&&u!==c||c.split(".")[0]!==u.split(".")[0])throw E("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw E("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,ue.ZN)(o)}var c,u;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw E("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await Be(this.internalStore,Gt(tr(e,t),Ut));if(!r)throw E("SNH",{name:e,schema:t});var a=Ke(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,u=o.schema;t[c]=u;var h=ut(u,this.hashFunction);if(r[c]=h,this.collections[i])throw E("DB3",{name:i});var l=tr(i,u),d={id:Gt(l,Ut),key:l,context:Ut,data:{name:c,schemaHash:await h.hash,schema:h.jsonSchema,version:h.version,connectedStorages:[]},_deleted:!1,_meta:T(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:h,database:this}),f=s(o);f.database=this,f.name=i,st("preCreateRxCollection",f),m.conflictHandler=f.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw E("DB12",{database:this.name,writeError:e});var a=(0,ue.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw E("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,ue.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:u={},options:h={},localDocuments:l=!1,cacheReplacementPolicy:d=Tt,conflictHandler:m=cr}=e;var f={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:x.isDevMode()};return st("preCreateRxStorageInstance",f),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,f).then((e=>{var f=new dr(t,r,a,e,n,i,c,u,h,d,o,m);return f.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(f,t,{get:()=>r.bind(f)})}));var e=pt.em;return s&&0!==f.schema.version&&(e=f.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:f,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:u,options:h,cacheReplacementPolicy:d,localDocuments:l,statics:o}}),f))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.addState=function(e){throw vt("state")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration-schema")},t.destroy=async function(){return this.destroyed?pt.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?pt.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>yr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=P(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:qe,schema:Jt,options:a,multiInstance:n,password:i,devMode:x.isDevMode()})}function wr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:u,allowSlowCount:h=!1,localDocuments:l=!1,hashFunction:d=pr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}),o||function(e,t){var r=t.name+"|"+e;if(yr.has(r))throw E("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),yr.add(t.name+"|"+a);var f=P(10);return br(f,t,a,r,i,n).catch((e=>{throw yr.delete(t.name+"|"+a),e})).then((e=>{var p=new gr(a,f,t,r,n,i,s,c,e,d,u,h,m);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}}).then((()=>p))}))}var Dr={RxSchema:ct.prototype,RxDocument:wt,RxQuery:Wt.prototype,RxCollection:dr.prototype,RxDatabase:gr.prototype},xr=new Set,_r=new Set;var kr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,w.A)(t,e),t}(Dt()),Ir={get isLocal(){return!0},get allAttachments$(){throw E("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(jr,this.parent);return this.parent.$.pipe((0,lt.p)((e=>e.documentId===this.primary)),(0,lt.p)((e=>e.isLocal)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((t=>e.docCache.getCachedRxDocument(t))),(0,ft.t)(ue.bz))},get $$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(jr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw O("LD2",{objPath:e});var t=v(this._data,e);return t=x.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,x.isDevMode()){if(e.includes(".item."))throw E("LD3",{objPath:e});if(e===this.primaryPath)throw E("LD4")}return this.$.pipe((0,ht.T)((e=>e._data)),(0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){return Rr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Pr(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Pr(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Pr(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:T(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Er=!1,Or=()=>{if(!Er){Er=!0;var e=wt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Ir,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Ir,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Ir[e]=(e=>()=>{throw E("LD6",{functionName:e})})(e)))}};function Rr(e){var t=e.parent;return t instanceof gr?t:t.database}var Cr=new WeakMap,jr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await $r(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ze(t,a,Mr);var n=new qt("id",e.$.pipe((0,lt.p)((e=>e.isLocal))),(t=>function(e,t){Or();var r=new kr(e.id,e,t);return Object.setPrototypeOf(r,Ir),r.prototype=Ir,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Qe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return jr.set(e,c),c})();Cr.set(e,a)}function Pr(e){var t=Cr.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw E("LD8",{database:r.name,collection:a})}return t}function $r(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Tr(a),schema:Mr,options:n,multiInstance:i,devMode:x.isDevMode()})}function Nr(e){var t=Cr.get(e);if(t)return Cr.delete(e),t.then((e=>e.storageInstance.close()))}async function Ar(e,t,r){var a=P(10),n=await $r(a,e,t,r,{},!1);await n.remove()}function Tr(e){return"plugin-local-documents-"+e}var Mr=Q({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function qr(e,t){var r=await Pr(this),a={id:e,data:t,_deleted:!1,_meta:T(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function Br(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Pr(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Be(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Qr(e){return this.$.pipe((0,dt.Z)(null),(0,Et.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Et.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,lt.p)((e=>e.use)),(0,ht.T)((e=>e.doc)))}var Fr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=qr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr},RxDatabase:e=>{e.insertLocal=qr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>Nr(e)},postDestroyRxCollection:{after:e=>Nr(e)},postRemoveRxDatabase:{after:e=>Ar(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Ar(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function Kr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:xr}),!xr.has(e)){if(_r.has(e.name))throw E("PL3",{name:e.name,plugin:e});if(xr.add(e),_r.add(e.name),!e.rxdb)throw O("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(Dr[t])})),e.overwritable&&Object.assign(x,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Fr);var e;return await wr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Zr=["#e6008d","#8d2089","#5f2688"]},8141:(e,t,r)=>{r.r(t),r.d(t,{default:()=>h});var a=r(4586),n=r(1595),i=r(6540),s=r(2303),o=r(2658),c=r(4848);const u="meeting-link-clicked";function h(){const{siteConfig:e}=(0,a.A)(),t=(0,s.A)();(0,i.useEffect)((()=>{t&&(0,o.IA)()&&(async()=>{const e=await(0,o.C3)();await e.getLocal(u)?console.log("# already tracked "+u):(window.trigger(u,10),await e.upsertLocal(u,{}))})()}));let r="https://rxdb.pipedrive.com/scheduler/";if(t){r+=new URLSearchParams(window.location.search).get("f")+"/schedulr"}return(0,c.jsx)(n.A,{title:`Chat - ${e.title}`,description:"Meeting Scheduler",children:(0,c.jsx)("main",{children:(0,c.jsxs)("div",{className:"redirectBox",style:{textAlign:"center"},children:[(0,c.jsx)("a",{href:"/",children:(0,c.jsx)("div",{className:"logo",children:(0,c.jsx)("img",{src:"/files/logo/logo_text.svg",alt:"RxDB",width:160})})}),(0,c.jsx)("h1",{children:"RxDB Meeting Scheduler"}),(0,c.jsx)("p",{children:(0,c.jsx)("b",{children:"You will be redirected in a few seconds."})}),(0,c.jsx)("p",{children:(0,c.jsx)("a",{href:r,children:"Click here to open the meeting scheduler directly."})}),(0,c.jsx)("meta",{httpEquiv:"Refresh",content:"0; url="+r})]})})})}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>u,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>h,dY:()=>a,em:()=>o,h$:()=>l,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var u=o;function h(e){return void 0===e&&(e=void 0),u=u.then((()=>c(e)))}function l(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/280a2389.d378aa1e.js b/docs/assets/js/280a2389.d378aa1e.js new file mode 100644 index 00000000000..3d17ec827df --- /dev/null +++ b/docs/assets/js/280a2389.d378aa1e.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[176],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Zr,C3:()=>Kr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function u(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var h=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},l=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(l.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(l.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(l.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function f(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function p(e,t){if(f(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!h(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function _(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var k=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])}((0,D.A)(Error)),I=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}])}((0,D.A)(TypeError));function E(e,t){return new k(e,x.tunnelErrorMessage(e),t)}function O(e,t){return new I(e,x.tunnelErrorMessage(e),t)}function R(e){return!(!e||409!==e.status)&&e}var C={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var j=/\./g,S="abcdefghijklmnopqrstuvwxyz";function P(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw E("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function Q(e){var t=B((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=F,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var F={type:"object",properties:{lwt:{type:"number",minimum:A,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=B(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",K="changes",Z="attachments",z="dexie",U=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=B(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),ue=r(3337),he=String.fromCharCode(65535),le=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,u=!0,h=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:u?le:he,endKey:a?he:le,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=le),void 0===i.endKey&&(i.endKey=he),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),u&&!i.inclusiveStart&&(u=!1),a&&!i.inclusiveEnd&&(a=!1),i})),l=h.map((e=>e.startKey)),d=h.map((e=>e.endKey)),m={index:e,startKeys:l,endKeys:d,inclusiveEnd:a,inclusiveStart:u,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,l,d)},f=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==le&&e!==he));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==he&&e!==le));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var u=r.sortSatisfiedByIndex?5:0;return n(u),a}(0,0,m);(f>=c||t.index)&&(c=f,s=m)})),!s)throw E("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),fe=new Set(["$eq","$gt","$gte"]),pe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var u=Object.keys(c).filter((e=>fe.has(e)));if(u.length>1)return!1;var h=u[0];if(h&&s.add(o),"$eq"!==h){if(i.length>0)return!1;i.push(h)}}var l=[],d=new Set;for(var[m,f]of Object.entries(t)){if(!e.includes(m))return!1;var p=Object.keys(f).filter((e=>pe.has(e)));if(p.length>1)return!1;var v=p[0];if(v&&d.add(m),"$eq"!==v){if(l.length>0)return!1;l.push(v)}}var y=0;for(var g of e){for(var b of[s,d]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[y]!==a[y]&&s.size>0&&d.size>0)return!1;y++}return!0}var ye=r(744),ge=r(2779),be=r(1692),we=r(4903),De=r(7705),xe=r(2403),_e=r(6776),ke=r(6950),Ie=r(6823),Ee=!1;function Oe(e){return Ee||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:we.xF,$project:we.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:De.a6,$eq:xe.XV,$elemMatch:ke.Jy,$exists:Ie.P,$gt:xe.MR,$gte:xe.fy,$in:xe.oZ,$lt:xe.NV,$lte:xe.Q_,$ne:xe.C5,$nin:xe.GU,$mod:_e.Pp,$nor:De.q3,$not:De.En,$or:De.sU,$regex:_e.WP,$size:ke.Ig,$type:Ie.T}),Ee=!0),new be.X(e)}function Re(e,t){var r=B(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,u=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>u&&(u=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ce(e,t){if(!t.sort)throw E("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Se(e){return e===le?-1/0:e}function Pe(e,t,r){return e.includes(t)?r===he||!0===r?"1":"0":r}function $e(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ne(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=je(e.schema,t.query));var c=$e(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),u=s.index,h=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+u.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||h.push(n),s.sortSatisfiedByIndex&&h.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var l=Ce(e.schema,t.query);h=h.sort(l)}return{documents:h=h.slice(n,i)}}function Ae(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Te(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?Ae(r).height:0)+1+"-"+e}var qe="_rxdb_internal";async function Be(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Qe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:x.deepFreezeWhenDevMode(a),previousDocumentData:x.deepFreezeWhenDevMode(n)}}function Fe(e,t,r,a){if(a)throw 409===a.status?E("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?E("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function Ke(e){var t=s(e);return t._meta=s(e._meta),t}function Ze(e,t,r){x.deepFreezeWhenDevMode(r);var a=B(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),x.isDevMode()){i=q(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw E("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw E("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,ue.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,ue.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:T(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var ze=r(3561),Ue=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ue.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,u=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,ze.X)(o))};var h=r.close.bind(r);r.close=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),h()};var l=r.remove.bind(r);r.remove=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),l()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=B(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw E("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,u=[],h=[],l=[],d={id:P(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=d.events,f=[],p=[],v=[],y=r.size>0,g=a.length,b=function(){var e,n=a[w],d=n.document,g=n.previous,b=d[t],D=d._deleted,x=g&&g._deleted,_=void 0;if(y&&(_=r.get(b)),_){var k=_._rev;if(!g||g&&k!==g._rev){var I={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:_};return l.push(I),1}var O=c?We(n):n;c&&(D?g&&Object.keys(g._attachments).forEach((e=>{p.push({documentId:b,attachmentId:e,digest:(0,ue.ZN)(g)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:_,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=O.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else f.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?l.push(e):(c?(h.push(We(O)),s&&s(d)):(h.push(O),s&&s(d)),o=O);var R=null,C=null,j=null;if(x&&!D)j="INSERT",R=c?He(d):d;else if(!g||x||D){if(!D)throw E("SNH",{args:{writeRow:n}});j="DELETE",R=(0,ue.ZN)(d),C=g}else j="UPDATE",R=c?He(d):d,C=g;var S={documentId:b,documentData:R,previousDocumentData:C,operation:j};m.push(S)}else{var P=!!D;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?f.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},l.push(e))})),e||(c?(u.push(We(n)),i&&i(d)):(u.push(n),i&&i(d)),o=n),!P){var $={documentId:b,operation:"INSERT",documentData:c?He(d):d,previousDocumentData:c&&g?He(g):g};m.push($)}}},w=0;w{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,ue.ZN)(r)).eventBulk.events.length>0){var s=(0,ue.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ne(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=$e(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ne(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(U,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[K]:"++sequence, id",[Z]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[Z],booleanIndexes:se(n)}})();return U.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(z,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=z,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw E("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw E("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw E("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=B(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw E("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),u(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),u(this,"defaultValues",e)}},{key:"hash",get:function(){return u(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}])}();function ut(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=Q(e);a=function(e){return o(e,!0)}(a),x.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ht=r(7708),lt=r(8146),dt=r(3356),mt=r(5520),ft=r(8609),pt=r(1753);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=$(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 ")}function yt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,ue.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=Ae(i._rev).height,n.forEach((e=>{var t=Ae(e._rev).height;t>s&&(i=e,s=t)})),i),u=o;for(var h of a)try{u=await h.modifier(c(u))}catch(l){h.reject(l),h.reject=()=>{},h.resolve=()=>{}}try{await this.preWrite(u,o)}catch(l){return void a.forEach((e=>e.reject(l)))}e.push({previous:o,document:u})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=R(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,ue.ZN)(o.documentInDb),(0,ue.ZN)(c).unshift(e)}))}else{var u=E("COL20",{name:C[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(u)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var wt={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.$.pipe((0,ht.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,lt.p)((e=>e.documentId===this.primary)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,ft.t)(ue.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(x.isDevMode()){if(e.includes(".item."))throw E("DOC1",{path:e});if(e===this.primaryPath)throw E("DOC2");if(this.collection.schema.finalFields.includes(e))throw E("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw E("DOC4",{path:e})}return this.$.pipe((0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return pt.$A;if(!t)throw E("DOC5",{path:e});if(!t.ref)throw E("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw E("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return x.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(N(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(N(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(N(e+"."+o))}return r.get(N(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return x.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,x.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw E("DOC11",{id:this.primary,document:this});await xt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Fe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(E("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Fe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw E("DOC14")}};function Dt(e){void 0===e&&(e=wt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function xt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),x.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var _t=r(2198),kt=r(511),It=r(4157),Et=r(2442),Ot=r(6114);function Rt(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Ct=new WeakMap;function jt(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Ct,e,(()=>{var t=e.collection,r=Re(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ce(t.schema.jsonSchema,r),i=je(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Rt(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,ue.ZN)(e._result).docsData.slice(0),n=(0,ue.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:x.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Ot.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Ot.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var St=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Pt(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function $t(e){return e.refCount$.observers.length}var Nt,At,Tt=(Nt=100,At=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Pt(t,e)))}}),Mt=new WeakSet;var qt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=yt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return u(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=x.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],u=Te(o._rev),h=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),l=h.byRev,d=l.get(u),m=d?d.deref():void 0;return m||(o=n(o),m=s(o),l.set(u,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,pt.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Te(e.revision)})})))}))))),m};return o}(this))}}])}();function Bt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Qt=function(){return(0,b.A)((function(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=Bt(this.collection._docCache,t)}),[{key:"docsData",get:function(){return u(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),u(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Qt(this.collection,e,e.length);this._result=t}else this._result=new Qt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw E("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,ue.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),u=await r.storageInstance.query(c);t=u.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw E("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Zt(this).then((()=>(0,kt._)(this.$))).then((t=>{if(!t&&e)throw E("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Re(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=zt(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,dt.Z)(null),(0,Et.Z)((()=>Zt(this))),(0,ht.T)((()=>this._result)),(0,ft.t)(ue.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,ue.ZN)(t).time))),(0,lt.p)((e=>!!e)),(0,ht.T)((e=>{var t=(0,ue.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,It.h)(e,this.refCount$.pipe((0,lt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return u(this,"queryMatcher",je(0,Re(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}])}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,pt.dY)().then((()=>(0,pt.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function Kt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Zt(e){return e.collection.database.destroyed||Kt(e)?pt.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||Kt(e))return pt.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,ue.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=jt(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var u=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!u.has(t)&&(u.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:x.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var h=o.map((e=>{var t=Ke(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(h,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,lt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,wt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>Dt(sr(e))))}(e),e,x.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var ur=["pre","post"],hr=["insert","save","remove","create"],lr=!1,dr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===u&&(u=Tt),void 0===h&&(h={}),void 0===l&&(l=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new St,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=u,this.statics=h,this.conflictHandler=l,function(e){if(lr)return;lr=!0;var t=Object.getPrototypeOf(e);hr.forEach((e=>{ur.map((r=>{var a=r+$(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ze(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>xt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,lt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Et.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ht.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new qt(this.schema.primaryPath,this.$.pipe((0,lt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Qe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),pt.em},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration-schema")},t.getMigrationState=function(){throw vt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Fe(this,e[this.schema.primaryPath],e,r),(0,ue.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=Bt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),u=c.success.map((e=>e[t]));return await Promise.all(u.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:u.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw E("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,ue.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),u=await c.incrementalModify((()=>a));i.push(u)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Fe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw E("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=pt.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw E("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw O("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw E("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw O("COL7",{key:t,when:e});if(!ur.includes(e))throw O("COL8",{key:t,when:e});if(!hr.includes(t))throw E("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw E("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return pt.em;var i=n.series.map((e=>()=>e(r,a)));return(0,pt.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?pt.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,lt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,lt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,lt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}])}();var mr=r(7635),fr=r(1007);var pr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,fr.sc)(e))},vr=r(5525),yr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l,d){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,Et.Z)((e=>e.events))),this.storageToken=pt.Dr,this.storageTokenDocument=pt.Dr,this.emittedEventBulkIds=new vr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=u,this.cleanupPolicy=h,this.allowSlowCount=l,this.reactivity=d,"pseudoInstance"!==this.name&&(this.internalStore=Ze(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=P(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:T(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,ue.ZN)(n.error[0]);if(i.isError&&R(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,u=e.rxdbVersion,!c||u.includes("beta")&&u!==c||c.split(".")[0]!==u.split(".")[0])throw E("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw E("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,ue.ZN)(o)}var c,u;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw E("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await Be(this.internalStore,Gt(tr(e,t),Ut));if(!r)throw E("SNH",{name:e,schema:t});var a=Ke(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,u=o.schema;t[c]=u;var h=ut(u,this.hashFunction);if(r[c]=h,this.collections[i])throw E("DB3",{name:i});var l=tr(i,u),d={id:Gt(l,Ut),key:l,context:Ut,data:{name:c,schemaHash:await h.hash,schema:h.jsonSchema,version:h.version,connectedStorages:[]},_deleted:!1,_meta:T(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:h,database:this}),f=s(o);f.database=this,f.name=i,st("preCreateRxCollection",f),m.conflictHandler=f.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw E("DB12",{database:this.name,writeError:e});var a=(0,ue.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw E("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,ue.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:u={},options:h={},localDocuments:l=!1,cacheReplacementPolicy:d=Tt,conflictHandler:m=cr}=e;var f={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:x.isDevMode()};return st("preCreateRxStorageInstance",f),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,f).then((e=>{var f=new dr(t,r,a,e,n,i,c,u,h,d,o,m);return f.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(f,t,{get:()=>r.bind(f)})}));var e=pt.em;return s&&0!==f.schema.version&&(e=f.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:f,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:u,options:h,cacheReplacementPolicy:d,localDocuments:l,statics:o}}),f))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.addState=function(e){throw vt("state")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration-schema")},t.destroy=async function(){return this.destroyed?pt.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?pt.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>yr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=P(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}])}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:qe,schema:Jt,options:a,multiInstance:n,password:i,devMode:x.isDevMode()})}function wr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:u,allowSlowCount:h=!1,localDocuments:l=!1,hashFunction:d=pr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}),o||function(e,t){var r=t.name+"|"+e;if(yr.has(r))throw E("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),yr.add(t.name+"|"+a);var f=P(10);return br(f,t,a,r,i,n).catch((e=>{throw yr.delete(t.name+"|"+a),e})).then((e=>{var p=new gr(a,f,t,r,n,i,s,c,e,d,u,h,m);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}}).then((()=>p))}))}var Dr={RxSchema:ct.prototype,RxDocument:wt,RxQuery:Wt.prototype,RxCollection:dr.prototype,RxDatabase:gr.prototype},xr=new Set,_r=new Set;var kr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,w.A)(t,e),t}(Dt()),Ir={get isLocal(){return!0},get allAttachments$(){throw E("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(jr,this.parent);return this.parent.$.pipe((0,lt.p)((e=>e.documentId===this.primary)),(0,lt.p)((e=>e.isLocal)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((t=>e.docCache.getCachedRxDocument(t))),(0,ft.t)(ue.bz))},get $$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(jr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw O("LD2",{objPath:e});var t=v(this._data,e);return t=x.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,x.isDevMode()){if(e.includes(".item."))throw E("LD3",{objPath:e});if(e===this.primaryPath)throw E("LD4")}return this.$.pipe((0,ht.T)((e=>e._data)),(0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){return Rr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Pr(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Pr(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Pr(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:T(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Er=!1,Or=()=>{if(!Er){Er=!0;var e=wt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Ir,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Ir,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Ir[e]=(e=>()=>{throw E("LD6",{functionName:e})})(e)))}};function Rr(e){var t=e.parent;return t instanceof gr?t:t.database}var Cr=new WeakMap,jr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await $r(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ze(t,a,Mr);var n=new qt("id",e.$.pipe((0,lt.p)((e=>e.isLocal))),(t=>function(e,t){Or();var r=new kr(e.id,e,t);return Object.setPrototypeOf(r,Ir),r.prototype=Ir,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Qe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return jr.set(e,c),c})();Cr.set(e,a)}function Pr(e){var t=Cr.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw E("LD8",{database:r.name,collection:a})}return t}function $r(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Tr(a),schema:Mr,options:n,multiInstance:i,devMode:x.isDevMode()})}function Nr(e){var t=Cr.get(e);if(t)return Cr.delete(e),t.then((e=>e.storageInstance.close()))}async function Ar(e,t,r){var a=P(10),n=await $r(a,e,t,r,{},!1);await n.remove()}function Tr(e){return"plugin-local-documents-"+e}var Mr=Q({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function qr(e,t){var r=await Pr(this),a={id:e,data:t,_deleted:!1,_meta:T(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function Br(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Pr(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Be(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Qr(e){return this.$.pipe((0,dt.Z)(null),(0,Et.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Et.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,lt.p)((e=>e.use)),(0,ht.T)((e=>e.doc)))}var Fr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=qr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr},RxDatabase:e=>{e.insertLocal=qr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>Nr(e)},postDestroyRxCollection:{after:e=>Nr(e)},postRemoveRxDatabase:{after:e=>Ar(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Ar(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function Kr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:xr}),!xr.has(e)){if(_r.has(e.name))throw E("PL3",{name:e.name,plugin:e});if(xr.add(e),_r.add(e.name),!e.rxdb)throw O("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(Dr[t])})),e.overwritable&&Object.assign(x,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Fr);var e;return await wr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Zr=["#e6008d","#8d2089","#5f2688"]},8141:(e,t,r)=>{r.r(t),r.d(t,{default:()=>l});var a=r(4586),n=r(1595),i=r(6540),s=r(2303),o=r(2658),c=r(4848);const u="meeting-link-clicked",h=1e3;function l(){const{siteConfig:e}=(0,a.A)(),[t,r]=(0,i.useState)(null),l=(0,s.A)();return(0,i.useEffect)((()=>{l&&(0,o.IA)()&&(async()=>{const e=new URLSearchParams(window.location.search).get("f");r("https://rxdb.pipedrive.com/scheduler/"+e+"/schedulr"),setTimeout((()=>window.location.href=t),h);const a=await(0,o.C3)();await a.getLocal(u)?console.log("# already tracked "+u):(window.trigger(u,10),await a.upsertLocal(u,{}))})()})),(0,c.jsx)(n.A,{title:`Chat - ${e.title}`,description:"Meeting Scheduler",children:(0,c.jsx)("main",{children:(0,c.jsxs)("div",{className:"redirectBox",style:{textAlign:"center"},children:[(0,c.jsx)("a",{href:"/",children:(0,c.jsx)("div",{className:"logo",children:(0,c.jsx)("img",{src:"/files/logo/logo_text.svg",alt:"RxDB",width:160})})}),(0,c.jsx)("h1",{children:"RxDB Meeting Scheduler"}),(0,c.jsx)("p",{children:(0,c.jsx)("b",{children:"You will be redirected in a few seconds."})}),!!t&&(0,c.jsx)(c.Fragment,{children:(0,c.jsx)("p",{children:(0,c.jsx)("a",{href:t,children:"Click here to open the meeting scheduler directly."})})})]})})})}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>u,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>h,dY:()=>a,em:()=>o,h$:()=>l,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var u=o;function h(e){return void 0===e&&(e=void 0),u=u.then((()=>c(e)))}function l(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/cde77f4f.8383bcb2.js b/docs/assets/js/cde77f4f.8383bcb2.js new file mode 100644 index 00000000000..53c541fd0b5 --- /dev/null +++ b/docs/assets/js/cde77f4f.8383bcb2.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[6287,2584],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Kr,C3:()=>zr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},d=new Set(["__proto__","prototype","constructor"]),h=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(d.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(d.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!h.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(d.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function y(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])}((0,w.A)(Error)),_=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}])}((0,w.A)(TypeError));function I(e,t){return new D(e,j.tunnelErrorMessage(e),t)}function R(e,t){return new _(e,j.tunnelErrorMessage(e),t)}function S(e){return!(!e||409!==e.status)&&e}var E={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var C=/\./g,P="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=y(t,e);if(void 0===r)throw I("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function F(e){var t=q((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=Q,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var Q={type:"object",properties:{lwt:{type:"number",minimum:$,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=q(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",z="changes",K="attachments",U="dexie",Z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=q(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),le=r(3337),ue=String.fromCharCode(65535),de=Number.MIN_SAFE_INTEGER;function he(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:l?de:ue,endKey:a?ue:de,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=de),void 0===i.endKey&&(i.endKey=ue),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),l&&!i.inclusiveStart&&(l=!1),a&&!i.inclusiveEnd&&(a=!1),i})),d=u.map((e=>e.startKey)),h=u.map((e=>e.endKey)),m={index:e,startKeys:d,endKeys:h,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ye(e,t.selector,d,h)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==de&&e!==ue));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==ue&&e!==de));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,s=m)})),!s)throw I("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ye(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&s.add(o),"$eq"!==u){if(i.length>0)return!1;i.push(u)}}var d=[],h=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var y=f[0];if(y&&h.add(m),"$eq"!==y){if(d.length>0)return!1;d.push(y)}}var v=0;for(var g of e){for(var b of[s,h]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[v]!==a[v]&&s.size>0&&h.size>0)return!1;v++}return!0}var ve=r(744),ge=r(2779),be=r(1692),xe=r(4903),we=r(7705),je=r(2403),ke=r(6776),De=r(6950),_e=r(6823),Ie=!1;function Re(e){return Ie||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:xe.xF,$project:xe.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:we.a6,$eq:je.XV,$elemMatch:De.Jy,$exists:_e.P,$gt:je.MR,$gte:je.fy,$in:je.oZ,$lt:je.NV,$lte:je.Q_,$ne:je.C5,$nin:je.GU,$mod:ke.Pp,$nor:we.q3,$not:we.En,$or:we.sU,$regex:ke.WP,$size:De.Ig,$type:_e.T}),Ie=!0),new be.X(e)}function Se(e,t){var r=q(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ee(e,t){if(!t.sort)throw I("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Pe(e){return e===de?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Ne(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ae(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=Ce(e.schema,t.query));var c=Ne(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),l=s.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),s.sortSatisfiedByIndex&&u.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var d=Ee(e.schema,t.query);u=u.sort(d)}return{documents:u=u.slice(n,i)}}function $e(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Be(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?$e(r).height:0)+1+"-"+e}var Te="_rxdb_internal";async function qe(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Fe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:j.deepFreezeWhenDevMode(a),previousDocumentData:j.deepFreezeWhenDevMode(n)}}function Qe(e,t,r,a){if(a)throw 409===a.status?I("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?I("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function ze(e){var t=s(e);return t._meta=s(e._meta),t}function Ke(e,t,r){j.deepFreezeWhenDevMode(r);var a=q(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),j.isDevMode()){i=T(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw I("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw I("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:B(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(3561),Ze=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ze.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ue.X)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),u()};var d=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),d()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=q(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw I("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,l=[],u=[],d=[],h={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=h.events,p=[],f=[],y=[],v=r.size>0,g=a.length,b=function(){var e,n=a[x],h=n.document,g=n.previous,b=h[t],w=h._deleted,j=g&&g._deleted,k=void 0;if(v&&(k=r.get(b)),k){var D=k._rev;if(!g||g&&D!==g._rev){var _={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return d.push(_),1}var R=c?We(n):n;c&&(w?g&&Object.keys(g._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.ZN)(g)._attachments[e].digest})})):(Object.entries(h._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(h._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&y.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?d.push(e):(c?(u.push(We(R)),s&&s(h)):(u.push(R),s&&s(h)),o=R);var S=null,E=null,C=null;if(j&&!w)C="INSERT",S=c?He(h):h;else if(!g||j||w){if(!w)throw I("SNH",{args:{writeRow:n}});C="DELETE",S=(0,le.ZN)(h),E=g}else C="UPDATE",S=c?He(h):h,E=g;var P={documentId:b,documentData:S,previousDocumentData:E,operation:C};m.push(P)}else{var O=!!w;if(c&&Object.entries(h._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},d.push(e))})),e||(c?(l.push(We(n)),i&&i(h)):(l.push(n),i&&i(h)),o=n),!O){var N={documentId:b,operation:"INSERT",documentData:c?He(h):h,previousDocumentData:c&&g?He(g):g};m.push(N)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,le.ZN)(r)).eventBulk.events.length>0){var s=(0,le.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ae(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=Ne(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ae(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(Z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[z]:"++sequence, id",[K]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[K],booleanIndexes:se(n)}})();return Z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw I("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw I("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw I("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=q(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw I("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}])}();function lt(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=F(e);a=function(e){return o(e,!0)}(a),j.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ut=r(7708),dt=r(8146),ht=r(3356),mt=r(5520),pt=r(8609),ft=r(1753);function yt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=N(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 ")}function vt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=$e(i._rev).height,n.forEach((e=>{var t=$e(e._rev).height;t>s&&(i=e,s=t)})),i),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(d){u.reject(d),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(d){return void a.forEach((e=>e.reject(d)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=S(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.ZN)(o.documentInDb),(0,le.ZN)(c).unshift(e)}))}else{var l=I("COL20",{name:E[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={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.$.pipe((0,ut.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,dt.p)((e=>e.documentId===this.primary)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.t)(le.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(j.isDevMode()){if(e.includes(".item."))throw I("DOC1",{path:e});if(e===this.primaryPath)throw I("DOC2");if(this.collection.schema.finalFields.includes(e))throw I("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw I("DOC4",{path:e})}return this.$.pipe((0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.$A;if(!t)throw I("DOC5",{path:e});if(!t.ref)throw I("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw I("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=y(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return j.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(A(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(A(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(A(e+"."+o))}return r.get(A(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return j.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,j.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw yt("update")},incrementalUpdate(e){throw yt("update")},updateCRDT(e){throw yt("crdt")},putAttachment(){throw yt("attachments")},getAttachment(){throw yt("attachments")},allAttachments(){throw yt("attachments")},get allAttachments$(){throw yt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw I("DOC11",{id:this.primary,document:this});await jt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Qe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(I("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Qe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw I("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function jt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),j.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(2198),Dt=r(511),_t=r(4157),It=r(2442),Rt=r(6114);function St(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Et=new WeakMap;function Ct(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Et,e,(()=>{var t=e.collection,r=Se(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ee(t.schema.jsonSchema,r),i=Ce(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:St(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.ZN)(e._result).docsData.slice(0),n=(0,le.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:j.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Rt.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Rt.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var Pt=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Nt(e){return e.refCount$.observers.length}var At,$t,Bt=(At=100,$t=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Ot(t,e)))}}),Mt=new WeakSet;var Tt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=vt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=j.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],l=Be(o._rev),u=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),d=u.byRev,h=d.get(l),m=h?h.deref():void 0;return m||(o=n(o),m=s(o),d.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Be(e.revision)})})))}))))),m};return o}(this))}}])}();function qt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Ft=function(){return(0,b.A)((function(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=qt(this.collection._docCache,t)}),[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Ft(this.collection,e,e.length);this._result=t}else this._result=new Ft(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw I("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw I("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,Dt._)(this.$))).then((t=>{if(!t&&e)throw I("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Se(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw yt("update")},t.where=function(e){throw yt("query-builder")},t.sort=function(e){throw yt("query-builder")},t.skip=function(e){throw yt("query-builder")},t.limit=function(e){throw yt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,ht.Z)(null),(0,It.Z)((()=>Kt(this))),(0,ut.T)((()=>this._result)),(0,pt.t)(le.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,le.ZN)(t).time))),(0,dt.p)((e=>!!e)),(0,ut.T)((e=>{var t=(0,le.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,_t.h)(e,this.refCount$.pipe((0,dt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Ce(0,Se(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}])}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,ft.dY)().then((()=>(0,ft.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function zt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||zt(e)?ft.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||zt(e))return ft.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,le.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=Ct(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:j.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var u=o.map((e=>{var t=ze(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,dt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>wt(sr(e))))}(e),e,j.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],dr=!1,hr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Bt),void 0===u&&(u={}),void 0===d&&(d=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Pt,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=d,function(e){if(dr)return;dr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+N(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>jt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,dt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,It.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Tt(this.schema.primaryPath,this.$.pipe((0,dt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Fe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.em},t.cleanup=function(e){throw yt("cleanup")},t.migrationNeeded=function(){throw yt("migration-schema")},t.getMigrationState=function(){throw yt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Qe(this,e[this.schema.primaryPath],e,r),(0,le.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=qt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw I("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));i.push(l)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Qe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw I("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw I("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw I("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.insertCRDT=function(e){throw yt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!ur.includes(t))throw I("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw I("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.em;var i=n.series.map((e=>()=>e(r,a)));return(0,ft.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,dt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,dt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,dt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}])}();var mr=r(7635),pr=r(1007);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.sc)(e))},yr=r(5525),vr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d,h){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,It.Z)((e=>e.events))),this.storageToken=ft.Dr,this.storageTokenDocument=ft.Dr,this.emittedEventBulkIds=new yr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=d,this.reactivity=h,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:B(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,le.ZN)(n.error[0]);if(i.isError&&S(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw I("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw I("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,le.ZN)(o)}var c,l;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw I("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await qe(this.internalStore,Gt(tr(e,t),Zt));if(!r)throw I("SNH",{name:e,schema:t});var a=ze(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[i])throw I("DB3",{name:i});var d=tr(i,l),h={id:Gt(d,Zt),key:d,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:B(),_rev:"",_attachments:{}};a.push({document:h});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=s(o);p.database=this,p.name=i,st("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw I("DB12",{database:this.name,writeError:e});var a=(0,le.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw I("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,le.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:d=!1,cacheReplacementPolicy:h=Bt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:j.isDevMode()};return st("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new hr(t,r,a,e,n,i,c,l,u,h,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.em;return s&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:l,options:u,cacheReplacementPolicy:h,localDocuments:d,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw yt("json-dump")},t.addState=function(e){throw yt("state")},t.importJSON=function(e){throw yt("json-dump")},t.backup=function(e){throw yt("backup")},t.leaderElector=function(){throw yt("leader-election")},t.isLeader=function(){throw yt("leader-election")},t.waitForLeadership=function(){throw yt("leader-election")},t.migrationStates=function(){throw yt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>vr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}])}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Te,schema:Jt,options:a,multiInstance:n,password:i,devMode:j.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:d=!1,hashFunction:h=fr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}),o||function(e,t){var r=t.name+"|"+e;if(vr.has(r))throw I("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),vr.add(t.name+"|"+a);var p=O(10);return br(p,t,a,r,i,n).catch((e=>{throw vr.delete(t.name+"|"+a),e})).then((e=>{var f=new gr(a,p,t,r,n,i,s,c,e,h,l,u,m);return ot("createRxDatabase",{database:f,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}}).then((()=>f))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Wt.prototype,RxCollection:hr.prototype,RxDatabase:gr.prototype},jr=new Set,kr=new Set;var Dr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.A)(t,e),t}(wt()),_r={get isLocal(){return!0},get allAttachments$(){throw I("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,dt.p)((e=>e.documentId===this.primary)),(0,dt.p)((e=>e.isLocal)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.t)(le.bz))},get $$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=y(this._data,e);return t=j.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,j.isDevMode()){if(e.includes(".item."))throw I("LD3",{objPath:e});if(e===this.primaryPath)throw I("LD4")}return this.$.pipe((0,ut.T)((e=>e._data)),(0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){return Sr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:B(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Ir=!1,Rr=()=>{if(!Ir){Ir=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(_r,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(_r,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>_r[e]=(e=>()=>{throw I("LD6",{functionName:e})})(e)))}};function Sr(e){var t=e.parent;return t instanceof gr?t:t.database}var Er=new WeakMap,Cr=new WeakMap;function Pr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Nr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Mr);var n=new Tt("id",e.$.pipe((0,dt.p)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new Dr(e.id,e,t);return Object.setPrototypeOf(r,_r),r.prototype=_r,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Fe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw I("LD8",{database:r.name,collection:a})}return t}function Nr(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Br(a),schema:Mr,options:n,multiInstance:i,devMode:j.isDevMode()})}function Ar(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function $r(e,t,r){var a=O(10),n=await Nr(a,e,t,r,{},!1);await n.remove()}function Br(e){return"plugin-local-documents-"+e}var Mr=F({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Tr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:B(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function qr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):qe(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Fr(e){return this.$.pipe((0,ht.Z)(null),(0,It.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,It.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,dt.p)((e=>e.use)),(0,ut.T)((e=>e.doc)))}var Qr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr},RxDatabase:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Pr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Pr(e.collection)}},preDestroyRxDatabase:{after:e=>Ar(e)},postDestroyRxCollection:{after:e=>Ar(e)},postRemoveRxDatabase:{after:e=>$r(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>$r(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function zr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:jr}),!jr.has(e)){if(kr.has(e.name))throw I("PL3",{name:e.name,plugin:e});if(jr.add(e),kr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(j,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Qr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Kr=["#e6008d","#8d2089","#5f2688"]},1527:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{h:()=>a})},6465:(e,t,r)=>{r.r(t),r.d(t,{default:()=>c});var a=r(2303),n=r(6540),i=r(2658),s=r(5607),o=r(4848);function c(){const e=(0,a.A)();return(0,n.useEffect)((()=>{e&&(0,i.IA)()&&(async()=>{const e=await(0,i.C3)(),t=await e.getLocal(s.FORM_VALUE_DOCUMENT_ID);if(console.dir(t),t){if(t._data.data.formSubmitted)return void console.log("# lead already tracked");window.trigger("premium_lead_"+t._data.data.homeCountry.toLowerCase(),Math.floor(t._data.data.price/3)),await t.incrementalPatch({formSubmitted:!0})}else window.trigger("premium_lead_unknown",300),await e.upsertLocal(s.FORM_VALUE_DOCUMENT_ID,{formSubmitted:!0})})()})),(0,o.jsxs)("main",{children:[(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsxs)("div",{className:"redirectBox",style:{textAlign:"center"},children:[(0,o.jsx)("a",{href:"/",target:"_blank",children:(0,o.jsx)("div",{className:"logo",children:(0,o.jsx)("img",{src:"/files/logo/logo_text.svg",alt:"RxDB",width:120})})}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsx)("h1",{children:"RxDB Premium Form Submitted"}),(0,o.jsx)("br",{}),(0,o.jsxs)("p",{style:{padding:50},children:["Thank you for submitting the form. You will directly get a confirmation email.",(0,o.jsx)("br",{}),(0,o.jsx)("b",{children:"Please check your spam folder!"}),".",(0,o.jsx)("br",{}),"In the next 24 hours you will get an email with a preview of the license agreement."]}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{})]})]})}},5607:(e,t,r)=>{r.r(t),r.d(t,{FORM_VALUE_DOCUMENT_ID:()=>v,default:()=>g});var a=r(4586),n=r(1595),i=r(5260),s=r(6540),o=r(3337),c=r(7810);const l=[{name:"Antigua and Barbuda",code:"AG",salary:49527},{name:"Argentina",code:"AR",salary:17158},{name:"Australia",code:"AU",salary:76036},{name:"Austria",code:"AT",salary:59383},{name:"Bahamas",code:"BS",salary:62024},{name:"Belarus",code:"BY",salary:5749},{name:"Belgium",code:"BE",salary:63749},{name:"Bermuda",code:"BM",salary:86590},{name:"Bosnia and Herzegovina",code:"BA",salary:11992},{name:"Brazil",code:"BR",salary:26464},{name:"Bulgaria",code:"BG",salary:23384},{name:"Cambodia",code:"KH",salary:18e3},{name:"Canada",code:"CA",salary:71554},{name:"Chile",code:"CL",salary:31073},{name:"China",code:"CN",salary:40611},{name:"Colombia",code:"CO",salary:12894},{name:"Costa Rica",code:"CR",salary:40256},{name:"Croatia",code:"HR",salary:22566},{name:"Czech Republic",code:"CZ",salary:33760},{name:"Denmark",code:"DK",salary:68778},{name:"Ecuador",code:"EC",salary:35016},{name:"Egypt",code:"EG",salary:7758},{name:"Estonia",code:"EE",salary:26728},{name:"Finland",code:"FI",salary:64198},{name:"France",code:"FR",salary:58137},{name:"Georgia",code:"GE",salary:40315},{name:"Germany",code:"DE",salary:72138},{name:"Greece",code:"GR",salary:36824},{name:"Guatemala",code:"GT",salary:49612},{name:"Holy See (Vatican City State)",code:"VA",salary:51474},{name:"Hong Kong",code:"HK",salary:71970},{name:"Hungary",code:"HU",salary:22341},{name:"Iceland",code:"IS",salary:66512},{name:"India",code:"IN",salary:35420},{name:"Indonesia",code:"ID",salary:20978},{name:"Iraq",code:"IQ",salary:21029},{name:"Ireland",code:"IE",salary:66281},{name:"Israel",code:"IL",salary:57466},{name:"Italy",code:"IT",salary:50900},{name:"Jamaica",code:"JM",salary:21048},{name:"Japan",code:"JP",salary:57793},{name:"Kazakhstan",code:"KZ",salary:12243},{name:"Republic of Korea",code:"KR",salary:45957},{name:"Latvia",code:"LV",salary:26728},{name:"Luxembourg",code:"LU",salary:84663},{name:"Malaysia",code:"MY",salary:26117},{name:"Malta",code:"MT",salary:41971},{name:"Mexico",code:"MX",salary:24050},{name:"Morocco",code:"MA",salary:17903},{name:"Netherlands",code:"NL",salary:62661},{name:"New Zealand",code:"NZ",salary:63948},{name:"Norway",code:"NO",salary:69498},{name:"Pakistan",code:"PK",salary:9066},{name:"Panama",code:"PA",salary:39143},{name:"Peru",code:"PE",salary:17469},{name:"Philippines",code:"PH",salary:11088},{name:"Poland",code:"PL",salary:30236},{name:"Portugal",code:"PT",salary:37959},{name:"Romania",code:"RO",salary:22319},{name:"Russian Federation",code:"RU",salary:20492},{name:"Saudi Arabia",code:"SA",salary:47336},{name:"Singapore",code:"SG",salary:66023},{name:"Slovakia",code:"SK",salary:29650},{name:"South Africa",code:"ZA",salary:40336},{name:"Spain",code:"ES",salary:47819},{name:"Sweden",code:"SE",salary:49361},{name:"Switzerland",code:"CH",salary:92820},{name:"Taiwan",code:"TW",salary:47737},{name:"Thailand",code:"TH",salary:21772},{name:"Turkey",code:"TR",salary:8788},{name:"Ukraine",code:"UA",salary:14139},{name:"United Arab Emirates",code:"AE",salary:66381},{name:"United Kingdom",code:"GB",salary:61188},{name:"United States",code:"US",salary:91935},{name:"Uruguay",code:"UY",salary:23754},{name:"Vietnam",code:"VN",salary:19058}],u={browser:.4,native:.4,performance:.35,sourcecode:0,perpetual:0},d=.05;var h=r(1527),m=r(2658),p=r(2303),f=r(4848);function y(e){let{children:t,fallback:r}=e;return(0,p.A)()?(0,f.jsx)(f.Fragment,{children:t?.()}):r??null}const v="premium-price-form-value";function g(){const{siteConfig:e}=(0,a.A)(),t=(0,p.A)();return(0,s.useEffect)((()=>{t&&window.trigger("open_pricing_page",1),(async()=>{if(!t||!(0,m.IA)())return;const e=await(0,m.C3)(),r=await e.getLocal(v);r&&(console.log("formValueDoc:"),console.dir(r),b("home-country",r._data.data.homeCountry),b("company-size",r._data.data.companySize),b("project-amount",r._data.data.projectAmount),b("license-period",r._data.data.licensePeriod),Object.keys(u).forEach((e=>{b("package-"+e,!1)})),r._data.data.packages.forEach((e=>{b("package-"+e,!0)})),document.getElementById("price-calculator-submit").click())})()})),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.A,{children:(0,f.jsx)("body",{className:"homepage"})}),(0,f.jsx)(n.A,{title:`Premium Plugins - ${e.title}`,description:"RxDB plugins for professionals. FAQ, pricing and license",children:(0,f.jsxs)("main",{children:[(0,f.jsx)("div",{className:"block first",children:(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:[(0,f.jsx)("b",{className:"underline",children:"RxDB"})," Premium Plugins"]}),(0,f.jsxs)("p",{style:{width:"80%"},children:["RxDB's premium plugins offer advanced features and optimizations that enhance application ",(0,f.jsx)("b",{children:"performance"})," ","and are backed by dedicated support and regular updates. Using the premium plugins is recommended for users that use RxDB in a professional context."]}),(0,f.jsxs)("div",{className:"premium-blocks",children:[(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage IndexedDB"}),(0,f.jsxs)("p",{children:["A storage for browsers based on ",(0,f.jsx)("b",{children:"IndexedDB"}),". Has the best latency on writes and smallest build size."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage OPFS"}),(0,f.jsxs)("p",{children:["Currently the RxStorage with best data throughput that can be used in the browser. Based on the ",(0,f.jsx)("b",{children:"OPFS File System Access API"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SQLite"}),(0,f.jsxs)("p",{children:["A fast storage based on ",(0,f.jsx)("b",{children:"SQLite"})," for Servers and Hybrid Apps. Can be used with"," ",(0,f.jsx)("b",{children:"Node.js"}),", ",(0,f.jsx)("b",{children:"Electron"}),", ",(0,f.jsx)("b",{children:"React Native"}),", ",(0,f.jsx)("b",{children:"Capacitor"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SharedWorker"}),(0,f.jsxs)("p",{children:["A RxStorage wrapper to run the storage inside of a SharedWorker which improves the performance by taking CPU load away from the main process. Used in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Worker"}),(0,f.jsx)("p",{children:"A RxStorage wrapper to run the storage inside of a Worker which improves the performance by taking CPU load away from the main process."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Sharding"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that improves performance by applying the sharding technique."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Memory Synced"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that creates a synced in-memory copy which improves performance for the initial page load time and write & read operations."})]})})}),(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Query Optimizer"}),(0,f.jsx)("p",{children:"A tool to find the best index for a given query. You can use this during build time to find the best index and then use that index during runtime."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Localstorage Meta Optimizer"}),(0,f.jsxs)("p",{children:["A wrapper around any other storage which optimizes the initial page load one by using localstorage for meta key-value document. Only works in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"WebCrypto Encryption"}),(0,f.jsx)("p",{children:"A faster and more secure encryption plugin based on the Web Crypto API."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Filesystem Node"}),(0,f.jsxs)("p",{children:["A fast RxStorage based on the ",(0,f.jsx)("b",{children:"Node.js"})," Filesystem."]})]})})}),(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Logger"}),(0,f.jsx)("p",{children:"A logging plugin useful to debug performance problems and for monitoring with Application Performance Monitoring (APM) tools like Bugsnag, Datadog, Elastic, Sentry and others"})]})})})]})]})}),(0,f.jsx)("div",{className:"block dark",id:"faq",children:(0,f.jsxs)("div",{className:"content centered premium-faq",children:[(0,f.jsxs)("h2",{children:["F.A.Q. ",(0,f.jsx)("b",{children:"(click to toggle)"})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Do I need the Premium Plugins?"}),"RxDB Core is open source and many use cases can be implemented with the Open Core part of RxDB. There are many"," ",(0,f.jsx)("a",{href:"/rx-storage.html",target:"_blank",children:"RxStorage"})," ","options and all core plugins that are required for replication, schema validation, encryption and so on, are totally free. As soon as your application is more then a side project you can consider using the premium plugins as an easy way to improve your applications performance and reduce the build size.",(0,f.jsx)("br",{}),"The main benefit of the Premium Plugins is ",(0,f.jsx)("b",{children:"performance"}),". The Premium RxStorage implementations have a better performance so reading and writing data is much faster especially on low-end devices. You can find a performance comparison"," ",(0,f.jsx)("a",{href:"/rx-storage-performance.html",target:"_blank",children:"here"}),". Also there are additional Premium Plugins that can be used to further optimize the performance of your application like the"," ",(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})," ","or the"," ",(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"Sharding"})," ","plugin."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not for free?"}),"The development of RxDB started in 2016 and after all these years it became clear that big implementation and improvement steps will not be done by the RxDB community. While the community submits valuable pull requests, they are mostly small improvements or bugfixes for specific edge case. Big rewrites and optimizations that require a big effort have only be done by the RxDB maintainer.",(0,f.jsx)("br",{}),"Selling RxDB Premium ensures that there will be always an incentive for someone to add features, keep everything up to date and to further improve and optimize the codebase. This gives the user the confidence that RxDB is a ",(0,f.jsx)("b",{children:"future proof"})," tech stack to build on which lets RxDB stand out compared to similar technologies."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is there no free trial period?"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:"RxDB is written in JavaScript and the code of the Premium Plugins does not contain any tracking or measurement code that would send information from your application to our servers in production mode. As soon as someone has the code on his computer, the maintainer has no chance to really ensure that after a free trial period the code is no longer used and deleted."}),(0,f.jsxs)("li",{children:["Before you can use the Premium Plugins you have to debate and sign a license agreement with the maintainer. This is a sophisticated process that creates overhead which distracts the maintainer from writing RxDB code. So handling trial period users is just not manageable. For this reason there is also no monthly subscriptions. Premium access must be paid ",(0,f.jsx)("b",{children:"per year"}),"."]})]})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not cheaper?"}),"The price of the Premium Plugins is chosen in way that ensures that there can be always one person that develops RxDB ",(0,f.jsx)("b",{children:"full time"}),". Compared to other JavaScript frameworks and developer tools, RxDB satisfies an edge use case for people that want to store data inside of their application on the users device. Most web developers do not need to do that and rely on the traditional client-server stack. So RxDB cannot be sold to that many people which increases the price."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I install/build the premium plugins in my CI?"}),(0,f.jsx)("b",{children:"Yes"})," you can safely install and use the Premium Plugins in your CI without additional payment."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Which payment methods are accepted?"}),(0,f.jsx)("b",{children:"Stripe.com"})," is used as payment processor so most known payment options like credit card, PayPal, SEPA transfer and others are available. A list of all options can be found"," ",(0,f.jsx)("a",{href:"https://stripe.com/docs/payments/payment-methods/overview",title:"stripe payment options",target:"_blank",children:"here"}),"."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I get a discount?"}),"Discounts are provided for people that have made a significant contribution to RxDB or one of RxDB's dependencies or to the Open Source Community overall. Also for private personal projects there is the option to solve one of the",(0,f.jsx)("a",{href:"https://github.com/pubkey/rxdb/blob/master/orga/premium-tasks.md",target:"_blank",children:"Premium Tasks"}),"to get 2 years access to the Premium Plugins."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Is there any tracking code inside of the premium plugins?"}),"No, the premium plugins themself do not contain any tracking code. When you build your application with RxDB and deploy it to production, it will not make requests from your users to any RxDB server."]})]})}),(0,f.jsxs)("div",{className:"block",children:[(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["RxDB Premium ",(0,f.jsx)("b",{className:"underline",children:"Price Calculator"})]}),(0,f.jsx)("div",{className:"price-calculator",children:(0,f.jsx)("div",{className:"price-calculator-inner",children:(0,f.jsxs)("form",{id:"price-calculator-form",children:[(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"home-country",children:"Company Home Country:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{list:"home-country",name:"home-country",pattern:"[A-Za-z \\-\\,]{2,}",required:!0,style:{width:"100%",maxWidth:240},autoComplete:"off",placeholder:"Company Home Country"}),(0,f.jsx)("datalist",{id:"home-country",children:l.sort(((e,t)=>e.name>=t.name?1:-1)).map(((e,t)=>(0,f.jsx)("option",{value:e.name,children:e.name},t)))})]})]}),(0,f.jsx)("br",{}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"company-size",children:"Company Size:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{type:"number",name:"company-size",min:1,max:1e6,required:!0,onKeyDown:()=>{const e=(0,o.ZN)(event);return 69!==e.keyCode&&189!==e.keyCode&&190!==e.keyCode},placeholder:"Company Size"}),(0,f.jsx)("div",{className:"suffix",children:"employee(s)"})]})]}),(0,f.jsxs)("div",{className:"packages",children:[(0,f.jsx)("h3",{children:"Packages:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-browser",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Browser Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:"RxStorage OPFS"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:"RxStorage IndexedDB"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:"RxStorage Worker"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:"WebCrypto Encryption"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-native",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Native Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:"RxStorage SQLite"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:"RxStorage Filesystem Node"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-performance",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Performance Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"RxStorage Sharding"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:"RxStorage Memory Synced"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:"RxStorage Shared Worker"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-utilities",type:"checkbox",className:"package-checkbox",defaultChecked:!0,disabled:!0}),(0,f.jsxs)("h4",{children:["Utilities Package ",(0,f.jsx)("b",{children:"always included"})]}),(0,f.jsx)("ul",{children:(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:"Logger"})})})]})}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("div",{className:"button",id:"price-calculator-submit",onClick:async()=>{(0,h.h)("calculate_premium_price",3);const e=(0,o.ZN)(document.getElementById("price-calculator-form"));if(!e.reportValidity())return void console.log("form not valid");const t=new FormData(e),r=Object.fromEntries(t.entries());console.log("formData:"),console.dir(r);const a=l.find((e=>e.name.toLowerCase()===r["home-country"].toLowerCase()));if(!a)return;const n=Object.entries(r).filter((e=>{let[t,r]=e;return t.startsWith("package-")})).map((e=>{let[t]=e;return(0,c.dG)(t.split("-"))})),i={companySize:parseInt(r["company-size"],10),teamSize:r["developer-count"],projectAmount:"1",licensePeriod:1,homeCountryCode:a.code,packages:n},s=function(e){if(console.log("calculatePrice:"),console.dir(e),"number"!=typeof e.licensePeriod)throw new Error("not a number "+typeof e.licensePeriod);const t=(0,o.ZN)(l.find((t=>t.code===e.homeCountryCode))).salary;let r=0;e.packages.forEach((e=>{const t=u[e];r+=t})),console.log("aimInPercent: "+r);let a=350+1.4*t*(r/100);if(2===e.packages.length&&(a*=.9),e.packages.length>2&&(a*=.8),e.companySize>1){let t=1+Math.pow(1*e.companySize-1,.45)/100*4.5;const r=6;t>r&&(t=r),console.log("input.companySize "+e.companySize+" - "+t),a*=t}if(e.packages.includes("sourcecode")){a*=1.75;const e=1520;a1200?100*Math.floor(a/100):50*Math.floor(a/50),{totalPrice:a}}(i);console.log("priceResult:"),console.log(JSON.stringify(s,null,4));const p=(0,o.ZN)(document.getElementById("price-calculator-result")),f=(0,o.ZN)(document.getElementById("total-per-project-per-month")),y=(e,t)=>{console.log("setPrice:"),console.dir(t),e.innerHTML=Math.ceil(t).toString()},g=s.totalPrice/i.licensePeriod;y(f,"infinity"!==i.projectAmount?g/parseInt(i.projectAmount,10)/12:0);const b=await(0,m.C3)();await b.upsertLocal(v,{companySize:r["company-size"],projectAmount:r["project-amount"],licensePeriod:r["license-period"],homeCountry:a.name,packages:n,price:s.totalPrice,formSubmitted:!1}),p.style.display="block"},children:"Estimate Price"})]})})}),(0,f.jsx)("div",{className:"price-calculator",style:{marginBottom:90},children:(0,f.jsxs)("div",{className:"price-calculator-inner",id:"price-calculator-result",style:{display:"none"},children:[(0,f.jsx)("h4",{children:"Estimated Price:"}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"inner",children:[(0,f.jsx)("span",{className:"price-label",children:"\u20ac"}),(0,f.jsx)("span",{id:"total-per-project-per-month",children:"84"}),(0,f.jsx)("span",{className:"per-month",children:"/month"}),(0,f.jsx)("span",{className:"clear"})]}),(0,f.jsx)("br",{}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"proceed-hint",children:["Fill out the ",(0,f.jsx)("b",{children:"form below \u2193"})," to proceed."]})]})})]}),(0,f.jsx)("div",{className:"block dark",id:"premium-request-form-block",children:(0,f.jsxs)("div",{className:"content centered premium-request",children:[(0,f.jsxs)("h2",{children:["Request Premium ",(0,f.jsx)("b",{className:"underline",children:"Form"})]}),(0,f.jsx)("p",{}),(0,f.jsx)(y,{fallback:(0,f.jsx)("span",{children:"Loading form iframe..."}),children:()=>(0,f.jsxs)("iframe",{id:"request-premium-form",src:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",children:["Your browser doesn't support iframes, ",(0,f.jsx)("a",{href:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",target:"_blank",rel:"nofollow",children:"go here"})]})})]})})]})]})})]})}function b(e,t){if(void 0===t)return;const r=document.querySelector("[name="+e+"]");r&&(r.type&&"checkbox"===r.type?r.checked=t:r.value=t)}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>l,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>u,dY:()=>a,em:()=>o,h$:()=>d,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function d(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/cde77f4f.ebf53539.js b/docs/assets/js/cde77f4f.ebf53539.js deleted file mode 100644 index 5ea6067bb98..00000000000 --- a/docs/assets/js/cde77f4f.ebf53539.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[6287,2584],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Kr,C3:()=>zr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},d=new Set(["__proto__","prototype","constructor"]),h=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(d.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(d.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!h.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(d.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function y(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,w.A)(Error)),_=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,w.A)(TypeError));function I(e,t){return new D(e,j.tunnelErrorMessage(e),t)}function R(e,t){return new _(e,j.tunnelErrorMessage(e),t)}function S(e){return!(!e||409!==e.status)&&e}var E={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var C=/\./g,P="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=y(t,e);if(void 0===r)throw I("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function F(e){var t=q((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=Q,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var Q={type:"object",properties:{lwt:{type:"number",minimum:$,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=q(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",z="changes",K="attachments",U="dexie",Z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=q(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),le=r(3337),ue=String.fromCharCode(65535),de=Number.MIN_SAFE_INTEGER;function he(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:l?de:ue,endKey:a?ue:de,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=de),void 0===i.endKey&&(i.endKey=ue),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),l&&!i.inclusiveStart&&(l=!1),a&&!i.inclusiveEnd&&(a=!1),i})),d=u.map((e=>e.startKey)),h=u.map((e=>e.endKey)),m={index:e,startKeys:d,endKeys:h,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ye(e,t.selector,d,h)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==de&&e!==ue));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==ue&&e!==de));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,s=m)})),!s)throw I("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ye(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&s.add(o),"$eq"!==u){if(i.length>0)return!1;i.push(u)}}var d=[],h=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var y=f[0];if(y&&h.add(m),"$eq"!==y){if(d.length>0)return!1;d.push(y)}}var v=0;for(var g of e){for(var b of[s,h]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[v]!==a[v]&&s.size>0&&h.size>0)return!1;v++}return!0}var ve=r(744),ge=r(2779),be=r(1692),xe=r(4903),we=r(7705),je=r(2403),ke=r(6776),De=r(6950),_e=r(6823),Ie=!1;function Re(e){return Ie||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:xe.xF,$project:xe.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:we.a6,$eq:je.XV,$elemMatch:De.Jy,$exists:_e.P,$gt:je.MR,$gte:je.fy,$in:je.oZ,$lt:je.NV,$lte:je.Q_,$ne:je.C5,$nin:je.GU,$mod:ke.Pp,$nor:we.q3,$not:we.En,$or:we.sU,$regex:ke.WP,$size:De.Ig,$type:_e.T}),Ie=!0),new be.X(e)}function Se(e,t){var r=q(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ee(e,t){if(!t.sort)throw I("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Pe(e){return e===de?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Ne(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Pe);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ae(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=Ce(e.schema,t.query));var c=Ne(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),l=s.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),s.sortSatisfiedByIndex&&u.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var d=Ee(e.schema,t.query);u=u.sort(d)}return{documents:u=u.slice(n,i)}}function $e(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Be(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?$e(r).height:0)+1+"-"+e}var Te="_rxdb_internal";async function qe(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Fe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:j.deepFreezeWhenDevMode(a),previousDocumentData:j.deepFreezeWhenDevMode(n)}}function Qe(e,t,r,a){if(a)throw 409===a.status?I("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?I("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function ze(e){var t=s(e);return t._meta=s(e._meta),t}function Ke(e,t,r){j.deepFreezeWhenDevMode(r);var a=q(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),j.isDevMode()){i=T(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw I("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw I("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:B(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(3561),Ze=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ze.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ue.X)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),u()};var d=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),d()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=q(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw I("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,l=[],u=[],d=[],h={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=h.events,p=[],f=[],y=[],v=r.size>0,g=a.length,b=function(){var e,n=a[x],h=n.document,g=n.previous,b=h[t],w=h._deleted,j=g&&g._deleted,k=void 0;if(v&&(k=r.get(b)),k){var D=k._rev;if(!g||g&&D!==g._rev){var _={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return d.push(_),1}var R=c?We(n):n;c&&(w?g&&Object.keys(g._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.ZN)(g)._attachments[e].digest})})):(Object.entries(h._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(h._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&y.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?d.push(e):(c?(u.push(We(R)),s&&s(h)):(u.push(R),s&&s(h)),o=R);var S=null,E=null,C=null;if(j&&!w)C="INSERT",S=c?He(h):h;else if(!g||j||w){if(!w)throw I("SNH",{args:{writeRow:n}});C="DELETE",S=(0,le.ZN)(h),E=g}else C="UPDATE",S=c?He(h):h,E=g;var P={documentId:b,documentData:S,previousDocumentData:E,operation:C};m.push(P)}else{var O=!!w;if(c&&Object.entries(h._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},d.push(e))})),e||(c?(l.push(We(n)),i&&i(h)):(l.push(n),i&&i(h)),o=n),!O){var N={documentId:b,operation:"INSERT",documentData:c?He(h):h,previousDocumentData:c&&g?He(g):g};m.push(N)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,le.ZN)(r)).eventBulk.events.length>0){var s=(0,le.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ae(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=Ne(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ae(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(Z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[z]:"++sequence, id",[K]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[K],booleanIndexes:se(n)}})();return Z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw I("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw I("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw I("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=q(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw I("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function lt(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=F(e);a=function(e){return o(e,!0)}(a),j.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ut=r(7708),dt=r(8146),ht=r(3356),mt=r(5520),pt=r(8609),ft=r(1753);function yt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=N(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 ")}function vt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=$e(i._rev).height,n.forEach((e=>{var t=$e(e._rev).height;t>s&&(i=e,s=t)})),i),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(d){u.reject(d),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(d){return void a.forEach((e=>e.reject(d)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=S(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.ZN)(o.documentInDb),(0,le.ZN)(c).unshift(e)}))}else{var l=I("COL20",{name:E[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={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.$.pipe((0,ut.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,dt.p)((e=>e.documentId===this.primary)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.t)(le.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(j.isDevMode()){if(e.includes(".item."))throw I("DOC1",{path:e});if(e===this.primaryPath)throw I("DOC2");if(this.collection.schema.finalFields.includes(e))throw I("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw I("DOC4",{path:e})}return this.$.pipe((0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.$A;if(!t)throw I("DOC5",{path:e});if(!t.ref)throw I("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw I("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=y(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return j.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(A(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(A(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(A(e+"."+o))}return r.get(A(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return j.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,j.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw yt("update")},incrementalUpdate(e){throw yt("update")},updateCRDT(e){throw yt("crdt")},putAttachment(){throw yt("attachments")},getAttachment(){throw yt("attachments")},allAttachments(){throw yt("attachments")},get allAttachments$(){throw yt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw I("DOC11",{id:this.primary,document:this});await jt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Qe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(I("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Qe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw I("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function jt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),j.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(2198),Dt=r(511),_t=r(4157),It=r(2442),Rt=r(6114);function St(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Et=new WeakMap;function Ct(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Et,e,(()=>{var t=e.collection,r=Se(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ee(t.schema.jsonSchema,r),i=Ce(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:St(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.ZN)(e._result).docsData.slice(0),n=(0,le.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:j.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Rt.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Rt.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var Pt=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Nt(e){return e.refCount$.observers.length}var At,$t,Bt=(At=100,$t=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Ot(t,e)))}}),Mt=new WeakSet;var Tt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=vt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=j.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],l=Be(o._rev),u=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),d=u.byRev,h=d.get(l),m=h?h.deref():void 0;return m||(o=n(o),m=s(o),d.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Be(e.revision)})})))}))))),m};return o}(this))}}]),e}();function qt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Ft=function(){function e(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=qt(this.collection._docCache,t)}return(0,b.A)(e,[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Ft(this.collection,e,e.length);this._result=t}else this._result=new Ft(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw I("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw I("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,Dt._)(this.$))).then((t=>{if(!t&&e)throw I("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Se(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw yt("update")},t.where=function(e){throw yt("query-builder")},t.sort=function(e){throw yt("query-builder")},t.skip=function(e){throw yt("query-builder")},t.limit=function(e){throw yt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,dt.p)((e=>!e.isLocal)),(0,ht.Z)(null),(0,It.Z)((()=>Kt(this))),(0,ut.T)((()=>this._result)),(0,pt.t)(le.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,le.ZN)(t).time))),(0,dt.p)((e=>!!e)),(0,ut.T)((e=>{var t=(0,le.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,_t.h)(e,this.refCount$.pipe((0,dt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Ce(0,Se(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,ft.dY)().then((()=>(0,ft.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function zt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||zt(e)?ft.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||zt(e))return ft.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,le.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=Ct(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:j.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var u=o.map((e=>{var t=ze(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,dt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>wt(sr(e))))}(e),e,j.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],dr=!1,hr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Bt),void 0===u&&(u={}),void 0===d&&(d=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Pt,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=d,function(e){if(dr)return;dr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+N(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>jt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,dt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,It.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Tt(this.schema.primaryPath,this.$.pipe((0,dt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Fe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.em},t.cleanup=function(e){throw yt("cleanup")},t.migrationNeeded=function(){throw yt("migration-schema")},t.getMigrationState=function(){throw yt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Qe(this,e[this.schema.primaryPath],e,r),(0,le.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=qt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw I("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));i.push(l)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Qe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw I("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw I("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw I("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.insertCRDT=function(e){throw yt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!ur.includes(t))throw I("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw I("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.em;var i=n.series.map((e=>()=>e(r,a)));return(0,ft.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,dt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,dt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,dt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7635),pr=r(1007);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.sc)(e))},yr=r(5525),vr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,d,h){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,It.Z)((e=>e.events))),this.storageToken=ft.Dr,this.storageTokenDocument=ft.Dr,this.emittedEventBulkIds=new yr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=d,this.reactivity=h,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:B(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,le.ZN)(n.error[0]);if(i.isError&&S(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw I("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw I("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,le.ZN)(o)}var c,l;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw I("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await qe(this.internalStore,Gt(tr(e,t),Zt));if(!r)throw I("SNH",{name:e,schema:t});var a=ze(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[i])throw I("DB3",{name:i});var d=tr(i,l),h={id:Gt(d,Zt),key:d,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:B(),_rev:"",_attachments:{}};a.push({document:h});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=s(o);p.database=this,p.name=i,st("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw I("DB12",{database:this.name,writeError:e});var a=(0,le.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw I("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,le.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:d=!1,cacheReplacementPolicy:h=Bt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:j.isDevMode()};return st("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new hr(t,r,a,e,n,i,c,l,u,h,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.em;return s&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:l,options:u,cacheReplacementPolicy:h,localDocuments:d,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw yt("json-dump")},t.addState=function(e){throw yt("state")},t.importJSON=function(e){throw yt("json-dump")},t.backup=function(e){throw yt("backup")},t.leaderElector=function(){throw yt("leader-election")},t.isLeader=function(){throw yt("leader-election")},t.waitForLeadership=function(){throw yt("leader-election")},t.migrationStates=function(){throw yt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>vr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Te,schema:Jt,options:a,multiInstance:n,password:i,devMode:j.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:d=!1,hashFunction:h=fr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}),o||function(e,t){var r=t.name+"|"+e;if(vr.has(r))throw I("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),vr.add(t.name+"|"+a);var p=O(10);return br(p,t,a,r,i,n).catch((e=>{throw vr.delete(t.name+"|"+a),e})).then((e=>{var f=new gr(a,p,t,r,n,i,s,c,e,h,l,u,m);return ot("createRxDatabase",{database:f,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:d}}).then((()=>f))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Wt.prototype,RxCollection:hr.prototype,RxDatabase:gr.prototype},jr=new Set,kr=new Set;var Dr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.A)(t,e),t}(wt()),_r={get isLocal(){return!0},get allAttachments$(){throw I("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,dt.p)((e=>e.documentId===this.primary)),(0,dt.p)((e=>e.isLocal)),(0,ut.T)((e=>vt(e))),(0,ht.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ut.T)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.t)(le.bz))},get $$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Sr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=y(this._data,e);return t=j.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,j.isDevMode()){if(e.includes(".item."))throw I("LD3",{objPath:e});if(e===this.primaryPath)throw I("LD4")}return this.$.pipe((0,ut.T)((e=>e._data)),(0,ut.T)((t=>y(t,e))),(0,mt.F)())},get$$(e){return Sr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:B(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Ir=!1,Rr=()=>{if(!Ir){Ir=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(_r,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(_r,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>_r[e]=(e=>()=>{throw I("LD6",{functionName:e})})(e)))}};function Sr(e){var t=e.parent;return t instanceof gr?t:t.database}var Er=new WeakMap,Cr=new WeakMap;function Pr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Nr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Mr);var n=new Tt("id",e.$.pipe((0,dt.p)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new Dr(e.id,e,t);return Object.setPrototypeOf(r,_r),r.prototype=_r,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Fe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw I("LD8",{database:r.name,collection:a})}return t}function Nr(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Br(a),schema:Mr,options:n,multiInstance:i,devMode:j.isDevMode()})}function Ar(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function $r(e,t,r){var a=O(10),n=await Nr(a,e,t,r,{},!1);await n.remove()}function Br(e){return"plugin-local-documents-"+e}var Mr=F({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Tr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:B(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function qr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):qe(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Fr(e){return this.$.pipe((0,ht.Z)(null),(0,It.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,It.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,dt.p)((e=>e.use)),(0,ut.T)((e=>e.doc)))}var Qr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr},RxDatabase:e=>{e.insertLocal=Tr,e.upsertLocal=qr,e.getLocal=Lr,e.getLocal$=Fr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Pr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Pr(e.collection)}},preDestroyRxDatabase:{after:e=>Ar(e)},postDestroyRxCollection:{after:e=>Ar(e)},postRemoveRxDatabase:{after:e=>$r(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>$r(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function zr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:jr}),!jr.has(e)){if(kr.has(e.name))throw I("PL3",{name:e.name,plugin:e});if(jr.add(e),kr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(j,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Qr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Kr=["#e6008d","#8d2089","#5f2688"]},1527:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{h:()=>a})},6465:(e,t,r)=>{r.r(t),r.d(t,{default:()=>c});var a=r(2303),n=r(6540),i=r(2658),s=r(5607),o=r(4848);function c(){const e=(0,a.A)();return(0,n.useEffect)((()=>{e&&(0,i.IA)()&&(async()=>{const e=await(0,i.C3)(),t=await e.getLocal(s.FORM_VALUE_DOCUMENT_ID);if(console.dir(t),t){if(t._data.data.formSubmitted)return void console.log("# lead already tracked");window.trigger("premium_lead_"+t._data.data.homeCountry.toLowerCase(),Math.floor(t._data.data.price/3)),await t.incrementalPatch({formSubmitted:!0})}else window.trigger("premium_lead_unknown",300),await e.upsertLocal(s.FORM_VALUE_DOCUMENT_ID,{formSubmitted:!0})})()})),(0,o.jsxs)("main",{children:[(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsxs)("div",{className:"redirectBox",style:{textAlign:"center"},children:[(0,o.jsx)("a",{href:"/",target:"_blank",children:(0,o.jsx)("div",{className:"logo",children:(0,o.jsx)("img",{src:"/files/logo/logo_text.svg",alt:"RxDB",width:120})})}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{}),(0,o.jsx)("h1",{children:"RxDB Premium Form Submitted"}),(0,o.jsx)("br",{}),(0,o.jsxs)("p",{style:{padding:50},children:["Thank you for submitting the form. You will directly get a confirmation email.",(0,o.jsx)("br",{}),(0,o.jsx)("b",{children:"Please check your spam folder!"}),".",(0,o.jsx)("br",{}),"In the next 24 hours you will get an email with a preview of the license agreement."]}),(0,o.jsx)("br",{}),(0,o.jsx)("br",{})]})]})}},5607:(e,t,r)=>{r.r(t),r.d(t,{FORM_VALUE_DOCUMENT_ID:()=>v,default:()=>g});var a=r(4586),n=r(1595),i=r(5260),s=r(6540),o=r(3337),c=r(7810);const l=[{name:"Antigua and Barbuda",code:"AG",salary:49527},{name:"Argentina",code:"AR",salary:17158},{name:"Australia",code:"AU",salary:76036},{name:"Austria",code:"AT",salary:59383},{name:"Bahamas",code:"BS",salary:62024},{name:"Belarus",code:"BY",salary:5749},{name:"Belgium",code:"BE",salary:63749},{name:"Bermuda",code:"BM",salary:86590},{name:"Bosnia and Herzegovina",code:"BA",salary:11992},{name:"Brazil",code:"BR",salary:26464},{name:"Bulgaria",code:"BG",salary:23384},{name:"Cambodia",code:"KH",salary:18e3},{name:"Canada",code:"CA",salary:71554},{name:"Chile",code:"CL",salary:31073},{name:"China",code:"CN",salary:40611},{name:"Colombia",code:"CO",salary:12894},{name:"Costa Rica",code:"CR",salary:40256},{name:"Croatia",code:"HR",salary:22566},{name:"Czech Republic",code:"CZ",salary:33760},{name:"Denmark",code:"DK",salary:68778},{name:"Ecuador",code:"EC",salary:35016},{name:"Egypt",code:"EG",salary:7758},{name:"Estonia",code:"EE",salary:26728},{name:"Finland",code:"FI",salary:64198},{name:"France",code:"FR",salary:58137},{name:"Georgia",code:"GE",salary:40315},{name:"Germany",code:"DE",salary:72138},{name:"Greece",code:"GR",salary:36824},{name:"Guatemala",code:"GT",salary:49612},{name:"Holy See (Vatican City State)",code:"VA",salary:51474},{name:"Hong Kong",code:"HK",salary:71970},{name:"Hungary",code:"HU",salary:22341},{name:"Iceland",code:"IS",salary:66512},{name:"India",code:"IN",salary:35420},{name:"Indonesia",code:"ID",salary:20978},{name:"Iraq",code:"IQ",salary:21029},{name:"Ireland",code:"IE",salary:66281},{name:"Israel",code:"IL",salary:57466},{name:"Italy",code:"IT",salary:50900},{name:"Jamaica",code:"JM",salary:21048},{name:"Japan",code:"JP",salary:57793},{name:"Kazakhstan",code:"KZ",salary:12243},{name:"Republic of Korea",code:"KR",salary:45957},{name:"Latvia",code:"LV",salary:26728},{name:"Luxembourg",code:"LU",salary:84663},{name:"Malaysia",code:"MY",salary:26117},{name:"Malta",code:"MT",salary:41971},{name:"Mexico",code:"MX",salary:24050},{name:"Morocco",code:"MA",salary:17903},{name:"Netherlands",code:"NL",salary:62661},{name:"New Zealand",code:"NZ",salary:63948},{name:"Norway",code:"NO",salary:69498},{name:"Pakistan",code:"PK",salary:9066},{name:"Panama",code:"PA",salary:39143},{name:"Peru",code:"PE",salary:17469},{name:"Philippines",code:"PH",salary:11088},{name:"Poland",code:"PL",salary:30236},{name:"Portugal",code:"PT",salary:37959},{name:"Romania",code:"RO",salary:22319},{name:"Russian Federation",code:"RU",salary:20492},{name:"Saudi Arabia",code:"SA",salary:47336},{name:"Singapore",code:"SG",salary:66023},{name:"Slovakia",code:"SK",salary:29650},{name:"South Africa",code:"ZA",salary:40336},{name:"Spain",code:"ES",salary:47819},{name:"Sweden",code:"SE",salary:49361},{name:"Switzerland",code:"CH",salary:92820},{name:"Taiwan",code:"TW",salary:47737},{name:"Thailand",code:"TH",salary:21772},{name:"Turkey",code:"TR",salary:8788},{name:"Ukraine",code:"UA",salary:14139},{name:"United Arab Emirates",code:"AE",salary:66381},{name:"United Kingdom",code:"GB",salary:61188},{name:"United States",code:"US",salary:91935},{name:"Uruguay",code:"UY",salary:23754},{name:"Vietnam",code:"VN",salary:19058}],u={browser:.4,native:.4,performance:.35,sourcecode:0,perpetual:0},d=.05;var h=r(1527),m=r(2658),p=r(2303),f=r(4848);function y(e){let{children:t,fallback:r}=e;return(0,p.A)()?(0,f.jsx)(f.Fragment,{children:t?.()}):r??null}const v="premium-price-form-value";function g(){const{siteConfig:e}=(0,a.A)(),t=(0,p.A)();return(0,s.useEffect)((()=>{t&&window.trigger("open_pricing_page",1),(async()=>{if(!t||!(0,m.IA)())return;const e=await(0,m.C3)(),r=await e.getLocal(v);r&&(console.log("formValueDoc:"),console.dir(r),b("home-country",r._data.data.homeCountry),b("company-size",r._data.data.companySize),b("project-amount",r._data.data.projectAmount),b("license-period",r._data.data.licensePeriod),Object.keys(u).forEach((e=>{b("package-"+e,!1)})),r._data.data.packages.forEach((e=>{b("package-"+e,!0)})),document.getElementById("price-calculator-submit").click())})()})),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.A,{children:(0,f.jsx)("body",{className:"homepage"})}),(0,f.jsx)(n.A,{title:`Premium Plugins - ${e.title}`,description:"RxDB plugins for professionals. FAQ, pricing and license",children:(0,f.jsxs)("main",{children:[(0,f.jsx)("div",{className:"block first",children:(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:[(0,f.jsx)("b",{className:"underline",children:"RxDB"})," Premium Plugins"]}),(0,f.jsxs)("p",{style:{width:"80%"},children:["RxDB's premium plugins offer advanced features and optimizations that enhance application ",(0,f.jsx)("b",{children:"performance"})," ","and are backed by dedicated support and regular updates. Using the premium plugins is recommended for users that use RxDB in a professional context."]}),(0,f.jsxs)("div",{className:"premium-blocks",children:[(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage IndexedDB"}),(0,f.jsxs)("p",{children:["A storage for browsers based on ",(0,f.jsx)("b",{children:"IndexedDB"}),". Has the best latency on writes and smallest build size."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage OPFS"}),(0,f.jsxs)("p",{children:["Currently the RxStorage with best data throughput that can be used in the browser. Based on the ",(0,f.jsx)("b",{children:"OPFS File System Access API"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SQLite"}),(0,f.jsxs)("p",{children:["A fast storage based on ",(0,f.jsx)("b",{children:"SQLite"})," for Servers and Hybrid Apps. Can be used with"," ",(0,f.jsx)("b",{children:"Node.js"}),", ",(0,f.jsx)("b",{children:"Electron"}),", ",(0,f.jsx)("b",{children:"React Native"}),", ",(0,f.jsx)("b",{children:"Capacitor"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SharedWorker"}),(0,f.jsxs)("p",{children:["A RxStorage wrapper to run the storage inside of a SharedWorker which improves the performance by taking CPU load away from the main process. Used in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Worker"}),(0,f.jsx)("p",{children:"A RxStorage wrapper to run the storage inside of a Worker which improves the performance by taking CPU load away from the main process."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Sharding"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that improves performance by applying the sharding technique."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Memory Synced"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that creates a synced in-memory copy which improves performance for the initial page load time and write & read operations."})]})})}),(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Query Optimizer"}),(0,f.jsx)("p",{children:"A tool to find the best index for a given query. You can use this during build time to find the best index and then use that index during runtime."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Localstorage Meta Optimizer"}),(0,f.jsxs)("p",{children:["A wrapper around any other storage which optimizes the initial page load one by using localstorage for meta key-value document. Only works in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"WebCrypto Encryption"}),(0,f.jsx)("p",{children:"A faster and more secure encryption plugin based on the Web Crypto API."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Filesystem Node"}),(0,f.jsxs)("p",{children:["A fast RxStorage based on the ",(0,f.jsx)("b",{children:"Node.js"})," Filesystem."]})]})})}),(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Logger"}),(0,f.jsx)("p",{children:"A logging plugin useful to debug performance problems and for monitoring with Application Performance Monitoring (APM) tools like Bugsnag, Datadog, Elastic, Sentry and others"})]})})})]})]})}),(0,f.jsx)("div",{className:"block dark",id:"faq",children:(0,f.jsxs)("div",{className:"content centered premium-faq",children:[(0,f.jsxs)("h2",{children:["F.A.Q. ",(0,f.jsx)("b",{children:"(click to toggle)"})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Do I need the Premium Plugins?"}),"RxDB Core is open source and many use cases can be implemented with the Open Core part of RxDB. There are many"," ",(0,f.jsx)("a",{href:"/rx-storage.html",target:"_blank",children:"RxStorage"})," ","options and all core plugins that are required for replication, schema validation, encryption and so on, are totally free. As soon as your application is more then a side project you can consider using the premium plugins as an easy way to improve your applications performance and reduce the build size.",(0,f.jsx)("br",{}),"The main benefit of the Premium Plugins is ",(0,f.jsx)("b",{children:"performance"}),". The Premium RxStorage implementations have a better performance so reading and writing data is much faster especially on low-end devices. You can find a performance comparison"," ",(0,f.jsx)("a",{href:"/rx-storage-performance.html",target:"_blank",children:"here"}),". Also there are additional Premium Plugins that can be used to further optimize the performance of your application like the"," ",(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})," ","or the"," ",(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"Sharding"})," ","plugin."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not for free?"}),"The development of RxDB started in 2016 and after all these years it became clear that big implementation and improvement steps will not be done by the RxDB community. While the community submits valuable pull requests, they are mostly small improvements or bugfixes for specific edge case. Big rewrites and optimizations that require a big effort have only be done by the RxDB maintainer.",(0,f.jsx)("br",{}),"Selling RxDB Premium ensures that there will be always an incentive for someone to add features, keep everything up to date and to further improve and optimize the codebase. This gives the user the confidence that RxDB is a ",(0,f.jsx)("b",{children:"future proof"})," tech stack to build on which lets RxDB stand out compared to similar technologies."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is there no free trial period?"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:"RxDB is written in JavaScript and the code of the Premium Plugins does not contain any tracking or measurement code that would send information from your application to our servers in production mode. As soon as someone has the code on his computer, the maintainer has no chance to really ensure that after a free trial period the code is no longer used and deleted."}),(0,f.jsxs)("li",{children:["Before you can use the Premium Plugins you have to debate and sign a license agreement with the maintainer. This is a sophisticated process that creates overhead which distracts the maintainer from writing RxDB code. So handling trial period users is just not manageable. For this reason there is also no monthly subscriptions. Premium access must be paid ",(0,f.jsx)("b",{children:"per year"}),"."]})]})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not cheaper?"}),"The price of the Premium Plugins is chosen in way that ensures that there can be always one person that develops RxDB ",(0,f.jsx)("b",{children:"full time"}),". Compared to other JavaScript frameworks and developer tools, RxDB satisfies an edge use case for people that want to store data inside of their application on the users device. Most web developers do not need to do that and rely on the traditional client-server stack. So RxDB cannot be sold to that many people which increases the price."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I install/build the premium plugins in my CI?"}),(0,f.jsx)("b",{children:"Yes"})," you can safely install and use the Premium Plugins in your CI without additional payment."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Which payment methods are accepted?"}),(0,f.jsx)("b",{children:"Stripe.com"})," is used as payment processor so most known payment options like credit card, PayPal, SEPA transfer and others are available. A list of all options can be found"," ",(0,f.jsx)("a",{href:"https://stripe.com/docs/payments/payment-methods/overview",title:"stripe payment options",target:"_blank",children:"here"}),"."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I get a discount?"}),"Discounts are provided for people that have made a significant contribution to RxDB or one of RxDB's dependencies or to the Open Source Community overall. Also for private personal projects there is the option to solve one of the",(0,f.jsx)("a",{href:"https://github.com/pubkey/rxdb/blob/master/orga/premium-tasks.md",target:"_blank",children:"Premium Tasks"}),"to get 2 years access to the Premium Plugins."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Is there any tracking code inside of the premium plugins?"}),"No, the premium plugins themself do not contain any tracking code. When you build your application with RxDB and deploy it to production, it will not make requests from your users to any RxDB server."]})]})}),(0,f.jsxs)("div",{className:"block",children:[(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["RxDB Premium ",(0,f.jsx)("b",{className:"underline",children:"Price Calculator"})]}),(0,f.jsx)("div",{className:"price-calculator",children:(0,f.jsx)("div",{className:"price-calculator-inner",children:(0,f.jsxs)("form",{id:"price-calculator-form",children:[(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"home-country",children:"Company Home Country:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{list:"home-country",name:"home-country",pattern:"[A-Za-z \\-\\,]{2,}",required:!0,style:{width:"100%",maxWidth:240},autoComplete:"off",placeholder:"Company Home Country"}),(0,f.jsx)("datalist",{id:"home-country",children:l.sort(((e,t)=>e.name>=t.name?1:-1)).map(((e,t)=>(0,f.jsx)("option",{value:e.name,children:e.name},t)))})]})]}),(0,f.jsx)("br",{}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"company-size",children:"Company Size:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{type:"number",name:"company-size",min:1,max:1e6,required:!0,onKeyDown:()=>{const e=(0,o.ZN)(event);return 69!==e.keyCode&&189!==e.keyCode&&190!==e.keyCode},placeholder:"Company Size"}),(0,f.jsx)("div",{className:"suffix",children:"employee(s)"})]})]}),(0,f.jsxs)("div",{className:"packages",children:[(0,f.jsx)("h3",{children:"Packages:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-browser",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Browser Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:"RxStorage OPFS"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:"RxStorage IndexedDB"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:"RxStorage Worker"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:"WebCrypto Encryption"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-native",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Native Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:"RxStorage SQLite"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:"RxStorage Filesystem Node"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-performance",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Performance Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"RxStorage Sharding"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:"RxStorage Memory Synced"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:"RxStorage Shared Worker"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-utilities",type:"checkbox",className:"package-checkbox",defaultChecked:!0,disabled:!0}),(0,f.jsxs)("h4",{children:["Utilities Package ",(0,f.jsx)("b",{children:"always included"})]}),(0,f.jsx)("ul",{children:(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:"Logger"})})})]})}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("div",{className:"button",id:"price-calculator-submit",onClick:async()=>{(0,h.h)("calculate_premium_price",3);const e=(0,o.ZN)(document.getElementById("price-calculator-form"));if(!e.reportValidity())return void console.log("form not valid");const t=new FormData(e),r=Object.fromEntries(t.entries());console.log("formData:"),console.dir(r);const a=l.find((e=>e.name.toLowerCase()===r["home-country"].toLowerCase()));if(!a)return;const n=Object.entries(r).filter((e=>{let[t,r]=e;return t.startsWith("package-")})).map((e=>{let[t]=e;return(0,c.dG)(t.split("-"))})),i={companySize:parseInt(r["company-size"],10),teamSize:r["developer-count"],projectAmount:"1",licensePeriod:1,homeCountryCode:a.code,packages:n},s=function(e){if(console.log("calculatePrice:"),console.dir(e),"number"!=typeof e.licensePeriod)throw new Error("not a number "+typeof e.licensePeriod);const t=(0,o.ZN)(l.find((t=>t.code===e.homeCountryCode))).salary;let r=0;e.packages.forEach((e=>{const t=u[e];r+=t})),console.log("aimInPercent: "+r);let a=350+1.4*t*(r/100);if(2===e.packages.length&&(a*=.8),e.packages.length>2&&(a*=.7),e.companySize>1){let t=1+Math.pow(1*e.companySize-1,.85)/100*4.5;const r=6;t>r&&(t=r),console.log("input.companySize "+e.companySize+" - "+t),a*=t}if(e.packages.includes("sourcecode")){a*=1.75;const e=1520;a1200?100*Math.floor(a/100):50*Math.floor(a/50),{totalPrice:a}}(i);console.log("priceResult:"),console.log(JSON.stringify(s,null,4));const p=(0,o.ZN)(document.getElementById("price-calculator-result")),f=(0,o.ZN)(document.getElementById("total-per-project-per-month")),y=(e,t)=>{console.log("setPrice:"),console.dir(t),e.innerHTML=Math.ceil(t).toString()},g=s.totalPrice/i.licensePeriod;y(f,"infinity"!==i.projectAmount?g/parseInt(i.projectAmount,10)/12:0);const b=await(0,m.C3)();await b.upsertLocal(v,{companySize:r["company-size"],projectAmount:r["project-amount"],licensePeriod:r["license-period"],homeCountry:a.name,packages:n,price:s.totalPrice,formSubmitted:!1}),p.style.display="block"},children:"Estimate Price"})]})})}),(0,f.jsx)("div",{className:"price-calculator",style:{marginBottom:90},children:(0,f.jsxs)("div",{className:"price-calculator-inner",id:"price-calculator-result",style:{display:"none"},children:[(0,f.jsx)("h4",{children:"Estimated Price:"}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"inner",children:[(0,f.jsx)("span",{className:"price-label",children:"\u20ac"}),(0,f.jsx)("span",{id:"total-per-project-per-month",children:"84"}),(0,f.jsx)("span",{className:"per-month",children:"/month"}),(0,f.jsx)("span",{className:"clear"})]}),(0,f.jsx)("br",{}),(0,f.jsx)("br",{}),(0,f.jsxs)("div",{className:"proceed-hint",children:["Fill out the ",(0,f.jsx)("b",{children:"form below \u2193"})," to proceed."]})]})})]}),(0,f.jsx)("div",{className:"block dark",id:"premium-request-form-block",children:(0,f.jsxs)("div",{className:"content centered premium-request",children:[(0,f.jsxs)("h2",{children:["Request Premium ",(0,f.jsx)("b",{className:"underline",children:"Form"})]}),(0,f.jsx)("p",{}),(0,f.jsx)(y,{fallback:(0,f.jsx)("span",{children:"Loading form iframe..."}),children:()=>(0,f.jsxs)("iframe",{id:"request-premium-form",src:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",children:["Your browser doesn't support iframes, ",(0,f.jsx)("a",{href:"https://webforms.pipedrive.com/f/c5cAfYVe373ccihUfJkyxdU2zg5Iz2liQB09nU6jOQCyRXOJy6W7qPdQdmomvugRj5",target:"_blank",rel:"nofollow",children:"go here"})]})})]})})]})]})})]})}function b(e,t){if(void 0===t)return;const r=document.querySelector("[name="+e+"]");r&&(r.type&&"checkbox"===r.type?r.checked=t:r.value=t)}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>l,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>u,dY:()=>a,em:()=>o,h$:()=>d,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function d(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/db34d6b0.a6415fdf.js b/docs/assets/js/db34d6b0.a6415fdf.js new file mode 100644 index 00000000000..bcba720a746 --- /dev/null +++ b/docs/assets/js/db34d6b0.a6415fdf.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[7320],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Zr,C3:()=>Kr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function u(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var h=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},l=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(l.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(l.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(l.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function f(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function p(e,t){if(f(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!h(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function _(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var k=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])}((0,D.A)(Error)),I=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}])}((0,D.A)(TypeError));function E(e,t){return new k(e,x.tunnelErrorMessage(e),t)}function O(e,t){return new I(e,x.tunnelErrorMessage(e),t)}function R(e){return!(!e||409!==e.status)&&e}var C={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var j=/\./g,S="abcdefghijklmnopqrstuvwxyz";function P(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw E("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function Q(e){var t=B((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=F,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var F={type:"object",properties:{lwt:{type:"number",minimum:A,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=B(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",K="changes",Z="attachments",U="dexie",z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=B(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===q(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),ue=r(3337),he=String.fromCharCode(65535),le=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=q(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,u=!0,h=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:u?le:he,endKey:a?he:le,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=le),void 0===i.endKey&&(i.endKey=he),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),u&&!i.inclusiveStart&&(u=!1),a&&!i.inclusiveEnd&&(a=!1),i})),l=h.map((e=>e.startKey)),d=h.map((e=>e.endKey)),m={index:e,startKeys:l,endKeys:d,inclusiveEnd:a,inclusiveStart:u,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,l,d)},f=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==le&&e!==he));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==he&&e!==le));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var u=r.sortSatisfiedByIndex?5:0;return n(u),a}(0,0,m);(f>=c||t.index)&&(c=f,s=m)})),!s)throw E("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),fe=new Set(["$eq","$gt","$gte"]),pe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var u=Object.keys(c).filter((e=>fe.has(e)));if(u.length>1)return!1;var h=u[0];if(h&&s.add(o),"$eq"!==h){if(i.length>0)return!1;i.push(h)}}var l=[],d=new Set;for(var[m,f]of Object.entries(t)){if(!e.includes(m))return!1;var p=Object.keys(f).filter((e=>pe.has(e)));if(p.length>1)return!1;var v=p[0];if(v&&d.add(m),"$eq"!==v){if(l.length>0)return!1;l.push(v)}}var y=0;for(var g of e){for(var b of[s,d]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[y]!==a[y]&&s.size>0&&d.size>0)return!1;y++}return!0}var ye=r(744),ge=r(2779),be=r(1692),we=r(4903),De=r(7705),xe=r(2403),_e=r(6776),ke=r(6950),Ie=r(6823),Ee=!1;function Oe(e){return Ee||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:we.xF,$project:we.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:De.a6,$eq:xe.XV,$elemMatch:ke.Jy,$exists:Ie.P,$gt:xe.MR,$gte:xe.fy,$in:xe.oZ,$lt:xe.NV,$lte:xe.Q_,$ne:xe.C5,$nin:xe.GU,$mod:_e.Pp,$nor:De.q3,$not:De.En,$or:De.sU,$regex:_e.WP,$size:ke.Ig,$type:Ie.T}),Ee=!0),new be.X(e)}function Re(e,t){var r=B(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,u=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>u&&(u=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ce(e,t){if(!t.sort)throw E("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Se(e){return e===le?-1/0:e}function Pe(e,t,r){return e.includes(t)?r===he||!0===r?"1":"0":r}function $e(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ne(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=je(e.schema,t.query));var c=$e(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),u=s.index,h=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+u.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||h.push(n),s.sortSatisfiedByIndex&&h.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var l=Ce(e.schema,t.query);h=h.sort(l)}return{documents:h=h.slice(n,i)}}function Ae(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Te(e){return parseInt(e.split("-")[0],10)}function qe(e,t){var r=t?t._rev:null;return(r?Ae(r).height:0)+1+"-"+e}var Me="_rxdb_internal";async function Be(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Qe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:x.deepFreezeWhenDevMode(a),previousDocumentData:x.deepFreezeWhenDevMode(n)}}function Fe(e,t,r,a){if(a)throw 409===a.status?E("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?E("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function Ke(e){var t=s(e);return t._meta=s(e._meta),t}function Ze(e,t,r){x.deepFreezeWhenDevMode(r);var a=B(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),x.isDevMode()){i=M(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw E("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw E("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=qe(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,ue.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:qe(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,ue.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:T(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(3561),ze=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new ze.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,u=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ue.X)(o))};var h=r.close.bind(r);r.close=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),h()};var l=r.remove.bind(r);r.remove=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),l()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=B(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw E("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,u=[],h=[],l=[],d={id:P(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=d.events,f=[],p=[],v=[],y=r.size>0,g=a.length,b=function(){var e,n=a[w],d=n.document,g=n.previous,b=d[t],D=d._deleted,x=g&&g._deleted,_=void 0;if(y&&(_=r.get(b)),_){var k=_._rev;if(!g||g&&k!==g._rev){var I={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:_};return l.push(I),1}var O=c?We(n):n;c&&(D?g&&Object.keys(g._attachments).forEach((e=>{p.push({documentId:b,attachmentId:e,digest:(0,ue.ZN)(g)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:_,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=O.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else f.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?l.push(e):(c?(h.push(We(O)),s&&s(d)):(h.push(O),s&&s(d)),o=O);var R=null,C=null,j=null;if(x&&!D)j="INSERT",R=c?He(d):d;else if(!g||x||D){if(!D)throw E("SNH",{args:{writeRow:n}});j="DELETE",R=(0,ue.ZN)(d),C=g}else j="UPDATE",R=c?He(d):d,C=g;var S={documentId:b,documentData:R,previousDocumentData:C,operation:j};m.push(S)}else{var P=!!D;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?f.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},l.push(e))})),e||(c?(u.push(We(n)),i&&i(d)):(u.push(n),i&&i(d)),o=n),!P){var $={documentId:b,operation:"INSERT",documentData:c?He(d):d,previousDocumentData:c&&g?He(g):g};m.push($)}}},w=0;w{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,ue.ZN)(r)).eventBulk.events.length>0){var s=(0,ue.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ne(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=$e(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ne(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[K]:"++sequence, id",[Z]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[Z],booleanIndexes:se(n)}})();return z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw E("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw E("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw E("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=B(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw E("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=q(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),u(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),u(this,"defaultValues",e)}},{key:"hash",get:function(){return u(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}])}();function ut(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=Q(e);a=function(e){return o(e,!0)}(a),x.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ht=r(7708),lt=r(8146),dt=r(3356),mt=r(5520),ft=r(8609),pt=r(1753);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=$(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 ")}function yt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,ue.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=Ae(i._rev).height,n.forEach((e=>{var t=Ae(e._rev).height;t>s&&(i=e,s=t)})),i),u=o;for(var h of a)try{u=await h.modifier(c(u))}catch(l){h.reject(l),h.reject=()=>{},h.resolve=()=>{}}try{await this.preWrite(u,o)}catch(l){return void a.forEach((e=>e.reject(l)))}e.push({previous:o,document:u})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=R(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,ue.ZN)(o.documentInDb),(0,ue.ZN)(c).unshift(e)}))}else{var u=E("COL20",{name:C[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(u)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var wt={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.$.pipe((0,ht.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,lt.p)((e=>e.documentId===this.primary)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,ft.t)(ue.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(x.isDevMode()){if(e.includes(".item."))throw E("DOC1",{path:e});if(e===this.primaryPath)throw E("DOC2");if(this.collection.schema.finalFields.includes(e))throw E("DOC3",{path:e});if(!q(this.collection.schema.jsonSchema,e))throw E("DOC4",{path:e})}return this.$.pipe((0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=q(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return pt.$A;if(!t)throw E("DOC5",{path:e});if(!t.ref)throw E("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw E("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return x.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(N(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(N(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(N(e+"."+o))}return r.get(N(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return x.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,x.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw E("DOC11",{id:this.primary,document:this});await xt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Fe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(E("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Fe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw E("DOC14")}};function Dt(e){void 0===e&&(e=wt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function xt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),x.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var _t=r(2198),kt=r(511),It=r(4157),Et=r(2442),Ot=r(6114);function Rt(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Ct=new WeakMap;function jt(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Ct,e,(()=>{var t=e.collection,r=Re(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ce(t.schema.jsonSchema,r),i=je(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Rt(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,ue.ZN)(e._result).docsData.slice(0),n=(0,ue.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:x.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Ot.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Ot.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var St=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Pt(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function $t(e){return e.refCount$.observers.length}var Nt,At,Tt=(Nt=100,At=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Pt(t,e)))}}),qt=new WeakSet;var Mt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=yt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return u(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=x.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],u=Te(o._rev),h=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),l=h.byRev,d=l.get(u),m=d?d.deref():void 0;return m||(o=n(o),m=s(o),l.set(u,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,pt.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Te(e.revision)})})))}))))),m};return o}(this))}}])}();function Bt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Qt=function(){return(0,b.A)((function(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=Bt(this.collection._docCache,t)}),[{key:"docsData",get:function(){return u(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),u(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Qt(this.collection,e,e.length);this._result=t}else this._result=new Qt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw E("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,ue.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),u=await r.storageInstance.query(c);t=u.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw E("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Zt(this).then((()=>(0,kt._)(this.$))).then((t=>{if(!t&&e)throw E("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Re(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,dt.Z)(null),(0,Et.Z)((()=>Zt(this))),(0,ht.T)((()=>this._result)),(0,ft.t)(ue.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,ue.ZN)(t).time))),(0,lt.p)((e=>!!e)),(0,ht.T)((e=>{var t=(0,ue.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,It.h)(e,this.refCount$.pipe((0,lt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return u(this,"queryMatcher",je(0,Re(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}])}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,qt.has(i)||(qt.add(i),(0,pt.dY)().then((()=>(0,pt.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),qt.delete(i)}))),s}function Kt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Zt(e){return e.collection.database.destroyed||Kt(e)?pt.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||Kt(e))return pt.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,ue.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=jt(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var u=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!u.has(t)&&(u.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:x.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var h=o.map((e=>{var t=Ke(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=qe(r,e),{previous:e,document:t}}));await t.bulkWrite(h,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,lt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,wt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>Dt(sr(e))))}(e),e,x.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var ur=["pre","post"],hr=["insert","save","remove","create"],lr=!1,dr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===u&&(u=Tt),void 0===h&&(h={}),void 0===l&&(l=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new St,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=u,this.statics=h,this.conflictHandler=l,function(e){if(lr)return;lr=!0;var t=Object.getPrototypeOf(e);hr.forEach((e=>{ur.map((r=>{var a=r+$(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ze(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>xt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,lt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Et.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ht.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Mt(this.schema.primaryPath,this.$.pipe((0,lt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Qe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),pt.em},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration-schema")},t.getMigrationState=function(){throw vt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Fe(this,e[this.schema.primaryPath],e,r),(0,ue.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=Bt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),u=c.success.map((e=>e[t]));return await Promise.all(u.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:u.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw E("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,ue.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),u=await c.incrementalModify((()=>a));i.push(u)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Fe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw E("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=pt.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw E("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw O("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw E("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw O("COL7",{key:t,when:e});if(!ur.includes(e))throw O("COL8",{key:t,when:e});if(!hr.includes(t))throw E("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw E("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return pt.em;var i=n.series.map((e=>()=>e(r,a)));return(0,pt.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?pt.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,lt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,lt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,lt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}])}();var mr=r(7635),fr=r(1007);var pr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,fr.sc)(e))},vr=r(5525),yr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l,d){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,Et.Z)((e=>e.events))),this.storageToken=pt.Dr,this.storageTokenDocument=pt.Dr,this.emittedEventBulkIds=new vr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=u,this.cleanupPolicy=h,this.allowSlowCount=l,this.reactivity=d,"pseudoInstance"!==this.name&&(this.internalStore=Ze(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=P(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:T(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,ue.ZN)(n.error[0]);if(i.isError&&R(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,u=e.rxdbVersion,!c||u.includes("beta")&&u!==c||c.split(".")[0]!==u.split(".")[0])throw E("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw E("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,ue.ZN)(o)}var c,u;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw E("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await Be(this.internalStore,Gt(tr(e,t),zt));if(!r)throw E("SNH",{name:e,schema:t});var a=Ke(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,u=o.schema;t[c]=u;var h=ut(u,this.hashFunction);if(r[c]=h,this.collections[i])throw E("DB3",{name:i});var l=tr(i,u),d={id:Gt(l,zt),key:l,context:zt,data:{name:c,schemaHash:await h.hash,schema:h.jsonSchema,version:h.version,connectedStorages:[]},_deleted:!1,_meta:T(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:h,database:this}),f=s(o);f.database=this,f.name=i,st("preCreateRxCollection",f),m.conflictHandler=f.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw E("DB12",{database:this.name,writeError:e});var a=(0,ue.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw E("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,ue.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:u={},options:h={},localDocuments:l=!1,cacheReplacementPolicy:d=Tt,conflictHandler:m=cr}=e;var f={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:x.isDevMode()};return st("preCreateRxStorageInstance",f),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,f).then((e=>{var f=new dr(t,r,a,e,n,i,c,u,h,d,o,m);return f.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(f,t,{get:()=>r.bind(f)})}));var e=pt.em;return s&&0!==f.schema.version&&(e=f.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:f,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:u,options:h,cacheReplacementPolicy:d,localDocuments:l,statics:o}}),f))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.addState=function(e){throw vt("state")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration-schema")},t.destroy=async function(){return this.destroyed?pt.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?pt.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>yr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=P(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}])}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Me,schema:Jt,options:a,multiInstance:n,password:i,devMode:x.isDevMode()})}function wr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:u,allowSlowCount:h=!1,localDocuments:l=!1,hashFunction:d=pr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}),o||function(e,t){var r=t.name+"|"+e;if(yr.has(r))throw E("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),yr.add(t.name+"|"+a);var f=P(10);return br(f,t,a,r,i,n).catch((e=>{throw yr.delete(t.name+"|"+a),e})).then((e=>{var p=new gr(a,f,t,r,n,i,s,c,e,d,u,h,m);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}}).then((()=>p))}))}var Dr={RxSchema:ct.prototype,RxDocument:wt,RxQuery:Wt.prototype,RxCollection:dr.prototype,RxDatabase:gr.prototype},xr=new Set,_r=new Set;var kr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,w.A)(t,e),t}(Dt()),Ir={get isLocal(){return!0},get allAttachments$(){throw E("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(jr,this.parent);return this.parent.$.pipe((0,lt.p)((e=>e.documentId===this.primary)),(0,lt.p)((e=>e.isLocal)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((t=>e.docCache.getCachedRxDocument(t))),(0,ft.t)(ue.bz))},get $$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(jr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw O("LD2",{objPath:e});var t=v(this._data,e);return t=x.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,x.isDevMode()){if(e.includes(".item."))throw E("LD3",{objPath:e});if(e===this.primaryPath)throw E("LD4")}return this.$.pipe((0,ht.T)((e=>e._data)),(0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){return Rr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Pr(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Pr(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Pr(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:T(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Er=!1,Or=()=>{if(!Er){Er=!0;var e=wt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Ir,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Ir,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Ir[e]=(e=>()=>{throw E("LD6",{functionName:e})})(e)))}};function Rr(e){var t=e.parent;return t instanceof gr?t:t.database}var Cr=new WeakMap,jr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await $r(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ze(t,a,qr);var n=new Mt("id",e.$.pipe((0,lt.p)((e=>e.isLocal))),(t=>function(e,t){Or();var r=new kr(e.id,e,t);return Object.setPrototypeOf(r,Ir),r.prototype=Ir,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Qe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return jr.set(e,c),c})();Cr.set(e,a)}function Pr(e){var t=Cr.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw E("LD8",{database:r.name,collection:a})}return t}function $r(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Tr(a),schema:qr,options:n,multiInstance:i,devMode:x.isDevMode()})}function Nr(e){var t=Cr.get(e);if(t)return Cr.delete(e),t.then((e=>e.storageInstance.close()))}async function Ar(e,t,r){var a=P(10),n=await $r(a,e,t,r,{},!1);await n.remove()}function Tr(e){return"plugin-local-documents-"+e}var qr=Q({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Mr(e,t){var r=await Pr(this),a={id:e,data:t,_deleted:!1,_meta:T(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function Br(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Pr(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Be(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Qr(e){return this.$.pipe((0,dt.Z)(null),(0,Et.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Et.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,lt.p)((e=>e.use)),(0,ht.T)((e=>e.doc)))}var Fr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Mr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr},RxDatabase:e=>{e.insertLocal=Mr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>Nr(e)},postDestroyRxCollection:{after:e=>Nr(e)},postRemoveRxDatabase:{after:e=>Ar(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Ar(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function Kr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:xr}),!xr.has(e)){if(_r.has(e.name))throw E("PL3",{name:e.name,plugin:e});if(xr.add(e),_r.add(e.name),!e.rxdb)throw O("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(Dr[t])})),e.overwritable&&Object.assign(x,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Fr);var e;return await wr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Zr=["#e6008d","#8d2089","#5f2688"]},9891:(e,t,r)=>{r.r(t),r.d(t,{default:()=>h});var a=r(4586),n=r(1595),i=r(6540),s=r(2303),o=r(2658),c=r(4848);const u="premium_license_opened";function h(){const{siteConfig:e}=(0,a.A)(),t=(0,s.A)();(0,i.useEffect)((()=>{t&&(0,o.IA)()&&(async()=>{const e=await(0,o.C3)();if(await e.getLocal(u))console.log("# file opening already tracked");else{const t=new URLSearchParams(window.location.search).get("v"),r=t?parseInt(t,10):300;window.trigger(u,Math.floor(r/3)),await e.upsertLocal(u,{})}})()}));let r="https://rxdb.pipedrive.com/documents/p/";if(t){r+=new URLSearchParams(window.location.search).get("f")}return(0,c.jsx)(n.A,{title:`Chat - ${e.title}`,description:"License Preview",children:(0,c.jsx)("main",{children:(0,c.jsxs)("div",{className:"redirectBox",style:{textAlign:"center"},children:[(0,c.jsx)("a",{href:"/",children:(0,c.jsx)("div",{className:"logo",children:(0,c.jsx)("img",{src:"/files/logo/logo_text.svg",alt:"RxDB",width:160})})}),(0,c.jsx)("h1",{children:"RxDB License Preview"}),(0,c.jsx)("p",{children:(0,c.jsx)("b",{children:"You will be redirected in a few seconds."})}),(0,c.jsx)("p",{children:(0,c.jsx)("a",{href:r,children:"Click here to open the license agreement directly."})}),(0,c.jsx)("meta",{httpEquiv:"Refresh",content:"1; url="+r})]})})})}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>u,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>h,dY:()=>a,em:()=>o,h$:()=>l,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var u=o;function h(e){return void 0===e&&(e=void 0),u=u.then((()=>c(e)))}function l(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/db34d6b0.aa85a0ae.js b/docs/assets/js/db34d6b0.aa85a0ae.js deleted file mode 100644 index 5538bcdb12f..00000000000 --- a/docs/assets/js/db34d6b0.aa85a0ae.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[7320],{2658:(e,t,r)=>{r.d(t,{Tj:()=>Zr,C3:()=>Kr,IA:()=>Hr});var a=r(7329);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function u(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var h=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},l=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(l.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(l.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(l.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function f(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function p(e,t){if(f(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!h(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function _(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((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var k=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,D.A)(Error)),I=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=_(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,w.A)(t,e),t.prototype.toString=function(){return this.message},(0,b.A)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,D.A)(TypeError));function E(e,t){return new k(e,x.tunnelErrorMessage(e),t)}function O(e,t){return new I(e,x.tunnelErrorMessage(e),t)}function R(e){return!(!e||409!==e.status)&&e}var C={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var j=/\./g,S="abcdefghijklmnopqrstuvwxyz";function P(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw E("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function Q(e){var t=B((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=F,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=W(e);(0,g.Hb)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.k_)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var F={type:"object",properties:{lwt:{type:"number",minimum:A,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function W(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=B(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var H="docs",K="changes",Z="attachments",U="dexie",z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=v(t,e);y(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=B(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.$r)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.$r)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===q(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.jw)(r)):r}var oe=r(9092),ce=r(5734),ue=r(3337),he=String.fromCharCode(65535),le=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=q(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,u=!0,h=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:u?le:he,endKey:a?he:le,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=le),void 0===i.endKey&&(i.endKey=he),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),u&&!i.inclusiveStart&&(u=!1),a&&!i.inclusiveEnd&&(a=!1),i})),l=h.map((e=>e.startKey)),d=h.map((e=>e.endKey)),m={index:e,startKeys:l,endKeys:d,inclusiveEnd:a,inclusiveStart:u,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,l,d)},f=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.Sd)(r.startKeys,(e=>e!==le&&e!==he));n(s*i);var o=(0,g.Sd)(r.startKeys,(e=>e!==he&&e!==le));n(o*i);var c=(0,g.Sd)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var u=r.sortSatisfiedByIndex?5:0;return n(u),a}(0,0,m);(f>=c||t.index)&&(c=f,s=m)})),!s)throw E("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),fe=new Set(["$eq","$gt","$gte"]),pe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var u=Object.keys(c).filter((e=>fe.has(e)));if(u.length>1)return!1;var h=u[0];if(h&&s.add(o),"$eq"!==h){if(i.length>0)return!1;i.push(h)}}var l=[],d=new Set;for(var[m,f]of Object.entries(t)){if(!e.includes(m))return!1;var p=Object.keys(f).filter((e=>pe.has(e)));if(p.length>1)return!1;var v=p[0];if(v&&d.add(m),"$eq"!==v){if(l.length>0)return!1;l.push(v)}}var y=0;for(var g of e){for(var b of[s,d]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[y]!==a[y]&&s.size>0&&d.size>0)return!1;y++}return!0}var ye=r(744),ge=r(2779),be=r(1692),we=r(4903),De=r(7705),xe=r(2403),_e=r(6776),ke=r(6950),Ie=r(6823),Ee=!1;function Oe(e){return Ee||((0,ge.DZ)(ge.hu.PIPELINE,{$sort:we.xF,$project:we.C2}),(0,ge.DZ)(ge.hu.QUERY,{$and:De.a6,$eq:xe.XV,$elemMatch:ke.Jy,$exists:Ie.P,$gt:xe.MR,$gte:xe.fy,$in:xe.oZ,$lt:xe.NV,$lte:xe.Q_,$ne:xe.C5,$nin:xe.GU,$mod:_e.Pp,$nor:De.q3,$not:De.En,$or:De.sU,$regex:_e.WP,$size:ke.Ig,$type:Ie.T}),Ee=!0),new be.X(e)}function Re(e,t){var r=B(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.$r)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,u=-1;e.indexes.forEach((e=>{var t=(0,g.k_)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>u&&(u=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ce(e,t){if(!t.sort)throw E("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Se(e){return e===le?-1/0:e}function Pe(e,t,r){return e.includes(t)?r===he||!0===r?"1":"0":r}function $e(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Pe(e,n,r)})).map(Se);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Ne(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=je(e.schema,t.query));var c=$e(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),u=s.index,h=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+u.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||h.push(n),s.sortSatisfiedByIndex&&h.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var l=Ce(e.schema,t.query);h=h.sort(l)}return{documents:h=h.slice(n,i)}}function Ae(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Te(e){return parseInt(e.split("-")[0],10)}function qe(e,t){var r=t?t._rev:null;return(r?Ae(r).height:0)+1+"-"+e}var Me="_rxdb_internal";async function Be(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Qe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:x.deepFreezeWhenDevMode(a),previousDocumentData:x.deepFreezeWhenDevMode(n)}}function Fe(e,t,r,a){if(a)throw 409===a.status?E("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?E("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function We(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function Ke(e){var t=s(e);return t._meta=s(e._meta),t}function Ze(e,t,r){x.deepFreezeWhenDevMode(r);var a=B(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),x.isDevMode()){i=M(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw E("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw E("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.t)(),i._rev=qe(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,ue.ZN)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:qe(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.Hb)(a.error,e.error),(0,g.Hb)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,ue.ZN)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:T(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(3561),ze=r(703),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new ze.X2(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.B,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,u=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ue.X)(o))};var h=r.close.bind(r);r.close=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),h()};var l=r.remove.bind(r);r.remove=async function(){return c=!0,u.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),l()}}}var Ye=(0,ce.t)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.B,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=B(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw E("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,u=[],h=[],l=[],d={id:P(10),events:[],checkpoint:null,context:n,startTime:(0,ce.t)(),endTime:0},m=d.events,f=[],p=[],v=[],y=r.size>0,g=a.length,b=function(){var e,n=a[w],d=n.document,g=n.previous,b=d[t],D=d._deleted,x=g&&g._deleted,_=void 0;if(y&&(_=r.get(b)),_){var k=_._rev;if(!g||g&&k!==g._rev){var I={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:_};return l.push(I),1}var O=c?We(n):n;c&&(D?g&&Object.keys(g._attachments).forEach((e=>{p.push({documentId:b,attachmentId:e,digest:(0,ue.ZN)(g)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:_,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=O.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else f.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?l.push(e):(c?(h.push(We(O)),s&&s(d)):(h.push(O),s&&s(d)),o=O);var R=null,C=null,j=null;if(x&&!D)j="INSERT",R=c?He(d):d;else if(!g||x||D){if(!D)throw E("SNH",{args:{writeRow:n}});j="DELETE",R=(0,ue.ZN)(d),C=g}else j="UPDATE",R=c?He(d):d,C=g;var S={documentId:b,documentData:R,previousDocumentData:C,operation:j};m.push(S)}else{var P=!!D;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?f.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},l.push(e))})),e||(c?(u.push(We(n)),i&&i(d)):(u.push(n),i&&i(d)),o=n),!P){var $={documentId:b,operation:"INSERT",documentData:c?He(d):d,previousDocumentData:c&&g?He(g):g};m.push($)}}},w=0;w{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,ue.ZN)(r)).eventBulk.events.length>0){var s=(0,ue.ZN)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.t)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Ne(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=$e(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Ne(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.t)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.B},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.cf(o,e),i={[H]:ae(n),[K]:"++sequence, id",[Z]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[Z],booleanIndexes:se(n)}})();return z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.12.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw E("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw E("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw E("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.k_)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=B(this.jsonSchema.primaryKey),this.finalFields=W(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw E("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=q(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"$$",{get:function(){return this.get$$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),u(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.A)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),u(this,"defaultValues",e)}},{key:"hash",get:function(){return u(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function ut(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=Q(e);a=function(e){return o(e,!0)}(a),x.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ht=r(7708),lt=r(8146),dt=r(3356),mt=r(5520),ft=r(8609),pt=r(1753);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=$(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 ")}function yt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,ue.ZN)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=Ae(i._rev).height,n.forEach((e=>{var t=Ae(e._rev).height;t>s&&(i=e,s=t)})),i),u=o;for(var h of a)try{u=await h.modifier(c(u))}catch(l){h.reject(l),h.reject=()=>{},h.resolve=()=>{}}try{await this.preWrite(u,o)}catch(l){return void a.forEach((e=>e.reject(l)))}e.push({previous:o,document:u})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=R(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,ue.ZN)(o.documentInDb),(0,ue.ZN)(c).unshift(e)}))}else{var u=E("COL20",{name:C[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(u)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var wt={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.$.pipe((0,ht.T)((e=>e._data._deleted)))},get deleted$$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,lt.p)((e=>e.documentId===this.primary)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,ft.t)(ue.bz))},get $$(){var e=this;return e.collection.database.getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get$(e){if(x.isDevMode()){if(e.includes(".item."))throw E("DOC1",{path:e});if(e===this.primaryPath)throw E("DOC2");if(this.collection.schema.finalFields.includes(e))throw E("DOC3",{path:e});if(!q(this.collection.schema.jsonSchema,e))throw E("DOC4",{path:e})}return this.$.pipe((0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){var t=this.get$(e);return this.collection.database.getReactivityFactory().fromObservable(t,this.getLatest().get(e))},populate(e){var t=q(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return pt.$A;if(!t)throw E("DOC5",{path:e});if(!t.ref)throw E("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw E("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return x.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if(a.endsWith("$$")){var i=a.slice(0,-2);return r.get$$(N(e+"."+i))}if("$"===n){var s=a.slice(0,-1);return r.get$(N(e+"."+s))}if("_"===n){var o=a.slice(0,-1);return r.populate(N(e+"."+o))}return r.get(N(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return x.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,x.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw E("DOC11",{id:this.primary,document:this});await xt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return Fe(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(E("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return Fe(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw E("DOC14")}};function Dt(e){void 0===e&&(e=wt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function xt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),x.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var _t=r(2198),kt=r(511),It=r(4157),Et=r(2442),Ot=r(6114);function Rt(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Ct=new WeakMap;function jt(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Ct,e,(()=>{var t=e.collection,r=Re(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ce(t.schema.jsonSchema,r),i=je(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Rt(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,ue.ZN)(e._result).docsData.slice(0),n=(0,ue.ZN)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:x.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Ot.kC)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Ot.Cs)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var St=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Pt(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function $t(e){return e.refCount$.observers.length}var Nt,At,Tt=(Nt=100,At=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Pt(t,e)))}}),qt=new WeakSet;var Mt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=yt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.A)(e,[{key:"getCachedRxDocument",get:function(){return u(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=x.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],u=Te(o._rev),h=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),l=h.byRev,d=l.get(u),m=d?d.deref():void 0;return m||(o=n(o),m=s(o),l.set(u,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,pt.vN)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Te(e.revision)})})))}))))),m};return o}(this))}}]),e}();function Bt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Qt=function(){function e(e,t,r){this.time=(0,ce.t)(),this.collection=e,this.count=r,this.documents=Bt(this.collection._docCache,t)}return(0,b.A)(e,[{key:"docsData",get:function(){return u(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),u(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Qt(this.collection,e,e.length);this._result=t}else this._result=new Qt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.t)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw E("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,ue.ZN)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.Hb)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),u=await r.storageInstance.query(c);t=u.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.t)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw E("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Zt(this).then((()=>(0,kt._)(this.$))).then((t=>{if(!t&&e)throw E("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Re(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.A)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,lt.p)((e=>!e.isLocal)),(0,dt.Z)(null),(0,Et.Z)((()=>Zt(this))),(0,ht.T)((()=>this._result)),(0,ft.t)(ue.bz),(0,mt.F)(((e,t)=>!(!e||e.time!==(0,ue.ZN)(t).time))),(0,lt.p)((e=>!!e)),(0,ht.T)((e=>{var t=(0,ue.ZN)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,It.h)(e,this.refCount$.pipe((0,lt.p)((()=>!1))))}return this._$}},{key:"$$",get:function(){return this.collection.database.getReactivityFactory().fromObservable(this.$,void 0)}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return u(this,"queryMatcher",je(0,Re(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Ht(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Wt(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,qt.has(i)||(qt.add(i),(0,pt.dY)().then((()=>(0,pt.Ve)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),qt.delete(i)}))),s}function Kt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Zt(e){return e.collection.database.destroyed||Kt(e)?pt.Dr:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.t)(),e.collection.database.destroyed||Kt(e))return pt.Dr;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,ue.ZN)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=jt(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var u=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!u.has(t)&&(u.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:x.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var h=o.map((e=>{var t=Ke(e);return t._deleted=!0,t._meta.lwt=(0,ce.t)(),t._rev=qe(r,e),{previous:e,document:t}}));await t.bulkWrite(h,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,lt.p)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,wt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((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(){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))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>Dt(sr(e))))}(e),e,x.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var ur=["pre","post"],hr=["insert","save","remove","create"],lr=!1,dr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===u&&(u=Tt),void 0===h&&(h={}),void 0===l&&(l=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new St,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=u,this.statics=h,this.conflictHandler=l,function(e){if(lr)return;lr=!0;var t=Object.getPrototypeOf(e);hr.forEach((e=>{ur.map((r=>{var a=r+$(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ze(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>xt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,lt.p)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Et.Z)((e=>e.events))),this.checkpoint$=t.pipe((0,ht.T)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Mt(this.schema.primaryPath,this.$.pipe((0,lt.p)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Qe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),pt.em},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration-schema")},t.getMigrationState=function(){throw vt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return Fe(this,e[this.schema.primaryPath],e,r),(0,ue.ZN)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=Bt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),u=c.success.map((e=>e[t]));return await Promise.all(u.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:u.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw E("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,ue.ZN)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),u=await c.incrementalModify((()=>a));i.push(u)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return Fe(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw E("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=pt.em),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw E("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw O("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw E("QU6");(e=s(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw O("COL7",{key:t,when:e});if(!ur.includes(e))throw O("COL8",{key:t,when:e});if(!hr.includes(t))throw E("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw E("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return pt.em;var i=n.series.map((e=>()=>e(r,a)));return(0,pt.h$)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?pt.Dr:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.A)(e,[{key:"insert$",get:function(){return this.$.pipe((0,lt.p)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,lt.p)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,lt.p)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7635),fr=r(1007);var pr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,fr.sc)(e))},vr=r(5525),yr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,u,h,l,d){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.G,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.states={},this.eventBulks$=new oe.B,this.observable$=this.eventBulks$.pipe((0,Et.Z)((e=>e.events))),this.storageToken=pt.Dr,this.storageTokenDocument=pt.Dr,this.emittedEventBulkIds=new vr.p4(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=u,this.cleanupPolicy=h,this.allowSlowCount=l,this.reactivity=d,"pseudoInstance"!==this.name&&(this.internalStore=Ze(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=P(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:T(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,ue.ZN)(n.error[0]);if(i.isError&&R(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,u=e.rxdbVersion,!c||u.includes("beta")&&u!==c||c.split(".")[0]!==u.split(".")[0])throw E("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw E("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,ue.ZN)(o)}var c,u;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw E("DB14",{database:this.name});return this.reactivity},t.$emit=function(e){this.emittedEventBulkIds.has(e.id)||(this.emittedEventBulkIds.add(e.id),this.eventBulks$.next(e))},t.removeCollectionDoc=async function(e,t){var r=await Be(this.internalStore,Gt(tr(e,t),zt));if(!r)throw E("SNH",{name:e,schema:t});var a=Ke(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,u=o.schema;t[c]=u;var h=ut(u,this.hashFunction);if(r[c]=h,this.collections[i])throw E("DB3",{name:i});var l=tr(i,u),d={id:Gt(l,zt),key:l,context:zt,data:{name:c,schemaHash:await h.hash,schema:h.jsonSchema,version:h.version,connectedStorages:[]},_deleted:!1,_meta:T(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:h,database:this}),f=s(o);f.database=this,f.name=i,st("preCreateRxCollection",f),m.conflictHandler=f.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw E("DB12",{database:this.name,writeError:e});var a=(0,ue.ZN)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw E("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,ue.ZN)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:u={},options:h={},localDocuments:l=!1,cacheReplacementPolicy:d=Tt,conflictHandler:m=cr}=e;var f={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:x.isDevMode()};return st("preCreateRxStorageInstance",f),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,f).then((e=>{var f=new dr(t,r,a,e,n,i,c,u,h,d,o,m);return f.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(f,t,{get:()=>r.bind(f)})}));var e=pt.em;return s&&0!==f.schema.version&&(e=f.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:f,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:u,options:h,cacheReplacementPolicy:d,localDocuments:l,statics:o}}),f))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.addState=function(e){throw vt("state")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration-schema")},t.destroy=async function(){return this.destroyed?pt.Dr:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?pt.Dr:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>yr.delete(this.storage.name+"|"+this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=P(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.A)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Me,schema:Jt,options:a,multiInstance:n,password:i,devMode:x.isDevMode()})}function wr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:u,allowSlowCount:h=!1,localDocuments:l=!1,hashFunction:d=pr,reactivity:m}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}),o||function(e,t){var r=t.name+"|"+e;if(yr.has(r))throw E("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}(a,t),yr.add(t.name+"|"+a);var f=P(10);return br(f,t,a,r,i,n).catch((e=>{throw yr.delete(t.name+"|"+a),e})).then((e=>{var p=new gr(a,f,t,r,n,i,s,c,e,d,u,h,m);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:l}}).then((()=>p))}))}var Dr={RxSchema:ct.prototype,RxDocument:wt,RxQuery:Wt.prototype,RxCollection:dr.prototype,RxDatabase:gr.prototype},xr=new Set,_r=new Set;var kr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,w.A)(t,e),t}(Dt()),Ir={get isLocal(){return!0},get allAttachments$(){throw E("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(jr,this.parent);return this.parent.$.pipe((0,lt.p)((e=>e.documentId===this.primary)),(0,lt.p)((e=>e.isLocal)),(0,ht.T)((e=>yt(e))),(0,dt.Z)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.F)(((e,t)=>e._rev===t._rev)),(0,ht.T)((t=>e.docCache.getCachedRxDocument(t))),(0,ft.t)(ue.bz))},get $$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.$,e.getLatest()._data)},get deleted$$(){var e=this;return Rr(e).getReactivityFactory().fromObservable(e.deleted$,e.getLatest().deleted)},getLatest(){var e=n(jr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw O("LD2",{objPath:e});var t=v(this._data,e);return t=x.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,x.isDevMode()){if(e.includes(".item."))throw E("LD3",{objPath:e});if(e===this.primaryPath)throw E("LD4")}return this.$.pipe((0,ht.T)((e=>e._data)),(0,ht.T)((t=>v(t,e))),(0,mt.F)())},get$$(e){return Rr(this).getReactivityFactory().fromObservable(this.get$(e),this.getLatest().get(e))},async incrementalModify(e){var t=await Pr(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Pr(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Pr(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:T(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Er=!1,Or=()=>{if(!Er){Er=!0;var e=wt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Ir,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Ir,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Ir[e]=(e=>()=>{throw E("LD6",{functionName:e})})(e)))}};function Rr(e){var t=e.parent;return t instanceof gr?t:t.database}var Cr=new WeakMap,jr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await $r(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ze(t,a,qr);var n=new Mt("id",e.$.pipe((0,lt.p)((e=>e.isLocal))),(t=>function(e,t){Or();var r=new kr(e.id,e,t);return Object.setPrototypeOf(r,Ir),r.prototype=Ir,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>Qe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return jr.set(e,c),c})();Cr.set(e,a)}function Pr(e){var t=Cr.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw E("LD8",{database:r.name,collection:a})}return t}function $r(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Tr(a),schema:qr,options:n,multiInstance:i,devMode:x.isDevMode()})}function Nr(e){var t=Cr.get(e);if(t)return Cr.delete(e),t.then((e=>e.storageInstance.close()))}async function Ar(e,t,r){var a=P(10),n=await $r(a,e,t,r,{},!1);await n.remove()}function Tr(e){return"plugin-local-documents-"+e}var qr=Q({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Mr(e,t){var r=await Pr(this),a={id:e,data:t,_deleted:!1,_meta:T(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function Br(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Lr(e){var t=await Pr(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Be(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Qr(e){return this.$.pipe((0,dt.Z)(null),(0,Et.Z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Et.Z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,lt.p)((e=>e.use)),(0,ht.T)((e=>e.doc)))}var Fr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Mr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr},RxDatabase:e=>{e.insertLocal=Mr,e.upsertLocal=Br,e.getLocal=Lr,e.getLocal$=Qr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>Nr(e)},postDestroyRxCollection:{after:e=>Nr(e)},postRemoveRxDatabase:{after:e=>Ar(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Ar(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Hr(){return"undefined"!=typeof window&&window.indexedDB}function Kr(){return Wr||(Wr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:xr}),!xr.has(e)){if(_r.has(e.name))throw E("PL3",{name:e.name,plugin:e});if(xr.add(e),_r.add(e.name),!e.rxdb)throw O("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(Dr[t])})),e.overwritable&&Object.assign(x,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Fr);var e;return await wr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const Zr=["#e6008d","#8d2089","#5f2688"]},9891:(e,t,r)=>{r.r(t),r.d(t,{default:()=>h});var a=r(4586),n=r(1595),i=r(6540),s=r(2303),o=r(2658),c=r(4848);const u="premium_license_opened";function h(){const{siteConfig:e}=(0,a.A)(),t=(0,s.A)();(0,i.useEffect)((()=>{t&&(0,o.IA)()&&(async()=>{const e=await(0,o.C3)();if(await e.getLocal(u))console.log("# file opening already tracked");else{const t=new URLSearchParams(window.location.search).get("v"),r=t?parseInt(t,10):300;window.trigger(u,Math.floor(r/3)),await e.upsertLocal(u,{})}})()}));let r="https://rxdb.pipedrive.com/documents/p/";if(t){r+=new URLSearchParams(window.location.search).get("f")}return(0,c.jsx)(n.A,{title:`Chat - ${e.title}`,description:"License Preview",children:(0,c.jsx)("main",{children:(0,c.jsxs)("div",{className:"redirectBox",style:{textAlign:"center"},children:[(0,c.jsx)("a",{href:"/",children:(0,c.jsx)("div",{className:"logo",children:(0,c.jsx)("img",{src:"/files/logo/logo_text.svg",alt:"RxDB",width:160})})}),(0,c.jsx)("h1",{children:"RxDB License Preview"}),(0,c.jsx)("p",{children:(0,c.jsx)("b",{children:"You will be redirected in a few seconds."})}),(0,c.jsx)("p",{children:(0,c.jsx)("a",{href:r,children:"Click here to open the license agreement directly."})}),(0,c.jsx)("meta",{httpEquiv:"Refresh",content:"1; url="+r})]})})})}},7810:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;an,Hb:()=>c,S7:()=>s,Sd:()=>o,dG:()=>a,jw:()=>u,k_:()=>i})},3337:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{ZN:()=>a,bz:()=>n});var n={bufferSize:1,refCount:!0}},1753:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$A:()=>s,Dr:()=>i,ND:()=>n,Ve:()=>h,dY:()=>a,em:()=>o,h$:()=>l,vN:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var u=o;function h(e){return void 0===e&&(e=void 0),u=u.then((()=>c(e)))}function l(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},5734:(e,t,r)=>{r.d(t,{t:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/main.eb882518.js b/docs/assets/js/main.095228e9.js similarity index 99% rename from docs/assets/js/main.eb882518.js rename to docs/assets/js/main.095228e9.js index 133a18f9c10..bb41f06a764 100644 --- a/docs/assets/js/main.eb882518.js +++ b/docs/assets/js/main.095228e9.js @@ -1,2 +1,2 @@ -/*! For license information please see main.eb882518.js.LICENSE.txt */ -(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[8792],{8328:(e,t,n)=>{"use strict";n.d(t,{A:()=>p});n(6540);var r=n(3259),a=n.n(r),o=n(4054);const i={"0027230a":[()=>n.e(8382).then(n.bind(n,2081)),"@site/docs/rx-storage-lokijs.md",2081],"01684a0a":[()=>n.e(6616).then(n.bind(n,3395)),"@site/docs/rx-storage-memory-synced.md",3395],"03e37916":[()=>n.e(6465).then(n.bind(n,3184)),"@site/docs/transactions-conflicts-revisions.md",3184],"045bd6f5":[()=>n.e(4475).then(n.bind(n,8201)),"@site/docs/encryption.md",8201],"04b0214f":[()=>n.e(6264).then(n.t.bind(n,4061,19)),"/home/runner/work/rxdb/rxdb/docs-src/.docusaurus/docusaurus-plugin-content-pages/default/plugin-route-context-module-100.json",4061],"0e268d20":[()=>Promise.all([n.e(5106),n.e(2584)]).then(n.bind(n,5607)),"@site/src/pages/premium.tsx",5607],"0e945c41":[()=>n.e(9796).then(n.bind(n,9722)),"@site/docs/replication-server.md",9722],"0f6e10f0":[()=>n.e(1475).then(n.bind(n,654)),"@site/docs/articles/progressive-web-app-database.md",654],"118cde4c":[()=>n.e(5272).then(n.bind(n,7245)),"@site/docs/replication-couchdb.md",7245],"14d72841":[()=>n.e(9772).then(n.bind(n,5221)),"@site/src/pages/newsletter.tsx",5221],17896441:[()=>Promise.all([n.e(1869),n.e(1968),n.e(8401)]).then(n.bind(n,242)),"@theme/DocItem",242],"187b985e":[()=>n.e(6866).then(n.bind(n,844)),"@site/docs/replication-webrtc.md",844],"1b0f8c91":[()=>n.e(3129).then(n.bind(n,9642)),"@site/docs/backup.md",9642],"1b238727":[()=>n.e(4013).then(n.bind(n,3721)),"@site/docs/rx-storage-performance.md",3721],"1c0701dd":[()=>n.e(6953).then(n.bind(n,668)),"@site/docs/middleware.md",668],"1da545ff":[()=>n.e(9743).then(n.bind(n,2678)),"@site/docs/releases/9.0.0.md",2678],"1df93b7f":[()=>Promise.all([n.e(1869),n.e(5106),n.e(9425),n.e(4583)]).then(n.bind(n,6866)),"@site/src/pages/index.tsx",6866],"1e0353aa":[()=>n.e(8588).then(n.bind(n,142)),"@site/docs/rx-storage.md",142],"1f391b9e":[()=>Promise.all([n.e(1869),n.e(1968),n.e(6061)]).then(n.bind(n,7973)),"@theme/MDXPage",7973],"21fa2740":[()=>n.e(5694).then(n.bind(n,763)),"@site/docs/releases/15.0.0.md",763],"2456d5e0":[()=>n.e(2966).then(n.bind(n,5654)),"@site/docs/rx-database.md",5654],"25626d15":[()=>n.e(268).then(n.bind(n,7258)),"@site/src/pages/chat.tsx",7258],"2564bf4f":[()=>n.e(6724).then(n.bind(n,5705)),"@site/docs/rxdb-tradeoffs.md",5705],"25a43fd4":[()=>n.e(4812).then(n.bind(n,3917)),"@site/docs/rx-storage-shared-worker.md",3917],"26b8a621":[()=>n.e(2055).then(n.bind(n,3439)),"@site/docs/replication-p2p.md",3439],"280a2389":[()=>Promise.all([n.e(5106),n.e(176)]).then(n.bind(n,8141)),"@site/src/pages/meeting.tsx",8141],"294ac9d5":[()=>n.e(8744).then(n.bind(n,958)),"@site/docs/plugins.md",958],"2efd0200":[()=>n.e(4132).then(n.bind(n,9839)),"@site/docs/tutorials/typescript.md",9839],"32667c41":[()=>n.e(8191).then(n.bind(n,6895)),"@site/docs/nosql-performance-tips.md",6895],"326aca46":[()=>n.e(4853).then(n.bind(n,3142)),"@site/docs/offline-first.md",3142],"34f94d1b":[()=>n.e(5832).then(n.bind(n,7746)),"@site/docs/electron-database.md",7746],36715375:[()=>n.e(2076).then(n.bind(n,2323)),"@site/src/pages/code.tsx",2323],"380cc66a":[()=>n.e(2061).then(n.bind(n,5668)),"@site/docs/rx-storage-dexie.md",5668],"38bbf12a":[()=>n.e(2078).then(n.bind(n,3762)),"@site/docs/articles/data-base.md",3762],"393be207":[()=>n.e(4134).then(n.bind(n,6602)),"@site/src/pages/markdown-page.md",6602],"39600c95":[()=>n.e(3148).then(n.bind(n,755)),"@site/docs/rx-query.md",755],"401008a8":[()=>n.e(5219).then(n.bind(n,6805)),"@site/docs/nodejs-database.md",6805],"41f941a1":[()=>n.e(5966).then(n.bind(n,3057)),"@site/docs/leader-election.md",3057],"432b83f9":[()=>n.e(4424).then(n.bind(n,9429)),"@site/docs/releases/8.0.0.md",9429],"4616b86a":[()=>n.e(465).then(n.bind(n,81)),"@site/docs/rx-storage-mongodb.md",81],"4777fd9a":[()=>n.e(6386).then(n.bind(n,1600)),"@site/docs/alternatives.md",1600],"4adf80bb":[()=>n.e(9548).then(n.bind(n,4442)),"@site/docs/rx-storage-pouchdb.md",4442],"4af60d2e":[()=>n.e(8545).then(n.bind(n,9249)),"@site/docs/articles/realtime-database.md",9249],"4ba7e5a3":[()=>n.e(9591).then(n.bind(n,6467)),"@site/docs/contribute.md",6467],"4ed9495b":[()=>n.e(1199).then(n.bind(n,1787)),"@site/docs/rx-storage-sqlite.md",1787],"502d8946":[()=>n.e(7817).then(n.bind(n,732)),"@site/src/pages/legal-notice.tsx",732],"51014a8a":[()=>n.e(9460).then(n.bind(n,262)),"@site/docs/articles/websockets-sse-polling-webrtc-webtransport.md",262],51334108:[()=>n.e(8926).then(n.bind(n,2644)),"@site/docs/articles/mobile-database.md",2644],"55a5b596":[()=>n.e(6717).then(n.bind(n,5536)),"@site/docs/rx-schema.md",5536],"5a273530":[()=>n.e(3881).then(n.bind(n,7589)),"@site/docs/rx-storage-remote.md",7589],"5e95c892":[()=>n.e(9647).then(n.bind(n,7121)),"@theme/DocsRoot",7121],"5e9f5e1a":[()=>Promise.resolve().then(n.bind(n,4784)),"@generated/docusaurus.config",4784],"60c23941":[()=>n.e(2915).then(n.t.bind(n,1966,19)),"/home/runner/work/rxdb/rxdb/docs-src/.docusaurus/docusaurus-plugin-content-docs/default/plugin-route-context-module-100.json",1966],"6187b59a":[()=>n.e(5866).then(n.bind(n,7409)),"@site/docs/rx-storage-worker.md",7409],"68a466be":[()=>n.e(3997).then(n.bind(n,3923)),"@site/docs/downsides-of-offline-first.md",3923],"6ae3580c":[()=>n.e(5320).then(n.bind(n,5376)),"@site/docs/replication.md",5376],"6bfb0089":[()=>n.e(6422).then(n.bind(n,300)),"@site/docs/adapters.md",300],"6cbff7c2":[()=>n.e(7408).then(n.bind(n,5943)),"@site/docs/rx-storage-opfs.md",5943],"6fd28feb":[()=>n.e(4618).then(n.bind(n,9408)),"@site/docs/rx-storage-foundationdb.md",9408],"714575d7":[()=>n.e(3185).then(n.bind(n,4880)),"@site/docs/rx-local-document.md",4880],"77d975e6":[()=>n.e(3949).then(n.bind(n,5707)),"@site/docs/articles/in-memory-nosql-database.md",5707],"7815dd0c":[()=>n.e(5335).then(n.bind(n,5515)),"@site/docs/population.md",5515],"7f02c700":[()=>n.e(9592).then(n.bind(n,9640)),"@site/docs/replication-firestore.md",9640],"8070e160":[()=>n.e(3822).then(n.bind(n,1685)),"@site/docs/quickstart.md",1685],"8288c265":[()=>n.e(9881).then(n.bind(n,1839)),"@site/docs/releases/11.0.0.md",1839],"84a3af36":[()=>n.e(6861).then(n.bind(n,8160)),"@site/docs/articles/json-database.md",8160],"84ae55a4":[()=>n.e(588).then(n.bind(n,2045)),"@site/docs/replication-nats.md",2045],"86b4e356":[()=>n.e(2786).then(n.bind(n,9278)),"@site/docs/orm.md",9278],"8aa53ed7":[()=>n.e(6723).then(n.bind(n,5870)),"@site/docs/articles/angular-database.md",5870],"8b0a0922":[()=>n.e(4557).then(n.bind(n,767)),"@site/docs/slow-indexeddb.md",767],"8bc07e20":[()=>n.e(1850).then(n.bind(n,5054)),"@site/docs/capacitor-database.md",5054],"91b454ee":[()=>n.e(4202).then(n.bind(n,9107)),"@site/docs/rx-storage-sharding.md",9107],"924d6dd6":[()=>n.e(5122).then(n.bind(n,2414)),"@site/docs/electron.md",2414],"92698a99":[()=>n.e(4166).then(n.bind(n,8568)),"@site/docs/rx-storage-indexeddb.md",8568],"931f4566":[()=>n.e(3595).then(n.bind(n,2439)),"@site/docs/schema-validation.md",2439],"935f2afb":[()=>n.e(8581).then(n.t.bind(n,5610,19)),"~docs/default/version-current-metadata-prop-751.json",5610],98405524:[()=>n.e(5504).then(n.bind(n,1934)),"@site/src/pages/survey.tsx",1934],"9dd8ea89":[()=>n.e(1715).then(n.bind(n,7919)),"@site/docs/logger.md",7919],"9e91b6f0":[()=>n.e(3021).then(n.bind(n,1844)),"@site/docs/why-nosql.md",1844],a406dc27:[()=>n.e(1500).then(n.bind(n,8306)),"@site/docs/migration-storage.md",8306],a442adcd:[()=>n.e(8760).then(n.bind(n,188)),"@site/docs/reactivity.md",188],a574e172:[()=>n.e(7149).then(n.bind(n,9329)),"@site/docs/replication-http.md",9329],a69eebfc:[()=>n.e(9408).then(n.bind(n,4120)),"@site/docs/query-optimizer.md",4120],a7bd4aaa:[()=>n.e(7098).then(n.bind(n,4532)),"@theme/DocVersionRoot",4532],a7f10198:[()=>n.e(1098).then(n.bind(n,769)),"@site/docs/data-migration.md",769],a94703ab:[()=>Promise.all([n.e(1869),n.e(9048)]).then(n.bind(n,2559)),"@theme/DocRoot",2559],aa14e6b1:[()=>n.e(9824).then(n.bind(n,3268)),"@site/docs/replication-graphql.md",3268],ab919a1f:[()=>n.e(6491).then(n.bind(n,4760)),"@site/docs/articles/embedded-database.md",4760],ac62b32d:[()=>n.e(9192).then(n.bind(n,9585)),"@site/docs/replication-websocket.md",9585],ad16b3ea:[()=>n.e(8674).then(n.bind(n,2462)),"@site/docs/dev-mode.md",2462],b0889a22:[()=>n.e(1107).then(n.bind(n,1798)),"@site/docs/cleanup.md",1798],b30f4f1f:[()=>n.e(3779).then(n.bind(n,5830)),"@site/docs/rx-attachment.md",5830],b8c49ce4:[()=>n.e(6355).then(n.bind(n,1605)),"@site/docs/releases/13.0.0.md",1605],badcd764:[()=>n.e(8318).then(n.bind(n,6042)),"@site/docs/articles/flutter-database.md",6042],c3bc9c50:[()=>n.e(9167).then(n.bind(n,4337)),"@site/docs/articles/react-database.md",4337],c44853e1:[()=>n.e(6584).then(n.bind(n,7390)),"@site/docs/rx-state.md",7390],c4de80f8:[()=>n.e(2777).then(n.bind(n,1173)),"@site/docs/install.md",1173],c6349bb6:[()=>n.e(5740).then(n.bind(n,2964)),"@site/docs/releases/14.0.0.md",2964],c6fdd490:[()=>n.e(4141).then(n.bind(n,5008)),"@site/docs/rx-server-scaling.md",5008],c843a053:[()=>n.e(9146).then(n.bind(n,8723)),"@site/docs/third-party-plugins.md",8723],c9c8e0b6:[()=>n.e(7249).then(n.bind(n,7674)),"@site/docs/articles/ionic-database.md",7674],cbbe8f0a:[()=>n.e(3852).then(n.bind(n,8783)),"@site/docs/rx-collection.md",8783],cde77f4f:[()=>Promise.all([n.e(5106),n.e(6287)]).then(n.bind(n,6465)),"@site/src/pages/premium-submitted.tsx",6465],d20e74b4:[()=>n.e(5123).then(n.bind(n,2853)),"@site/docs/crdt.md",2853],d2758528:[()=>n.e(2586).then(n.bind(n,7108)),"@site/docs/articles/browser-storage.md",7108],d4da9db3:[()=>n.e(1400).then(n.bind(n,4228)),"@site/docs/rx-storage-memory.md",4228],d622bd51:[()=>n.e(2845).then(n.bind(n,9804)),"@site/docs/migration-schema.md",9804],db34d6b0:[()=>Promise.all([n.e(5106),n.e(7320)]).then(n.bind(n,9891)),"@site/src/pages/license.tsx",9891],dbde2ffe:[()=>n.e(6543).then(n.bind(n,118)),"@site/docs/rx-document.md",118],dc42ba65:[()=>n.e(4962).then(n.bind(n,4494)),"@site/docs/key-compression.md",4494],e24529eb:[()=>n.e(6797).then(n.bind(n,9263)),"@site/docs/rx-storage-localstorage-meta-optimizer.md",9263],e6b4453d:[()=>n.e(2360).then(n.bind(n,9133)),"@site/docs/query-cache.md",9133],e7478ff0:[()=>n.e(5416).then(n.bind(n,1873)),"@site/docs/questions-answers.md",1873],eadd9b3c:[()=>n.e(4886).then(n.bind(n,8041)),"@site/docs/rx-storage-filesystem-node.md",8041],ebace26e:[()=>n.e(4028).then(n.bind(n,7016)),"@site/docs/releases/10.0.0.md",7016],ec526260:[()=>n.e(7396).then(n.bind(n,9592)),"@site/docs/articles/browser-database.md",9592],ed2d6610:[()=>n.e(3469).then(n.bind(n,9222)),"@site/docs/releases/12.0.0.md",9222],ee1b9f21:[()=>n.e(6998).then(n.bind(n,3179)),"@site/docs/react-native-database.md",3179],f15938da:[()=>n.e(4630).then(n.bind(n,5674)),"@site/docs/articles/localstorage.md",5674],f43e80a8:[()=>n.e(1558).then(n.bind(n,9544)),"@site/docs/rx-server.md",9544],f44bb875:[()=>n.e(561).then(n.bind(n,46)),"@site/docs/articles/frontend-database.md",46],fe7a07ee:[()=>n.e(2085).then(n.bind(n,9378)),"@site/docs/rx-storage-denokv.md",9378]};var l=n(4848);function s(e){let{error:t,retry:n,pastDelay:r}=e;return t?(0,l.jsxs)("div",{style:{textAlign:"center",color:"#fff",backgroundColor:"#fa383e",borderColor:"#fa383e",borderStyle:"solid",borderRadius:"0.25rem",borderWidth:"1px",boxSizing:"border-box",display:"block",padding:"1rem",flex:"0 0 50%",marginLeft:"25%",marginRight:"25%",marginTop:"5rem",maxWidth:"50%",width:"100%"},children:[(0,l.jsx)("p",{children:String(t)}),(0,l.jsx)("div",{children:(0,l.jsx)("button",{type:"button",onClick:n,children:"Retry"})})]}):r?(0,l.jsx)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:(0,l.jsx)("svg",{id:"loader",style:{width:128,height:110,position:"absolute",top:"calc(100vh - 64%)"},viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",stroke:"#61dafb",children:(0,l.jsxs)("g",{fill:"none",fillRule:"evenodd",transform:"translate(1 1)",strokeWidth:"2",children:[(0,l.jsxs)("circle",{cx:"22",cy:"22",r:"6",strokeOpacity:"0",children:[(0,l.jsx)("animate",{attributeName:"r",begin:"1.5s",dur:"3s",values:"6;22",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-opacity",begin:"1.5s",dur:"3s",values:"1;0",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-width",begin:"1.5s",dur:"3s",values:"2;0",calcMode:"linear",repeatCount:"indefinite"})]}),(0,l.jsxs)("circle",{cx:"22",cy:"22",r:"6",strokeOpacity:"0",children:[(0,l.jsx)("animate",{attributeName:"r",begin:"3s",dur:"3s",values:"6;22",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-opacity",begin:"3s",dur:"3s",values:"1;0",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-width",begin:"3s",dur:"3s",values:"2;0",calcMode:"linear",repeatCount:"indefinite"})]}),(0,l.jsx)("circle",{cx:"22",cy:"22",r:"8",children:(0,l.jsx)("animate",{attributeName:"r",begin:"0s",dur:"1.5s",values:"6;1;2;3;4;5;6",calcMode:"linear",repeatCount:"indefinite"})})]})})}):null}var c=n(6921),u=n(3102);function d(e,t){if("*"===e)return a()({loading:s,loader:()=>n.e(9293).then(n.bind(n,9293)),modules:["@theme/NotFound"],webpack:()=>[9293],render(e,t){const n=e.default;return(0,l.jsx)(u.W,{value:{plugin:{name:"native",id:"default"}},children:(0,l.jsx)(n,{...t})})}});const r=o[`${e}-${t}`],d={},p=[],f=[],m=(0,c.A)(r);return Object.entries(m).forEach((e=>{let[t,n]=e;const r=i[n];r&&(d[t]=r[0],p.push(r[1]),f.push(r[2]))})),a().Map({loading:s,loader:d,modules:p,webpack:()=>f,render(t,n){const a=JSON.parse(JSON.stringify(r));Object.entries(t).forEach((t=>{let[n,r]=t;const o=r.default;if(!o)throw new Error(`The page component at ${e} doesn't have a default export. This makes it impossible to render anything. Consider default-exporting a React component.`);"object"!=typeof o&&"function"!=typeof o||Object.keys(r).filter((e=>"default"!==e)).forEach((e=>{o[e]=r[e]}));let i=a;const l=n.split(".");l.slice(0,-1).forEach((e=>{i=i[e]})),i[l[l.length-1]]=o}));const o=a.__comp;delete a.__comp;const i=a.__context;return delete a.__context,(0,l.jsx)(u.W,{value:i,children:(0,l.jsx)(o,{...a,...n})})}})}const p=[{path:"/chat",component:d("/chat","fd7"),exact:!0},{path:"/code",component:d("/code","8ef"),exact:!0},{path:"/legal-notice",component:d("/legal-notice","cfc"),exact:!0},{path:"/license",component:d("/license","d06"),exact:!0},{path:"/markdown-page",component:d("/markdown-page","784"),exact:!0},{path:"/meeting",component:d("/meeting","6b0"),exact:!0},{path:"/newsletter",component:d("/newsletter","d15"),exact:!0},{path:"/premium",component:d("/premium","d94"),exact:!0},{path:"/premium-submitted",component:d("/premium-submitted","714"),exact:!0},{path:"/survey",component:d("/survey","9e0"),exact:!0},{path:"/",component:d("/","d82"),exact:!0},{path:"/",component:d("/","d17"),routes:[{path:"/",component:d("/","ce1"),routes:[{path:"/",component:d("/","d81"),routes:[{path:"/adapters.html",component:d("/adapters.html","fb4"),exact:!0},{path:"/alternatives.html",component:d("/alternatives.html","d53"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/angular-database.html",component:d("/articles/angular-database.html","e30"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/browser-database.html",component:d("/articles/browser-database.html","b0a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/browser-storage.html",component:d("/articles/browser-storage.html","286"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/data-base.html",component:d("/articles/data-base.html","797"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/embedded-database.html",component:d("/articles/embedded-database.html","596"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/flutter-database.html",component:d("/articles/flutter-database.html","f8a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/frontend-database.html",component:d("/articles/frontend-database.html","a83"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/in-memory-nosql-database.html",component:d("/articles/in-memory-nosql-database.html","ead"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/ionic-database.html",component:d("/articles/ionic-database.html","df6"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/json-database.html",component:d("/articles/json-database.html","bff"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/localstorage.html",component:d("/articles/localstorage.html","b1b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/mobile-database.html",component:d("/articles/mobile-database.html","1d7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/progressive-web-app-database.html",component:d("/articles/progressive-web-app-database.html","862"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/react-database.html",component:d("/articles/react-database.html","179"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/realtime-database.html",component:d("/articles/realtime-database.html","bc3"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/websockets-sse-polling-webrtc-webtransport.html",component:d("/articles/websockets-sse-polling-webrtc-webtransport.html","864"),exact:!0,sidebar:"tutorialSidebar"},{path:"/backup.html",component:d("/backup.html","123"),exact:!0,sidebar:"tutorialSidebar"},{path:"/capacitor-database.html",component:d("/capacitor-database.html","71f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/cleanup.html",component:d("/cleanup.html","d7f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/contribution.html",component:d("/contribution.html","129"),exact:!0,sidebar:"tutorialSidebar"},{path:"/crdt.html",component:d("/crdt.html","c69"),exact:!0,sidebar:"tutorialSidebar"},{path:"/data-migration",component:d("/data-migration","7c7"),exact:!0},{path:"/dev-mode.html",component:d("/dev-mode.html","11d"),exact:!0,sidebar:"tutorialSidebar"},{path:"/downsides-of-offline-first.html",component:d("/downsides-of-offline-first.html","ba4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/electron-database.html",component:d("/electron-database.html","44e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/electron.html",component:d("/electron.html","693"),exact:!0,sidebar:"tutorialSidebar"},{path:"/encryption.html",component:d("/encryption.html","265"),exact:!0,sidebar:"tutorialSidebar"},{path:"/install.html",component:d("/install.html","9ec"),exact:!0,sidebar:"tutorialSidebar"},{path:"/key-compression.html",component:d("/key-compression.html","171"),exact:!0,sidebar:"tutorialSidebar"},{path:"/leader-election.html",component:d("/leader-election.html","9aa"),exact:!0,sidebar:"tutorialSidebar"},{path:"/logger.html",component:d("/logger.html","949"),exact:!0,sidebar:"tutorialSidebar"},{path:"/middleware.html",component:d("/middleware.html","34f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/migration-schema.html",component:d("/migration-schema.html","618"),exact:!0,sidebar:"tutorialSidebar"},{path:"/migration-storage.html",component:d("/migration-storage.html","34a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/nodejs-database.html",component:d("/nodejs-database.html","6a2"),exact:!0,sidebar:"tutorialSidebar"},{path:"/nosql-performance-tips.html",component:d("/nosql-performance-tips.html","fd8"),exact:!0,sidebar:"tutorialSidebar"},{path:"/offline-first.html",component:d("/offline-first.html","e1b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/orm.html",component:d("/orm.html","798"),exact:!0,sidebar:"tutorialSidebar"},{path:"/plugins.html",component:d("/plugins.html","f25"),exact:!0,sidebar:"tutorialSidebar"},{path:"/population.html",component:d("/population.html","b89"),exact:!0,sidebar:"tutorialSidebar"},{path:"/query-cache.html",component:d("/query-cache.html","45f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/query-optimizer.html",component:d("/query-optimizer.html","bd3"),exact:!0,sidebar:"tutorialSidebar"},{path:"/questions-answers.html",component:d("/questions-answers.html","840"),exact:!0,sidebar:"tutorialSidebar"},{path:"/quickstart.html",component:d("/quickstart.html","417"),exact:!0,sidebar:"tutorialSidebar"},{path:"/react-native-database.html",component:d("/react-native-database.html","7b4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/reactivity.html",component:d("/reactivity.html","4d4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/10.0.0.html",component:d("/releases/10.0.0.html","8ce"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/11.0.0.html",component:d("/releases/11.0.0.html","712"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/12.0.0.html",component:d("/releases/12.0.0.html","a36"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/13.0.0.html",component:d("/releases/13.0.0.html","605"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/14.0.0.html",component:d("/releases/14.0.0.html","14c"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/15.0.0.html",component:d("/releases/15.0.0.html","4dd"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/8.0.0.html",component:d("/releases/8.0.0.html","fdc"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/9.0.0.html",component:d("/releases/9.0.0.html","f4b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-couchdb.html",component:d("/replication-couchdb.html","6d5"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-firestore.html",component:d("/replication-firestore.html","bcb"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-graphql.html",component:d("/replication-graphql.html","a6c"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-http.html",component:d("/replication-http.html","16a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-nats.html",component:d("/replication-nats.html","ac4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-p2p.html",component:d("/replication-p2p.html","ec6"),exact:!0},{path:"/replication-server",component:d("/replication-server","aa6"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-webrtc.html",component:d("/replication-webrtc.html","ff6"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-websocket.html",component:d("/replication-websocket.html","4f9"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication.html",component:d("/replication.html","62b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-attachment.html",component:d("/rx-attachment.html","7d7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-collection.html",component:d("/rx-collection.html","7dc"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-database.html",component:d("/rx-database.html","e4e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-document.html",component:d("/rx-document.html","e09"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-local-document.html",component:d("/rx-local-document.html","0db"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-query.html",component:d("/rx-query.html","2cf"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-schema.html",component:d("/rx-schema.html","671"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-server-scaling.html",component:d("/rx-server-scaling.html","da1"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-server.html",component:d("/rx-server.html","ed5"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-state.html",component:d("/rx-state.html","198"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-denokv.html",component:d("/rx-storage-denokv.html","b6e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-dexie.html",component:d("/rx-storage-dexie.html","bb3"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-filesystem-node.html",component:d("/rx-storage-filesystem-node.html","a57"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-foundationdb.html",component:d("/rx-storage-foundationdb.html","3c8"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-indexeddb.html",component:d("/rx-storage-indexeddb.html","631"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-localstorage-meta-optimizer.html",component:d("/rx-storage-localstorage-meta-optimizer.html","064"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-lokijs.html",component:d("/rx-storage-lokijs.html","1be"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-memory-synced.html",component:d("/rx-storage-memory-synced.html","65f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-memory.html",component:d("/rx-storage-memory.html","c21"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-mongodb.html",component:d("/rx-storage-mongodb.html","5ad"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-opfs.html",component:d("/rx-storage-opfs.html","6f7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-performance.html",component:d("/rx-storage-performance.html","b12"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-pouchdb.html",component:d("/rx-storage-pouchdb.html","d82"),exact:!0},{path:"/rx-storage-remote.html",component:d("/rx-storage-remote.html","5df"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-sharding.html",component:d("/rx-storage-sharding.html","b30"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-shared-worker.html",component:d("/rx-storage-shared-worker.html","0f4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-sqlite.html",component:d("/rx-storage-sqlite.html","ad7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-worker.html",component:d("/rx-storage-worker.html","a4e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage.html",component:d("/rx-storage.html","144"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rxdb-tradeoffs.html",component:d("/rxdb-tradeoffs.html","5cb"),exact:!0},{path:"/schema-validation.html",component:d("/schema-validation.html","3f1"),exact:!0},{path:"/slow-indexeddb.html",component:d("/slow-indexeddb.html","a40"),exact:!0,sidebar:"tutorialSidebar"},{path:"/third-party-plugins.html",component:d("/third-party-plugins.html","549"),exact:!0,sidebar:"tutorialSidebar"},{path:"/transactions-conflicts-revisions.html",component:d("/transactions-conflicts-revisions.html","53a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/tutorials/typescript.html",component:d("/tutorials/typescript.html","a33"),exact:!0,sidebar:"tutorialSidebar"},{path:"/why-nosql.html",component:d("/why-nosql.html","ad0"),exact:!0,sidebar:"tutorialSidebar"}]}]}]},{path:"*",component:d("*")}]},6125:(e,t,n)=>{"use strict";n.d(t,{o:()=>o,x:()=>i});var r=n(6540),a=n(4848);const o=r.createContext(!1);function i(e){let{children:t}=e;const[n,i]=(0,r.useState)(!1);return(0,r.useEffect)((()=>{i(!0)}),[]),(0,a.jsx)(o.Provider,{value:n,children:t})}},8522:(e,t,n)=>{"use strict";var r=n(6540),a=n(5338),o=n(4625),i=n(545),l=n(8193);const s=[n(1911),n(119),n(6134),n(6294),n(1043)];var c=n(8328),u=n(6347),d=n(2831),p=n(2303),f=n(4848);function m(e){let{children:t}=e;const n=(0,p.A)();return(0,r.useEffect)((()=>{n&&(function(){const e="fixed-chat-button";if(document.getElementById(e))return;const t=document.createElement("a");t.id=e,t.href="/chat",t.target="_blank",t.innerHTML="\ud83d\udcac Community Chat";const n=document.createElement("style");n.type="text/css",n.innerText="#"+e+" {color: white;position: fixed;right: 0;bottom: 0;background-color: var(--color-top);padding-left: 17px;padding-right: 17px;padding-top: 10px;padding-bottom: 5px;text-align: center;margin-right: 50px;font-weight: bold;border-top-left-radius: 9px;border-top-right-radius: 9px;z-index: 11;}#fixed-chat-button:hover {box-shadow: 2px 2px 13px #ca007c, -2px -1px 14px #ff009e;text-decoration: underline;}",document.head.appendChild(n),document.body.appendChild(t)}(),function(){if("/"===location.pathname)return;const e=[{text:"Follow",keyword:"@twitter",url:"https://twitter.com/intent/user?screen_name=rxdbjs",icon:"\ud83d\udc26"},{text:"Follow",keyword:"@LinkedIn",url:"https://www.linkedin.com/company/rxdb",icon:"[in]"},{text:"Chat",keyword:"@discord",url:"https://rxdb.info/chat",icon:"\ud83d\udcac"},{text:"Star",keyword:"@github",url:"https://rxdb.info/code",icon:"\ud83d\udc19\ud83d\udcbb"},{text:"Subscribe",keyword:"@newsletter",url:"https://rxdb.info/newsletter",icon:"\ud83d\udcf0"}];function t(e,t){e.parentNode.insertBefore(t,e.nextSibling)}const n="rxdb-call-to-action-button";function r(){console.log("set call to action button");const r=6e5,a=Date.now(),o=(a-a%r)/r;console.log("timeslot "+o);const i=o%e.length;console.log("randid: "+i);const l=e[i],s=document.querySelector(".call-to-action");s&&s.parentNode.removeChild(s);const c=document.querySelector(".navbar__items");if(!c)return;const u=document.createElement("div");u.classList.add("call-to-action");const d=document.createElement("a");d.onclick=()=>{window.trigger("call-to-action",.35)},d.classList.add("hover-shadow-top"),d.id=n,d.innerHTML=l.text+' '+l.keyword+''+l.icon+"",d.href=l.url,d.target="_blank",u.append(d),t(c,u)}r()}())})),(0,f.jsx)(f.Fragment,{children:t})}var h=n(5260),g=n(4586),b=n(6025),y=n(6342),v=n(1003),w=n(2131),x=n(4090),k=n(2967),S=n(440),E=n(1463);function _(){const{i18n:{currentLocale:e,defaultLocale:t,localeConfigs:n}}=(0,g.A)(),r=(0,w.o)(),a=n[e].htmlLang,o=e=>e.replace("-","_");return(0,f.jsxs)(h.A,{children:[Object.entries(n).map((e=>{let[t,{htmlLang:n}]=e;return(0,f.jsx)("link",{rel:"alternate",href:r.createUrl({locale:t,fullyQualified:!0}),hrefLang:n},t)})),(0,f.jsx)("link",{rel:"alternate",href:r.createUrl({locale:t,fullyQualified:!0}),hrefLang:"x-default"}),(0,f.jsx)("meta",{property:"og:locale",content:o(a)}),Object.values(n).filter((e=>a!==e.htmlLang)).map((e=>(0,f.jsx)("meta",{property:"og:locale:alternate",content:o(e.htmlLang)},`meta-og-${e.htmlLang}`)))]})}function C(e){let{permalink:t}=e;const{siteConfig:{url:n}}=(0,g.A)(),r=function(){const{siteConfig:{url:e,baseUrl:t,trailingSlash:n}}=(0,g.A)(),{pathname:r}=(0,u.zy)();return e+(0,S.applyTrailingSlash)((0,b.A)(r),{trailingSlash:n,baseUrl:t})}(),a=t?`${n}${t}`:r;return(0,f.jsxs)(h.A,{children:[(0,f.jsx)("meta",{property:"og:url",content:a}),(0,f.jsx)("link",{rel:"canonical",href:a})]})}function T(){const{i18n:{currentLocale:e}}=(0,g.A)(),{metadata:t,image:n}=(0,y.p)();return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(h.A,{children:[(0,f.jsx)("meta",{name:"twitter:card",content:"summary_large_image"}),(0,f.jsx)("body",{className:x.w})]}),n&&(0,f.jsx)(v.be,{image:n}),(0,f.jsx)(C,{}),(0,f.jsx)(_,{}),(0,f.jsx)(E.A,{tag:k.Cy,locale:e}),(0,f.jsx)(h.A,{children:t.map(((e,t)=>(0,f.jsx)("meta",{...e},t)))})]})}const A=new Map;function j(e){if(A.has(e.pathname))return{...e,pathname:A.get(e.pathname)};if((0,d.u)(c.A,e.pathname).some((e=>{let{route:t}=e;return!0===t.exact})))return A.set(e.pathname,e.pathname),e;const t=e.pathname.trim().replace(/(?:\/index)?\.html$/,"")||"/";return A.set(e.pathname,t),{...e,pathname:t}}var N=n(6125),R=n(6988),L=n(205);function P(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{const r=t.default?.[e]??t[e];return r?.(...n)}));return()=>a.forEach((e=>e?.()))}const O=function(e){let{children:t,location:n,previousLocation:r}=e;return(0,L.A)((()=>{r!==n&&(!function(e){let{location:t,previousLocation:n}=e;if(!n)return;const r=t.pathname===n.pathname,a=t.hash===n.hash,o=t.search===n.search;if(r&&a&&!o)return;const{hash:i}=t;if(i){const e=decodeURIComponent(i.substring(1)),t=document.getElementById(e);t?.scrollIntoView()}else window.scrollTo(0,0)}({location:n,previousLocation:r}),P("onRouteDidUpdate",{previousLocation:r,location:n}))}),[r,n]),t};function I(e){const t=Array.from(new Set([e,decodeURI(e)])).map((e=>(0,d.u)(c.A,e))).flat();return Promise.all(t.map((e=>e.route.component.preload?.())))}class D extends r.Component{previousLocation;routeUpdateCleanupCb;constructor(e){super(e),this.previousLocation=null,this.routeUpdateCleanupCb=l.A.canUseDOM?P("onRouteUpdate",{previousLocation:null,location:this.props.location}):()=>{},this.state={nextRouteHasLoaded:!0}}shouldComponentUpdate(e,t){if(e.location===this.props.location)return t.nextRouteHasLoaded;const n=e.location;return this.previousLocation=this.props.location,this.setState({nextRouteHasLoaded:!1}),this.routeUpdateCleanupCb=P("onRouteUpdate",{previousLocation:this.previousLocation,location:n}),I(n.pathname).then((()=>{this.routeUpdateCleanupCb(),this.setState({nextRouteHasLoaded:!0})})).catch((e=>{console.warn(e),window.location.reload()})),!1}render(){const{children:e,location:t}=this.props;return(0,f.jsx)(O,{previousLocation:this.previousLocation,location:t,children:(0,f.jsx)(u.qh,{location:t,render:()=>e})})}}const M=D,F="__docusaurus-base-url-issue-banner-container",z="__docusaurus-base-url-issue-banner",B="__docusaurus-base-url-issue-banner-suggestion-container";function $(e){return`\ndocument.addEventListener('DOMContentLoaded', function maybeInsertBanner() {\n var shouldInsert = typeof window['docusaurus'] === 'undefined';\n shouldInsert && insertBanner();\n});\n\nfunction insertBanner() {\n var bannerContainer = document.createElement('div');\n bannerContainer.id = '${F}';\n var bannerHtml = ${JSON.stringify(function(e){return`\n
\n

Your Docusaurus site did not load properly.

\n

A very common reason is a wrong site baseUrl configuration.

\n

Current configured baseUrl = ${e} ${"/"===e?" (default value)":""}

\n

We suggest trying baseUrl =

\n
\n`}(e)).replace(/{if("undefined"==typeof document)return void n();const r=document.createElement("link");r.setAttribute("rel","prefetch"),r.setAttribute("href",e),r.onload=()=>t(),r.onerror=()=>n();const a=document.getElementsByTagName("head")[0]??document.getElementsByName("script")[0]?.parentNode;a?.appendChild(r)}))}:function(e){return new Promise(((t,n)=>{const r=new XMLHttpRequest;r.open("GET",e,!0),r.withCredentials=!0,r.onload=()=>{200===r.status?t():n()},r.send(null)}))};var Y=n(6921);const J=new Set,Z=new Set,X=()=>navigator.connection?.effectiveType.includes("2g")||navigator.connection?.saveData,ee={prefetch(e){if(!(e=>!X()&&!Z.has(e)&&!J.has(e))(e))return!1;J.add(e);const t=(0,d.u)(c.A,e).flatMap((e=>{return t=e.route.path,Object.entries(Q).filter((e=>{let[n]=e;return n.replace(/-[^-]+$/,"")===t})).flatMap((e=>{let[,t]=e;return Object.values((0,Y.A)(t))}));var t}));return Promise.all(t.map((e=>{const t=n.gca(e);return t&&!t.includes("undefined")?K(t).catch((()=>{})):Promise.resolve()})))},preload:e=>!!(e=>!X()&&!Z.has(e))(e)&&(Z.add(e),I(e))},te=Object.freeze(ee),ne=Boolean(!0);if(l.A.canUseDOM){window.docusaurus=te;const e=document.getElementById("__docusaurus"),t=(0,f.jsx)(i.vd,{children:(0,f.jsx)(o.Kd,{children:(0,f.jsx)(V,{})})}),n=(e,t)=>{console.error("Docusaurus React Root onRecoverableError:",e,t)},l=()=>{if(ne)r.startTransition((()=>{a.hydrateRoot(e,t,{onRecoverableError:n})}));else{const o=a.createRoot(e,{onRecoverableError:n});r.startTransition((()=>{o.render(t)}))}};I(window.location.pathname).then(l)}},6988:(e,t,n)=>{"use strict";n.d(t,{o:()=>d,l:()=>p});var r=n(6540),a=n(4784);const o=JSON.parse('{"docusaurus-plugin-google-gtag":{"default":{"trackingID":["G-62D63SY3S0"],"anonymizeIP":false,"id":"default"}},"docusaurus-lunr-search":{"default":{"fileNames":{"searchDoc":"search-doc-1710806454997.json","lunrIndex":"lunr-index-1710806454997.json"}}},"docusaurus-plugin-google-tag-manager":{"default":{"containerId":"GTM-PL63TR5","id":"default"}},"docusaurus-plugin-content-docs":{"default":{"path":"/","versions":[{"name":"current","label":"Next","isLast":true,"path":"/","mainDocId":"quickstart","docs":[{"id":"adapters","path":"/adapters.html"},{"id":"alternatives","path":"/alternatives.html","sidebar":"tutorialSidebar"},{"id":"articles/angular-database","path":"/articles/angular-database.html","sidebar":"tutorialSidebar"},{"id":"articles/browser-database","path":"/articles/browser-database.html","sidebar":"tutorialSidebar"},{"id":"articles/browser-storage","path":"/articles/browser-storage.html","sidebar":"tutorialSidebar"},{"id":"articles/data-base","path":"/articles/data-base.html","sidebar":"tutorialSidebar"},{"id":"articles/embedded-database","path":"/articles/embedded-database.html","sidebar":"tutorialSidebar"},{"id":"articles/flutter-database","path":"/articles/flutter-database.html","sidebar":"tutorialSidebar"},{"id":"articles/frontend-database","path":"/articles/frontend-database.html","sidebar":"tutorialSidebar"},{"id":"articles/in-memory-nosql-database","path":"/articles/in-memory-nosql-database.html","sidebar":"tutorialSidebar"},{"id":"articles/ionic-database","path":"/articles/ionic-database.html","sidebar":"tutorialSidebar"},{"id":"articles/json-database","path":"/articles/json-database.html","sidebar":"tutorialSidebar"},{"id":"articles/localstorage","path":"/articles/localstorage.html","sidebar":"tutorialSidebar"},{"id":"articles/mobile-database","path":"/articles/mobile-database.html","sidebar":"tutorialSidebar"},{"id":"articles/progressive-web-app-database","path":"/articles/progressive-web-app-database.html","sidebar":"tutorialSidebar"},{"id":"articles/react-database","path":"/articles/react-database.html","sidebar":"tutorialSidebar"},{"id":"articles/realtime-database","path":"/articles/realtime-database.html","sidebar":"tutorialSidebar"},{"id":"articles/websockets-sse-polling-webrtc-webtransport","path":"/articles/websockets-sse-polling-webrtc-webtransport.html","sidebar":"tutorialSidebar"},{"id":"backup","path":"/backup.html","sidebar":"tutorialSidebar"},{"id":"capacitor-database","path":"/capacitor-database.html","sidebar":"tutorialSidebar"},{"id":"cleanup","path":"/cleanup.html","sidebar":"tutorialSidebar"},{"id":"contribute","path":"/contribution.html","sidebar":"tutorialSidebar"},{"id":"crdt","path":"/crdt.html","sidebar":"tutorialSidebar"},{"id":"data-migration","path":"/data-migration"},{"id":"dev-mode","path":"/dev-mode.html","sidebar":"tutorialSidebar"},{"id":"downsides-of-offline-first","path":"/downsides-of-offline-first.html","sidebar":"tutorialSidebar"},{"id":"electron","path":"/electron.html","sidebar":"tutorialSidebar"},{"id":"electron-database","path":"/electron-database.html","sidebar":"tutorialSidebar"},{"id":"encryption","path":"/encryption.html","sidebar":"tutorialSidebar"},{"id":"install","path":"/install.html","sidebar":"tutorialSidebar"},{"id":"key-compression","path":"/key-compression.html","sidebar":"tutorialSidebar"},{"id":"leader-election","path":"/leader-election.html","sidebar":"tutorialSidebar"},{"id":"logger","path":"/logger.html","sidebar":"tutorialSidebar"},{"id":"middleware","path":"/middleware.html","sidebar":"tutorialSidebar"},{"id":"migration-schema","path":"/migration-schema.html","sidebar":"tutorialSidebar"},{"id":"migration-storage","path":"/migration-storage.html","sidebar":"tutorialSidebar"},{"id":"nodejs-database","path":"/nodejs-database.html","sidebar":"tutorialSidebar"},{"id":"nosql-performance-tips","path":"/nosql-performance-tips.html","sidebar":"tutorialSidebar"},{"id":"offline-first","path":"/offline-first.html","sidebar":"tutorialSidebar"},{"id":"orm","path":"/orm.html","sidebar":"tutorialSidebar"},{"id":"plugins","path":"/plugins.html","sidebar":"tutorialSidebar"},{"id":"population","path":"/population.html","sidebar":"tutorialSidebar"},{"id":"query-cache","path":"/query-cache.html","sidebar":"tutorialSidebar"},{"id":"query-optimizer","path":"/query-optimizer.html","sidebar":"tutorialSidebar"},{"id":"questions-answers","path":"/questions-answers.html","sidebar":"tutorialSidebar"},{"id":"quickstart","path":"/quickstart.html","sidebar":"tutorialSidebar"},{"id":"react-native-database","path":"/react-native-database.html","sidebar":"tutorialSidebar"},{"id":"reactivity","path":"/reactivity.html","sidebar":"tutorialSidebar"},{"id":"releases/10.0.0","path":"/releases/10.0.0.html","sidebar":"tutorialSidebar"},{"id":"releases/11.0.0","path":"/releases/11.0.0.html","sidebar":"tutorialSidebar"},{"id":"releases/12.0.0","path":"/releases/12.0.0.html","sidebar":"tutorialSidebar"},{"id":"releases/13.0.0","path":"/releases/13.0.0.html","sidebar":"tutorialSidebar"},{"id":"releases/14.0.0","path":"/releases/14.0.0.html","sidebar":"tutorialSidebar"},{"id":"releases/15.0.0","path":"/releases/15.0.0.html","sidebar":"tutorialSidebar"},{"id":"releases/8.0.0","path":"/releases/8.0.0.html","sidebar":"tutorialSidebar"},{"id":"releases/9.0.0","path":"/releases/9.0.0.html","sidebar":"tutorialSidebar"},{"id":"replication","path":"/replication.html","sidebar":"tutorialSidebar"},{"id":"replication-couchdb","path":"/replication-couchdb.html","sidebar":"tutorialSidebar"},{"id":"replication-firestore","path":"/replication-firestore.html","sidebar":"tutorialSidebar"},{"id":"replication-graphql","path":"/replication-graphql.html","sidebar":"tutorialSidebar"},{"id":"replication-http","path":"/replication-http.html","sidebar":"tutorialSidebar"},{"id":"replication-nats","path":"/replication-nats.html","sidebar":"tutorialSidebar"},{"id":"replication-p2p","path":"/replication-p2p.html"},{"id":"replication-server","path":"/replication-server","sidebar":"tutorialSidebar"},{"id":"replication-webrtc","path":"/replication-webrtc.html","sidebar":"tutorialSidebar"},{"id":"replication-websocket","path":"/replication-websocket.html","sidebar":"tutorialSidebar"},{"id":"rx-attachment","path":"/rx-attachment.html","sidebar":"tutorialSidebar"},{"id":"rx-collection","path":"/rx-collection.html","sidebar":"tutorialSidebar"},{"id":"rx-database","path":"/rx-database.html","sidebar":"tutorialSidebar"},{"id":"rx-document","path":"/rx-document.html","sidebar":"tutorialSidebar"},{"id":"rx-local-document","path":"/rx-local-document.html","sidebar":"tutorialSidebar"},{"id":"rx-query","path":"/rx-query.html","sidebar":"tutorialSidebar"},{"id":"rx-schema","path":"/rx-schema.html","sidebar":"tutorialSidebar"},{"id":"rx-server","path":"/rx-server.html","sidebar":"tutorialSidebar"},{"id":"rx-server-scaling","path":"/rx-server-scaling.html","sidebar":"tutorialSidebar"},{"id":"rx-state","path":"/rx-state.html","sidebar":"tutorialSidebar"},{"id":"rx-storage","path":"/rx-storage.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-denokv","path":"/rx-storage-denokv.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-dexie","path":"/rx-storage-dexie.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-filesystem-node","path":"/rx-storage-filesystem-node.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-foundationdb","path":"/rx-storage-foundationdb.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-indexeddb","path":"/rx-storage-indexeddb.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-localstorage-meta-optimizer","path":"/rx-storage-localstorage-meta-optimizer.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-lokijs","path":"/rx-storage-lokijs.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-memory","path":"/rx-storage-memory.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-memory-synced","path":"/rx-storage-memory-synced.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-mongodb","path":"/rx-storage-mongodb.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-opfs","path":"/rx-storage-opfs.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-performance","path":"/rx-storage-performance.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-pouchdb","path":"/rx-storage-pouchdb.html"},{"id":"rx-storage-remote","path":"/rx-storage-remote.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-sharding","path":"/rx-storage-sharding.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-shared-worker","path":"/rx-storage-shared-worker.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-sqlite","path":"/rx-storage-sqlite.html","sidebar":"tutorialSidebar"},{"id":"rx-storage-worker","path":"/rx-storage-worker.html","sidebar":"tutorialSidebar"},{"id":"rxdb-tradeoffs","path":"/rxdb-tradeoffs.html"},{"id":"schema-validation","path":"/schema-validation.html"},{"id":"slow-indexeddb","path":"/slow-indexeddb.html","sidebar":"tutorialSidebar"},{"id":"third-party-plugins","path":"/third-party-plugins.html","sidebar":"tutorialSidebar"},{"id":"transactions-conflicts-revisions","path":"/transactions-conflicts-revisions.html","sidebar":"tutorialSidebar"},{"id":"tutorials/typescript","path":"/tutorials/typescript.html","sidebar":"tutorialSidebar"},{"id":"why-nosql","path":"/why-nosql.html","sidebar":"tutorialSidebar"}],"draftIds":[],"sidebars":{"tutorialSidebar":{"link":{"path":"/quickstart.html","label":"quickstart"}}}}],"breadcrumbs":true}}}'),i=JSON.parse('{"defaultLocale":"en","locales":["en"],"path":"i18n","currentLocale":"en","localeConfigs":{"en":{"label":"English","direction":"ltr","htmlLang":"en","calendar":"gregory","path":"en"}}}');var l=n(2654);const s=JSON.parse('{"docusaurusVersion":"3.0.1","siteVersion":"0.0.0","pluginVersions":{"docusaurus-plugin-content-docs":{"type":"package","name":"@docusaurus/plugin-content-docs","version":"3.0.1"},"docusaurus-plugin-content-blog":{"type":"package","name":"@docusaurus/plugin-content-blog","version":"3.0.1"},"docusaurus-plugin-content-pages":{"type":"package","name":"@docusaurus/plugin-content-pages","version":"3.0.1"},"docusaurus-plugin-google-gtag":{"type":"package","name":"@docusaurus/plugin-google-gtag","version":"3.0.1"},"docusaurus-plugin-google-tag-manager":{"type":"package","name":"@docusaurus/plugin-google-tag-manager","version":"3.0.1"},"docusaurus-plugin-sitemap":{"type":"package","name":"@docusaurus/plugin-sitemap","version":"3.0.1"},"docusaurus-theme-classic":{"type":"package","name":"@docusaurus/theme-classic","version":"3.0.1"},"docusaurus-lunr-search":{"type":"package","name":"docusaurus-lunr-search","version":"3.3.1"}}}');var c=n(4848);const u={siteConfig:a.default,siteMetadata:s,globalData:o,i18n:i,codeTranslations:l},d=r.createContext(u);function p(e){let{children:t}=e;return(0,c.jsx)(d.Provider,{value:u,children:t})}},7489:(e,t,n)=>{"use strict";n.d(t,{A:()=>f});var r=n(6540),a=n(8193),o=n(5260),i=n(440),l=n(1595),s=n(4848);function c(e){let{error:t,tryAgain:n}=e;return(0,s.jsxs)("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"flex-start",minHeight:"100vh",width:"100%",maxWidth:"80ch",fontSize:"20px",margin:"0 auto",padding:"1rem"},children:[(0,s.jsx)("h1",{style:{fontSize:"3rem"},children:"This page crashed"}),(0,s.jsx)("button",{type:"button",onClick:n,style:{margin:"1rem 0",fontSize:"2rem",cursor:"pointer",borderRadius:20,padding:"1rem"},children:"Try again"}),(0,s.jsx)(u,{error:t})]})}function u(e){let{error:t}=e;const n=(0,i.getErrorCausalChain)(t).map((e=>e.message)).join("\n\nCause:\n");return(0,s.jsx)("p",{style:{whiteSpace:"pre-wrap"},children:n})}function d(e){let{error:t,tryAgain:n}=e;return(0,s.jsxs)(f,{fallback:()=>(0,s.jsx)(c,{error:t,tryAgain:n}),children:[(0,s.jsx)(o.A,{children:(0,s.jsx)("title",{children:"Page Error"})}),(0,s.jsx)(l.A,{children:(0,s.jsx)(c,{error:t,tryAgain:n})})]})}const p=e=>(0,s.jsx)(d,{...e});class f extends r.Component{constructor(e){super(e),this.state={error:null}}componentDidCatch(e){a.A.canUseDOM&&this.setState({error:e})}render(){const{children:e}=this.props,{error:t}=this.state;if(t){const e={error:t,tryAgain:()=>this.setState({error:null})};return(this.props.fallback??p)(e)}return e??null}}},8193:(e,t,n)=>{"use strict";n.d(t,{A:()=>a});const r="undefined"!=typeof window&&"document"in window&&"createElement"in window.document,a={canUseDOM:r,canUseEventListeners:r&&("addEventListener"in window||"attachEvent"in window),canUseIntersectionObserver:r&&"IntersectionObserver"in window,canUseViewport:r&&"screen"in window}},5260:(e,t,n)=>{"use strict";n.d(t,{A:()=>o});n(6540);var r=n(545),a=n(4848);function o(e){return(0,a.jsx)(r.mg,{...e})}},5489:(e,t,n)=>{"use strict";n.d(t,{A:()=>f});var r=n(6540),a=n(4625),o=n(440),i=n(4586),l=n(6654),s=n(8193),c=n(4848);const u=r.createContext({collectLink:()=>{}});var d=n(6025);function p(e,t){let{isNavLink:n,to:p,href:f,activeClassName:m,isActive:h,"data-noBrokenLinkCheck":g,autoAddBaseUrl:b=!0,...y}=e;const{siteConfig:{trailingSlash:v,baseUrl:w}}=(0,i.A)(),{withBaseUrl:x}=(0,d.h)(),k=(0,r.useContext)(u),S=(0,r.useRef)(null);(0,r.useImperativeHandle)(t,(()=>S.current));const E=p||f;const _=(0,l.A)(E),C=E?.replace("pathname://","");let T=void 0!==C?(A=C,b&&(e=>e.startsWith("/"))(A)?x(A):A):void 0;var A;T&&_&&(T=(0,o.applyTrailingSlash)(T,{trailingSlash:v,baseUrl:w}));const j=(0,r.useRef)(!1),N=n?a.k2:a.N_,R=s.A.canUseIntersectionObserver,L=(0,r.useRef)(),P=()=>{j.current||null==T||(window.docusaurus.preload(T),j.current=!0)};(0,r.useEffect)((()=>(!R&&_&&null!=T&&window.docusaurus.prefetch(T),()=>{R&&L.current&&L.current.disconnect()})),[L,T,R,_]);const O=T?.startsWith("#")??!1,I=!T||!_||O;return I||g||k.collectLink(T),I?(0,c.jsx)("a",{ref:S,href:T,...E&&!_&&{target:"_blank",rel:"noopener noreferrer"},...y}):(0,c.jsx)(N,{...y,onMouseEnter:P,onTouchStart:P,innerRef:e=>{S.current=e,R&&e&&_&&(L.current=new window.IntersectionObserver((t=>{t.forEach((t=>{e===t.target&&(t.isIntersecting||t.intersectionRatio>0)&&(L.current.unobserve(e),L.current.disconnect(),null!=T&&window.docusaurus.prefetch(T))}))})),L.current.observe(e))},to:T,...n&&{isActive:h,activeClassName:m}})}const f=r.forwardRef(p)},1312:(e,t,n)=>{"use strict";n.d(t,{A:()=>c,T:()=>s});var r=n(6540),a=n(4848);function o(e,t){const n=e.split(/(\{\w+\})/).map(((e,n)=>{if(n%2==1){const n=t?.[e.slice(1,-1)];if(void 0!==n)return n}return e}));return n.some((e=>(0,r.isValidElement)(e)))?n.map(((e,t)=>(0,r.isValidElement)(e)?r.cloneElement(e,{key:t}):e)).filter((e=>""!==e)):n.join("")}var i=n(2654);function l(e){let{id:t,message:n}=e;if(void 0===t&&void 0===n)throw new Error("Docusaurus translation declarations must have at least a translation id or a default translation message");return i[t??n]??n??t}function s(e,t){let{message:n,id:r}=e;return o(l({message:n,id:r}),t)}function c(e){let{children:t,id:n,values:r}=e;if(t&&"string"!=typeof t)throw console.warn("Illegal children",t),new Error("The Docusaurus component only accept simple string values");const i=l({message:t,id:n});return(0,a.jsx)(a.Fragment,{children:o(i,r)})}},7065:(e,t,n)=>{"use strict";n.d(t,{W:()=>r});const r="default"},6654:(e,t,n)=>{"use strict";function r(e){return/^(?:\w*:|\/\/)/.test(e)}function a(e){return void 0!==e&&!r(e)}n.d(t,{A:()=>a,z:()=>r})},6025:(e,t,n)=>{"use strict";n.d(t,{A:()=>l,h:()=>i});var r=n(6540),a=n(4586),o=n(6654);function i(){const{siteConfig:{baseUrl:e,url:t}}=(0,a.A)(),n=(0,r.useCallback)(((n,r)=>function(e,t,n,r){let{forcePrependBaseUrl:a=!1,absolute:i=!1}=void 0===r?{}:r;if(!n||n.startsWith("#")||(0,o.z)(n))return n;if(a)return t+n.replace(/^\//,"");if(n===t.replace(/\/$/,""))return t;const l=n.startsWith(t)?n:t+n.replace(/^\//,"");return i?e+l:l}(t,e,n,r)),[t,e]);return{withBaseUrl:n}}function l(e,t){void 0===t&&(t={});const{withBaseUrl:n}=i();return n(e,t)}},4586:(e,t,n)=>{"use strict";n.d(t,{A:()=>o});var r=n(6540),a=n(6988);function o(){return(0,r.useContext)(a.o)}},6588:(e,t,n)=>{"use strict";n.d(t,{P_:()=>i,kh:()=>o});var r=n(4586),a=n(7065);function o(e,t){void 0===t&&(t={});const n=function(){const{globalData:e}=(0,r.A)();return e}()[e];if(!n&&t.failfast)throw new Error(`Docusaurus plugin global data not found for "${e}" plugin.`);return n}function i(e,t,n){void 0===t&&(t=a.W),void 0===n&&(n={});const r=o(e),i=r?.[t];if(!i&&n.failfast)throw new Error(`Docusaurus plugin global data not found for "${e}" plugin with id "${t}".`);return i}},2303:(e,t,n)=>{"use strict";n.d(t,{A:()=>o});var r=n(6540),a=n(6125);function o(){return(0,r.useContext)(a.o)}},205:(e,t,n)=>{"use strict";n.d(t,{A:()=>a});var r=n(6540);const a=n(8193).A.canUseDOM?r.useLayoutEffect:r.useEffect},6921:(e,t,n)=>{"use strict";n.d(t,{A:()=>a});const r=e=>"object"==typeof e&&!!e&&Object.keys(e).length>0;function a(e){const t={};return function e(n,a){Object.entries(n).forEach((n=>{let[o,i]=n;const l=a?`${a}.${o}`:o;r(i)?e(i,l):t[l]=i}))}(e),t}},3102:(e,t,n)=>{"use strict";n.d(t,{W:()=>i,o:()=>o});var r=n(6540),a=n(4848);const o=r.createContext(null);function i(e){let{children:t,value:n}=e;const i=r.useContext(o),l=(0,r.useMemo)((()=>function(e){let{parent:t,value:n}=e;if(!t){if(!n)throw new Error("Unexpected: no Docusaurus route context found");if(!("plugin"in n))throw new Error("Unexpected: Docusaurus topmost route context has no `plugin` attribute");return n}const r={...t.data,...n?.data};return{plugin:t.plugin,data:r}}({parent:i,value:n})),[i,n]);return(0,a.jsx)(o.Provider,{value:l,children:t})}},8295:(e,t,n)=>{"use strict";n.d(t,{zK:()=>f,vT:()=>u,Gy:()=>s,HW:()=>m,ht:()=>c,r7:()=>p,jh:()=>d});var r=n(6347),a=n(6588);const o=e=>e.versions.find((e=>e.isLast));function i(e,t){const n=function(e,t){const n=o(e);return[...e.versions.filter((e=>e!==n)),n].find((e=>!!(0,r.B6)(t,{path:e.path,exact:!1,strict:!1})))}(e,t),a=n?.docs.find((e=>!!(0,r.B6)(t,{path:e.path,exact:!0,strict:!1})));return{activeVersion:n,activeDoc:a,alternateDocVersions:a?function(t){const n={};return e.versions.forEach((e=>{e.docs.forEach((r=>{r.id===t&&(n[e.name]=r)}))})),n}(a.id):{}}}const l={},s=()=>(0,a.kh)("docusaurus-plugin-content-docs")??l,c=e=>(0,a.P_)("docusaurus-plugin-content-docs",e,{failfast:!0});function u(e){void 0===e&&(e={});const t=s(),{pathname:n}=(0,r.zy)();return function(e,t,n){void 0===n&&(n={});const a=Object.entries(e).sort(((e,t)=>t[1].path.localeCompare(e[1].path))).find((e=>{let[,n]=e;return!!(0,r.B6)(t,{path:n.path,exact:!1,strict:!1})})),o=a?{pluginId:a[0],pluginData:a[1]}:void 0;if(!o&&n.failfast)throw new Error(`Can't find active docs plugin for "${t}" pathname, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: ${Object.values(e).map((e=>e.path)).join(", ")}`);return o}(t,n,e)}function d(e){return c(e).versions}function p(e){const t=c(e);return o(t)}function f(e){const t=c(e),{pathname:n}=(0,r.zy)();return i(t,n)}function m(e){const t=c(e),{pathname:n}=(0,r.zy)();return function(e,t){const n=o(e);return{latestDocSuggestion:i(e,t).alternateDocVersions[n.name],latestVersionSuggestion:n}}(t,n)}},1911:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>r});const r={onRouteDidUpdate(e){let{location:t,previousLocation:n}=e;!n||t.pathname===n.pathname&&t.search===n.search&&t.hash===n.hash||setTimeout((()=>{window.gtag("set","page_path",t.pathname+t.search+t.hash),window.gtag("event","page_view")}))}}},6294:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>o});var r=n(5947),a=n.n(r);a().configure({showSpinner:!1});const o={onRouteUpdate(e){let{location:t,previousLocation:n}=e;if(n&&t.pathname!==n.pathname){const e=window.setTimeout((()=>{a().start()}),200);return()=>window.clearTimeout(e)}},onRouteDidUpdate(){a().done()}}},6134:(e,t,n)=>{"use strict";n.r(t);var r=n(1765),a=n(4784);!function(e){const{themeConfig:{prism:t}}=a.default,{additionalLanguages:r}=t;globalThis.Prism=e,r.forEach((e=>{"php"===e&&n(9700),n(8692)(`./prism-${e}`)})),delete globalThis.Prism}(r.My)},1107:(e,t,n)=>{"use strict";n.d(t,{A:()=>c});n(6540);var r=n(4164),a=n(1312),o=n(6342),i=n(5489);const l={anchorWithStickyNavbar:"anchorWithStickyNavbar_LWe7",anchorWithHideOnScrollNavbar:"anchorWithHideOnScrollNavbar_WYt5"};var s=n(4848);function c(e){let{as:t,id:n,...c}=e;const{navbar:{hideOnScroll:u}}=(0,o.p)();if("h1"===t||!n)return(0,s.jsx)(t,{...c,id:void 0});const d=(0,a.T)({id:"theme.common.headingLinkTitle",message:"Direct link to {heading}",description:"Title for link to heading"},{heading:"string"==typeof c.children?c.children:n});return(0,s.jsxs)(t,{...c,className:(0,r.A)("anchor",u?l.anchorWithHideOnScrollNavbar:l.anchorWithStickyNavbar,c.className),id:n,children:[c.children,(0,s.jsx)(i.A,{className:"hash-link",to:`#${n}`,"aria-label":d,title:d,children:"\u200b"})]})}},3186:(e,t,n)=>{"use strict";n.d(t,{A:()=>o});n(6540);const r={iconExternalLink:"iconExternalLink_nPIU"};var a=n(4848);function o(e){let{width:t=13.5,height:n=13.5}=e;return(0,a.jsx)("svg",{width:t,height:n,"aria-hidden":"true",viewBox:"0 0 24 24",className:r.iconExternalLink,children:(0,a.jsx)("path",{fill:"currentColor",d:"M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"})})}},1595:(e,t,n)=>{"use strict";n.d(t,{A:()=>bt});var r=n(6540),a=n(4164),o=n(7489),i=n(1003),l=n(6347),s=n(1312),c=n(5062),u=n(4848);const d="__docusaurus_skipToContent_fallback";function p(e){e.setAttribute("tabindex","-1"),e.focus(),e.removeAttribute("tabindex")}function f(){const e=(0,r.useRef)(null),{action:t}=(0,l.W6)(),n=(0,r.useCallback)((e=>{e.preventDefault();const t=document.querySelector("main:first-of-type")??document.getElementById(d);t&&p(t)}),[]);return(0,c.$)((n=>{let{location:r}=n;e.current&&!r.hash&&"PUSH"===t&&p(e.current)})),{containerRef:e,onClick:n}}const m=(0,s.T)({id:"theme.common.skipToMainContent",description:"The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation",message:"Skip to main content"});function h(e){const t=e.children??m,{containerRef:n,onClick:r}=f();return(0,u.jsx)("div",{ref:n,role:"region","aria-label":m,children:(0,u.jsx)("a",{...e,href:`#${d}`,onClick:r,children:t})})}var g=n(7559),b=n(4090);const y={skipToContent:"skipToContent_fXgn"};function v(){return(0,u.jsx)(h,{className:y.skipToContent})}var w=n(6342),x=n(5041);function k(e){let{width:t=21,height:n=21,color:r="currentColor",strokeWidth:a=1.2,className:o,...i}=e;return(0,u.jsx)("svg",{viewBox:"0 0 15 15",width:t,height:n,...i,children:(0,u.jsx)("g",{stroke:r,strokeWidth:a,children:(0,u.jsx)("path",{d:"M.75.75l13.5 13.5M14.25.75L.75 14.25"})})})}const S={closeButton:"closeButton_CVFx"};function E(e){return(0,u.jsx)("button",{type:"button","aria-label":(0,s.T)({id:"theme.AnnouncementBar.closeButtonAriaLabel",message:"Close",description:"The ARIA label for close button of announcement bar"}),...e,className:(0,a.A)("clean-btn close",S.closeButton,e.className),children:(0,u.jsx)(k,{width:14,height:14,strokeWidth:3.1})})}const _={content:"content_knG7"};function C(e){const{announcementBar:t}=(0,w.p)(),{content:n}=t;return(0,u.jsx)("div",{...e,className:(0,a.A)(_.content,e.className),dangerouslySetInnerHTML:{__html:n}})}const T={announcementBar:"announcementBar_mb4j",announcementBarPlaceholder:"announcementBarPlaceholder_vyr4",announcementBarClose:"announcementBarClose_gvF7",announcementBarContent:"announcementBarContent_xLdY"};function A(){const{announcementBar:e}=(0,w.p)(),{isActive:t,close:n}=(0,x.Mj)();if(!t)return null;const{backgroundColor:r,textColor:a,isCloseable:o}=e;return(0,u.jsxs)("div",{className:T.announcementBar,style:{backgroundColor:r,color:a},role:"banner",children:[o&&(0,u.jsx)("div",{className:T.announcementBarPlaceholder}),(0,u.jsx)(C,{className:T.announcementBarContent}),o&&(0,u.jsx)(E,{onClick:n,className:T.announcementBarClose})]})}var j=n(9876),N=n(3104);var R=n(9532),L=n(5600);const P=r.createContext(null);function O(e){let{children:t}=e;const n=function(){const e=(0,j.M)(),t=(0,L.YL)(),[n,a]=(0,r.useState)(!1),o=null!==t.component,i=(0,R.ZC)(o);return(0,r.useEffect)((()=>{o&&!i&&a(!0)}),[o,i]),(0,r.useEffect)((()=>{o?e.shown||a(!0):a(!1)}),[e.shown,o]),(0,r.useMemo)((()=>[n,a]),[n])}();return(0,u.jsx)(P.Provider,{value:n,children:t})}function I(e){if(e.component){const t=e.component;return(0,u.jsx)(t,{...e.props})}}function D(){const e=(0,r.useContext)(P);if(!e)throw new R.dV("NavbarSecondaryMenuDisplayProvider");const[t,n]=e,a=(0,r.useCallback)((()=>n(!1)),[n]),o=(0,L.YL)();return(0,r.useMemo)((()=>({shown:t,hide:a,content:I(o)})),[a,o,t])}function M(e){let{header:t,primaryMenu:n,secondaryMenu:r}=e;const{shown:o}=D();return(0,u.jsxs)("div",{className:"navbar-sidebar",children:[t,(0,u.jsxs)("div",{className:(0,a.A)("navbar-sidebar__items",{"navbar-sidebar__items--show-secondary":o}),children:[(0,u.jsx)("div",{className:"navbar-sidebar__item menu",children:n}),(0,u.jsx)("div",{className:"navbar-sidebar__item menu",children:r})]})]})}var F=n(5293),z=n(2303);function B(e){return(0,u.jsx)("svg",{viewBox:"0 0 24 24",width:24,height:24,...e,children:(0,u.jsx)("path",{fill:"currentColor",d:"M12,9c1.65,0,3,1.35,3,3s-1.35,3-3,3s-3-1.35-3-3S10.35,9,12,9 M12,7c-2.76,0-5,2.24-5,5s2.24,5,5,5s5-2.24,5-5 S14.76,7,12,7L12,7z M2,13l2,0c0.55,0,1-0.45,1-1s-0.45-1-1-1l-2,0c-0.55,0-1,0.45-1,1S1.45,13,2,13z M20,13l2,0c0.55,0,1-0.45,1-1 s-0.45-1-1-1l-2,0c-0.55,0-1,0.45-1,1S19.45,13,20,13z M11,2v2c0,0.55,0.45,1,1,1s1-0.45,1-1V2c0-0.55-0.45-1-1-1S11,1.45,11,2z M11,20v2c0,0.55,0.45,1,1,1s1-0.45,1-1v-2c0-0.55-0.45-1-1-1C11.45,19,11,19.45,11,20z M5.99,4.58c-0.39-0.39-1.03-0.39-1.41,0 c-0.39,0.39-0.39,1.03,0,1.41l1.06,1.06c0.39,0.39,1.03,0.39,1.41,0s0.39-1.03,0-1.41L5.99,4.58z M18.36,16.95 c-0.39-0.39-1.03-0.39-1.41,0c-0.39,0.39-0.39,1.03,0,1.41l1.06,1.06c0.39,0.39,1.03,0.39,1.41,0c0.39-0.39,0.39-1.03,0-1.41 L18.36,16.95z M19.42,5.99c0.39-0.39,0.39-1.03,0-1.41c-0.39-0.39-1.03-0.39-1.41,0l-1.06,1.06c-0.39,0.39-0.39,1.03,0,1.41 s1.03,0.39,1.41,0L19.42,5.99z M7.05,18.36c0.39-0.39,0.39-1.03,0-1.41c-0.39-0.39-1.03-0.39-1.41,0l-1.06,1.06 c-0.39,0.39-0.39,1.03,0,1.41s1.03,0.39,1.41,0L7.05,18.36z"})})}function $(e){return(0,u.jsx)("svg",{viewBox:"0 0 24 24",width:24,height:24,...e,children:(0,u.jsx)("path",{fill:"currentColor",d:"M9.37,5.51C9.19,6.15,9.1,6.82,9.1,7.5c0,4.08,3.32,7.4,7.4,7.4c0.68,0,1.35-0.09,1.99-0.27C17.45,17.19,14.93,19,12,19 c-3.86,0-7-3.14-7-7C5,9.07,6.81,6.55,9.37,5.51z M12,3c-4.97,0-9,4.03-9,9s4.03,9,9,9s9-4.03,9-9c0-0.46-0.04-0.92-0.1-1.36 c-0.98,1.37-2.58,2.26-4.4,2.26c-2.98,0-5.4-2.42-5.4-5.4c0-1.81,0.89-3.42,2.26-4.4C12.92,3.04,12.46,3,12,3L12,3z"})})}const U={toggle:"toggle_vylO",toggleButton:"toggleButton_gllP",darkToggleIcon:"darkToggleIcon_wfgR",lightToggleIcon:"lightToggleIcon_pyhR",toggleButtonDisabled:"toggleButtonDisabled_aARS"};function q(e){let{className:t,buttonClassName:n,value:r,onChange:o}=e;const i=(0,z.A)(),l=(0,s.T)({message:"Switch between dark and light mode (currently {mode})",id:"theme.colorToggle.ariaLabel",description:"The ARIA label for the navbar color mode toggle"},{mode:"dark"===r?(0,s.T)({message:"dark mode",id:"theme.colorToggle.ariaLabel.mode.dark",description:"The name for the dark color mode"}):(0,s.T)({message:"light mode",id:"theme.colorToggle.ariaLabel.mode.light",description:"The name for the light color mode"})});return(0,u.jsx)("div",{className:(0,a.A)(U.toggle,t),children:(0,u.jsxs)("button",{className:(0,a.A)("clean-btn",U.toggleButton,!i&&U.toggleButtonDisabled,n),type:"button",onClick:()=>o("dark"===r?"light":"dark"),disabled:!i,title:l,"aria-label":l,"aria-live":"polite",children:[(0,u.jsx)(B,{className:(0,a.A)(U.toggleIcon,U.lightToggleIcon)}),(0,u.jsx)($,{className:(0,a.A)(U.toggleIcon,U.darkToggleIcon)})]})})}const H=r.memo(q),G={darkNavbarColorModeToggle:"darkNavbarColorModeToggle_X3D1"};function W(e){let{className:t}=e;const n=(0,w.p)().navbar.style,r=(0,w.p)().colorMode.disableSwitch,{colorMode:a,setColorMode:o}=(0,F.G)();return r?null:(0,u.jsx)(H,{className:t,buttonClassName:"dark"===n?G.darkNavbarColorModeToggle:void 0,value:a,onChange:o})}var V=n(3465);function Q(){return(0,u.jsx)(V.A,{className:"navbar__brand",imageClassName:"navbar__logo",titleClassName:"navbar__title text--truncate"})}function K(){const e=(0,j.M)();return(0,u.jsx)("button",{type:"button","aria-label":(0,s.T)({id:"theme.docs.sidebar.closeSidebarButtonAriaLabel",message:"Close navigation bar",description:"The ARIA label for close button of mobile sidebar"}),className:"clean-btn navbar-sidebar__close",onClick:()=>e.toggle(),children:(0,u.jsx)(k,{color:"var(--ifm-color-emphasis-600)"})})}function Y(){return(0,u.jsxs)("div",{className:"navbar-sidebar__brand",children:[(0,u.jsx)(Q,{}),(0,u.jsx)(W,{className:"margin-right--md"}),(0,u.jsx)(K,{})]})}var J=n(5489),Z=n(6025),X=n(6654);function ee(e,t){return void 0!==e&&void 0!==t&&new RegExp(e,"gi").test(t)}var te=n(3186);function ne(e){let{activeBasePath:t,activeBaseRegex:n,to:r,href:a,label:o,html:i,isDropdownLink:l,prependBaseUrlToHref:s,...c}=e;const d=(0,Z.A)(r),p=(0,Z.A)(t),f=(0,Z.A)(a,{forcePrependBaseUrl:!0}),m=o&&a&&!(0,X.A)(a),h=i?{dangerouslySetInnerHTML:{__html:i}}:{children:(0,u.jsxs)(u.Fragment,{children:[o,m&&(0,u.jsx)(te.A,{...l&&{width:12,height:12}})]})};return a?(0,u.jsx)(J.A,{href:s?f:a,...c,...h}):(0,u.jsx)(J.A,{to:d,isNavLink:!0,...(t||n)&&{isActive:(e,t)=>n?ee(n,t.pathname):t.pathname.startsWith(p)},...c,...h})}function re(e){let{className:t,isDropdownItem:n=!1,...r}=e;const o=(0,u.jsx)(ne,{className:(0,a.A)(n?"dropdown__link":"navbar__item navbar__link",t),isDropdownLink:n,...r});return n?(0,u.jsx)("li",{children:o}):o}function ae(e){let{className:t,isDropdownItem:n,...r}=e;return(0,u.jsx)("li",{className:"menu__list-item",children:(0,u.jsx)(ne,{className:(0,a.A)("menu__link",t),...r})})}function oe(e){let{mobile:t=!1,position:n,...r}=e;const a=t?ae:re;return(0,u.jsx)(a,{...r,activeClassName:r.activeClassName??(t?"menu__link--active":"navbar__link--active")})}var ie=n(1422),le=n(9169),se=n(4586);const ce={dropdownNavbarItemMobile:"dropdownNavbarItemMobile_S0Fm"};function ue(e,t){return e.some((e=>function(e,t){return!!(0,le.ys)(e.to,t)||!!ee(e.activeBaseRegex,t)||!(!e.activeBasePath||!t.startsWith(e.activeBasePath))}(e,t)))}function de(e){let{items:t,position:n,className:o,onClick:i,...l}=e;const s=(0,r.useRef)(null),[c,d]=(0,r.useState)(!1);return(0,r.useEffect)((()=>{const e=e=>{s.current&&!s.current.contains(e.target)&&d(!1)};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e),document.addEventListener("focusin",e),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e),document.removeEventListener("focusin",e)}}),[s]),(0,u.jsxs)("div",{ref:s,className:(0,a.A)("navbar__item","dropdown","dropdown--hoverable",{"dropdown--right":"right"===n,"dropdown--show":c}),children:[(0,u.jsx)(ne,{"aria-haspopup":"true","aria-expanded":c,role:"button",href:l.to?void 0:"#",className:(0,a.A)("navbar__link",o),...l,onClick:l.to?void 0:e=>e.preventDefault(),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),d(!c))},children:l.children??l.label}),(0,u.jsx)("ul",{className:"dropdown__menu",children:t.map(((e,t)=>(0,r.createElement)(je,{isDropdownItem:!0,activeClassName:"dropdown__link--active",...e,key:t})))})]})}function pe(e){let{items:t,className:n,position:o,onClick:i,...s}=e;const c=function(){const{siteConfig:{baseUrl:e}}=(0,se.A)(),{pathname:t}=(0,l.zy)();return t.replace(e,"/")}(),d=ue(t,c),{collapsed:p,toggleCollapsed:f,setCollapsed:m}=(0,ie.u)({initialState:()=>!d});return(0,r.useEffect)((()=>{d&&m(!d)}),[c,d,m]),(0,u.jsxs)("li",{className:(0,a.A)("menu__list-item",{"menu__list-item--collapsed":p}),children:[(0,u.jsx)(ne,{role:"button",className:(0,a.A)(ce.dropdownNavbarItemMobile,"menu__link menu__link--sublist menu__link--sublist-caret",n),...s,onClick:e=>{e.preventDefault(),f()},children:s.children??s.label}),(0,u.jsx)(ie.N,{lazy:!0,as:"ul",className:"menu__list",collapsed:p,children:t.map(((e,t)=>(0,r.createElement)(je,{mobile:!0,isDropdownItem:!0,onClick:i,activeClassName:"menu__link--active",...e,key:t})))})]})}function fe(e){let{mobile:t=!1,...n}=e;const r=t?pe:de;return(0,u.jsx)(r,{...n})}var me=n(2131);function he(e){let{width:t=20,height:n=20,...r}=e;return(0,u.jsx)("svg",{viewBox:"0 0 24 24",width:t,height:n,"aria-hidden":!0,...r,children:(0,u.jsx)("path",{fill:"currentColor",d:"M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"})})}const ge="iconLanguage_nlXk";var be=n(6588),ye=n(689),ve=n.n(ye);function we(){const e=(0,l.zy)(),t=(0,l.W6)(),{siteConfig:{baseUrl:n}}=(0,se.A)(),[a,o]=(0,r.useState)({wordToHighlight:"",isTitleSuggestion:!1,titleText:""});return(0,r.useEffect)((()=>{if(!e.state?.highlightState||0===e.state.highlightState.wordToHighlight.length)return;o(e.state.highlightState);const{highlightState:n,...r}=e.state;t.replace({...e,state:r})}),[e.state?.highlightState,t,e]),(0,r.useEffect)((()=>{if(0===a.wordToHighlight.length)return;const e=document.getElementsByTagName("article")[0]??document.getElementsByTagName("main")[0];if(!e)return;const t=new(ve())(e),n={ignoreJoiners:!0};return t.mark(a.wordToHighlight,n),()=>t.unmark(n)}),[a,n]),null}const xe=e=>{const t=(0,r.useRef)(!1),o=(0,r.useRef)(null),[i,s]=(0,r.useState)(!1),c=(0,l.W6)(),{siteConfig:d={}}=(0,se.A)(),p=(d.plugins||[]).find((e=>Array.isArray(e)&&"string"==typeof e[0]&&e[0].includes("docusaurus-lunr-search"))),f=(0,z.A)(),{baseUrl:m}=d,h=p&&p[1]?.assetUrl||m,g=(0,be.P_)("docusaurus-lunr-search"),b=()=>{t.current||(Promise.all([fetch(`${h}${g.fileNames.searchDoc}`).then((e=>e.json())),fetch(`${h}${g.fileNames.lunrIndex}`).then((e=>e.json())),Promise.all([n.e(4250),n.e(7443)]).then(n.bind(n,4004)),Promise.all([n.e(1869),n.e(9187)]).then(n.bind(n,9187))]).then((e=>{let[t,n,{default:r}]=e;const{searchDocs:a,options:o}=t;a&&0!==a.length&&(((e,t,n,r)=>{new n({searchDocs:e,searchIndex:t,baseUrl:m,inputSelector:"#search_input_react",handleSelected:(e,t,n)=>{const a=n.url||"/";document.createElement("a").href=a,e.setVal(""),t.target.blur();let o="";if(r.highlightResult)try{const e=(n.text||n.subcategory||n.title).match(new RegExp("\\w*","g"));if(e&&e.length>0){const t=document.createElement("div");t.innerHTML=e[0],o=t.textContent}}catch(i){console.log(i)}c.push(a,{highlightState:{wordToHighlight:o}})},maxHits:r.maxHits})})(a,n,r,o),s(!0))})),t.current=!0)},y=(0,r.useCallback)((t=>{o.current.contains(t.target)||o.current.focus(),e.handleSearchBarToggle&&e.handleSearchBarToggle(!e.isSearchBarExpanded)}),[e.isSearchBarExpanded]);let v;return f&&(b(),v=window.navigator.platform.startsWith("Mac")?"Search \u2318+K":"Search Ctrl+K"),(0,u.jsxs)("div",{className:"navbar__search",children:[(0,u.jsx)("span",{"aria-label":"expand searchbar",role:"button",className:(0,a.A)("search-icon",{"search-icon-hidden":e.isSearchBarExpanded}),onClick:y,onKeyDown:y,tabIndex:0}),(0,u.jsx)("input",{id:"search_input_react",type:"search",placeholder:i?v:"Loading...","aria-label":"Search",className:(0,a.A)("navbar__search-input",{"search-bar-expanded":e.isSearchBarExpanded},{"search-bar":!e.isSearchBarExpanded}),onClick:b,onMouseOver:b,onFocus:y,onBlur:y,ref:o,disabled:!i}),(0,u.jsx)(we,{})]},"search-box")},ke={navbarSearchContainer:"navbarSearchContainer_Bca1"};function Se(e){let{children:t,className:n}=e;return(0,u.jsx)("div",{className:(0,a.A)(n,ke.navbarSearchContainer),children:t})}var Ee=n(8295),_e=n(1754);var Ce=n(5597);const Te=e=>e.docs.find((t=>t.id===e.mainDocId));const Ae={default:oe,localeDropdown:function(e){let{mobile:t,dropdownItemsBefore:n,dropdownItemsAfter:r,queryString:a="",...o}=e;const{i18n:{currentLocale:i,locales:c,localeConfigs:d}}=(0,se.A)(),p=(0,me.o)(),{search:f,hash:m}=(0,l.zy)(),h=[...n,...c.map((e=>{const n=`${`pathname://${p.createUrl({locale:e,fullyQualified:!1})}`}${f}${m}${a}`;return{label:d[e].label,lang:d[e].htmlLang,to:n,target:"_self",autoAddBaseUrl:!1,className:e===i?t?"menu__link--active":"dropdown__link--active":""}})),...r],g=t?(0,s.T)({message:"Languages",id:"theme.navbar.mobileLanguageDropdown.label",description:"The label for the mobile language switcher dropdown"}):d[i].label;return(0,u.jsx)(fe,{...o,mobile:t,label:(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(he,{className:ge}),g]}),items:h})},search:function(e){let{mobile:t,className:n}=e;return t?null:(0,u.jsx)(Se,{className:n,children:(0,u.jsx)(xe,{})})},dropdown:fe,html:function(e){let{value:t,className:n,mobile:r=!1,isDropdownItem:o=!1}=e;const i=o?"li":"div";return(0,u.jsx)(i,{className:(0,a.A)({navbar__item:!r&&!o,"menu__list-item":r},n),dangerouslySetInnerHTML:{__html:t}})},doc:function(e){let{docId:t,label:n,docsPluginId:r,...a}=e;const{activeDoc:o}=(0,Ee.zK)(r),i=(0,_e.QB)(t,r),l=o?.path===i?.path;return null===i||i.unlisted&&!l?null:(0,u.jsx)(oe,{exact:!0,...a,isActive:()=>l||!!o?.sidebar&&o.sidebar===i.sidebar,label:n??i.id,to:i.path})},docSidebar:function(e){let{sidebarId:t,label:n,docsPluginId:r,...a}=e;const{activeDoc:o}=(0,Ee.zK)(r),i=(0,_e.fW)(t,r).link;if(!i)throw new Error(`DocSidebarNavbarItem: Sidebar with ID "${t}" doesn't have anything to be linked to.`);return(0,u.jsx)(oe,{exact:!0,...a,isActive:()=>o?.sidebar===t,label:n??i.label,to:i.path})},docsVersion:function(e){let{label:t,to:n,docsPluginId:r,...a}=e;const o=(0,_e.Vd)(r)[0],i=t??o.label,l=n??(e=>e.docs.find((t=>t.id===e.mainDocId)))(o).path;return(0,u.jsx)(oe,{...a,label:i,to:l})},docsVersionDropdown:function(e){let{mobile:t,docsPluginId:n,dropdownActiveClassDisabled:r,dropdownItemsBefore:a,dropdownItemsAfter:o,...i}=e;const{search:c,hash:d}=(0,l.zy)(),p=(0,Ee.zK)(n),f=(0,Ee.jh)(n),{savePreferredVersionName:m}=(0,Ce.g1)(n),h=[...a,...f.map((e=>{const t=p.alternateDocVersions[e.name]??Te(e);return{label:e.label,to:`${t.path}${c}${d}`,isActive:()=>e===p.activeVersion,onClick:()=>m(e.name)}})),...o],g=(0,_e.Vd)(n)[0],b=t&&h.length>1?(0,s.T)({id:"theme.navbar.mobileVersionsDropdown.label",message:"Versions",description:"The label for the navbar versions dropdown on mobile view"}):g.label,y=t&&h.length>1?void 0:Te(g).path;return h.length<=1?(0,u.jsx)(oe,{...i,mobile:t,label:b,to:y,isActive:r?()=>!1:void 0}):(0,u.jsx)(fe,{...i,mobile:t,label:b,to:y,items:h,isActive:r?()=>!1:void 0})}};function je(e){let{type:t,...n}=e;const r=function(e,t){return e&&"default"!==e?e:"items"in t?"dropdown":"default"}(t,n),a=Ae[r];if(!a)throw new Error(`No NavbarItem component found for type "${t}".`);return(0,u.jsx)(a,{...n})}function Ne(){const e=(0,j.M)(),t=(0,w.p)().navbar.items;return(0,u.jsx)("ul",{className:"menu__list",children:t.map(((t,n)=>(0,r.createElement)(je,{mobile:!0,...t,onClick:()=>e.toggle(),key:n})))})}function Re(e){return(0,u.jsx)("button",{...e,type:"button",className:"clean-btn navbar-sidebar__back",children:(0,u.jsx)(s.A,{id:"theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel",description:"The label of the back button to return to main menu, inside the mobile navbar sidebar secondary menu (notably used to display the docs sidebar)",children:"\u2190 Back to main menu"})})}function Le(){const e=0===(0,w.p)().navbar.items.length,t=D();return(0,u.jsxs)(u.Fragment,{children:[!e&&(0,u.jsx)(Re,{onClick:()=>t.hide()}),t.content]})}function Pe(){const e=(0,j.M)();var t;return void 0===(t=e.shown)&&(t=!0),(0,r.useEffect)((()=>(document.body.style.overflow=t?"hidden":"visible",()=>{document.body.style.overflow="visible"})),[t]),e.shouldRender?(0,u.jsx)(M,{header:(0,u.jsx)(Y,{}),primaryMenu:(0,u.jsx)(Ne,{}),secondaryMenu:(0,u.jsx)(Le,{})}):null}const Oe={navbarHideable:"navbarHideable_m1mJ",navbarHidden:"navbarHidden_jGov"};function Ie(e){return(0,u.jsx)("div",{role:"presentation",...e,className:(0,a.A)("navbar-sidebar__backdrop",e.className)})}function De(e){let{children:t}=e;const{navbar:{hideOnScroll:n,style:o}}=(0,w.p)(),i=(0,j.M)(),{navbarRef:l,isNavbarVisible:d}=function(e){const[t,n]=(0,r.useState)(e),a=(0,r.useRef)(!1),o=(0,r.useRef)(0),i=(0,r.useCallback)((e=>{null!==e&&(o.current=e.getBoundingClientRect().height)}),[]);return(0,N.Mq)(((t,r)=>{let{scrollY:i}=t;if(!e)return;if(i=l?n(!1):i+c{if(!e)return;const r=t.location.hash;if(r?document.getElementById(r.substring(1)):void 0)return a.current=!0,void n(!1);n(!0)})),{navbarRef:i,isNavbarVisible:t}}(n);return(0,u.jsxs)("nav",{ref:l,"aria-label":(0,s.T)({id:"theme.NavBar.navAriaLabel",message:"Main",description:"The ARIA label for the main navigation"}),className:(0,a.A)("navbar","navbar--fixed-top",n&&[Oe.navbarHideable,!d&&Oe.navbarHidden],{"navbar--dark":"dark"===o,"navbar--primary":"primary"===o,"navbar-sidebar--show":i.shown}),children:[t,(0,u.jsx)(Ie,{onClick:i.toggle}),(0,u.jsx)(Pe,{})]})}var Me=n(440);const Fe={errorBoundaryError:"errorBoundaryError_a6uf",errorBoundaryFallback:"errorBoundaryFallback_VBag"};function ze(e){return(0,u.jsx)("button",{type:"button",...e,children:(0,u.jsx)(s.A,{id:"theme.ErrorPageContent.tryAgain",description:"The label of the button to try again rendering when the React error boundary captures an error",children:"Try again"})})}function Be(e){let{error:t}=e;const n=(0,Me.getErrorCausalChain)(t).map((e=>e.message)).join("\n\nCause:\n");return(0,u.jsx)("p",{className:Fe.errorBoundaryError,children:n})}class $e extends r.Component{componentDidCatch(e,t){throw this.props.onError(e,t)}render(){return this.props.children}}const Ue="right";function qe(e){let{width:t=30,height:n=30,className:r,...a}=e;return(0,u.jsx)("svg",{className:r,width:t,height:n,viewBox:"0 0 30 30","aria-hidden":"true",...a,children:(0,u.jsx)("path",{stroke:"currentColor",strokeLinecap:"round",strokeMiterlimit:"10",strokeWidth:"2",d:"M4 7h22M4 15h22M4 23h22"})})}function He(){const{toggle:e,shown:t}=(0,j.M)();return(0,u.jsx)("button",{onClick:e,"aria-label":(0,s.T)({id:"theme.docs.sidebar.toggleSidebarButtonAriaLabel",message:"Toggle navigation bar",description:"The ARIA label for hamburger menu button of mobile navigation"}),"aria-expanded":t,className:"navbar__toggle clean-btn",type:"button",children:(0,u.jsx)(qe,{})})}const Ge={colorModeToggle:"colorModeToggle_DEke"};function We(e){let{items:t}=e;return(0,u.jsx)(u.Fragment,{children:t.map(((e,t)=>(0,u.jsx)($e,{onError:t=>new Error(`A theme navbar item failed to render.\nPlease double-check the following navbar item (themeConfig.navbar.items) of your Docusaurus config:\n${JSON.stringify(e,null,2)}`,{cause:t}),children:(0,u.jsx)(je,{...e})},t)))})}function Ve(e){let{left:t,right:n}=e;return(0,u.jsxs)("div",{className:"navbar__inner",children:[(0,u.jsx)("div",{className:"navbar__items",children:t}),(0,u.jsx)("div",{className:"navbar__items navbar__items--right",children:n})]})}function Qe(){const e=(0,j.M)(),t=(0,w.p)().navbar.items,[n,r]=function(e){function t(e){return"left"===(e.position??Ue)}return[e.filter(t),e.filter((e=>!t(e)))]}(t),a=t.find((e=>"search"===e.type));return(0,u.jsx)(Ve,{left:(0,u.jsxs)(u.Fragment,{children:[!e.disabled&&(0,u.jsx)(He,{}),(0,u.jsx)(Q,{}),(0,u.jsx)(We,{items:n})]}),right:(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(We,{items:r}),(0,u.jsx)(W,{className:Ge.colorModeToggle}),!a&&(0,u.jsx)(Se,{children:(0,u.jsx)(xe,{})})]})})}function Ke(){return(0,u.jsx)(De,{children:(0,u.jsx)(Qe,{})})}function Ye(e){let{item:t}=e;const{to:n,href:r,label:a,prependBaseUrlToHref:o,...i}=t,l=(0,Z.A)(n),s=(0,Z.A)(r,{forcePrependBaseUrl:!0});return(0,u.jsxs)(J.A,{className:"footer__link-item",...r?{href:o?s:r}:{to:l},...i,children:[a,r&&!(0,X.A)(r)&&(0,u.jsx)(te.A,{})]})}function Je(e){let{item:t}=e;return t.html?(0,u.jsx)("li",{className:"footer__item",dangerouslySetInnerHTML:{__html:t.html}}):(0,u.jsx)("li",{className:"footer__item",children:(0,u.jsx)(Ye,{item:t})},t.href??t.to)}function Ze(e){let{column:t}=e;return(0,u.jsxs)("div",{className:"col footer__col",children:[(0,u.jsx)("div",{className:"footer__title",children:t.title}),(0,u.jsx)("ul",{className:"footer__items clean-list",children:t.items.map(((e,t)=>(0,u.jsx)(Je,{item:e},t)))})]})}function Xe(e){let{columns:t}=e;return(0,u.jsx)("div",{className:"row footer__links",children:t.map(((e,t)=>(0,u.jsx)(Ze,{column:e},t)))})}function et(){return(0,u.jsx)("span",{className:"footer__link-separator",children:"\xb7"})}function tt(e){let{item:t}=e;return t.html?(0,u.jsx)("span",{className:"footer__link-item",dangerouslySetInnerHTML:{__html:t.html}}):(0,u.jsx)(Ye,{item:t})}function nt(e){let{links:t}=e;return(0,u.jsx)("div",{className:"footer__links text--center",children:(0,u.jsx)("div",{className:"footer__links",children:t.map(((e,n)=>(0,u.jsxs)(r.Fragment,{children:[(0,u.jsx)(tt,{item:e}),t.length!==n+1&&(0,u.jsx)(et,{})]},n)))})})}function rt(e){let{links:t}=e;return function(e){return"title"in e[0]}(t)?(0,u.jsx)(Xe,{columns:t}):(0,u.jsx)(nt,{links:t})}var at=n(1122);const ot={footerLogoLink:"footerLogoLink_BH7S"};function it(e){let{logo:t}=e;const{withBaseUrl:n}=(0,Z.h)(),r={light:n(t.src),dark:n(t.srcDark??t.src)};return(0,u.jsx)(at.A,{className:(0,a.A)("footer__logo",t.className),alt:t.alt,sources:r,width:t.width,height:t.height,style:t.style})}function lt(e){let{logo:t}=e;return t.href?(0,u.jsx)(J.A,{href:t.href,className:ot.footerLogoLink,target:t.target,children:(0,u.jsx)(it,{logo:t})}):(0,u.jsx)(it,{logo:t})}function st(e){let{copyright:t}=e;return(0,u.jsx)("div",{className:"footer__copyright",dangerouslySetInnerHTML:{__html:t}})}function ct(e){let{style:t,links:n,logo:r,copyright:o}=e;return(0,u.jsx)("footer",{className:(0,a.A)("footer",{"footer--dark":"dark"===t}),children:(0,u.jsxs)("div",{className:"container container-fluid",children:[n,(r||o)&&(0,u.jsxs)("div",{className:"footer__bottom text--center",children:[r&&(0,u.jsx)("div",{className:"margin-bottom--sm",children:r}),o]})]})})}function ut(){const{footer:e}=(0,w.p)();if(!e)return null;const{copyright:t,links:n,logo:r,style:a}=e;return(0,u.jsx)(ct,{style:a,links:n&&n.length>0&&(0,u.jsx)(rt,{links:n}),logo:r&&(0,u.jsx)(lt,{logo:r}),copyright:t&&(0,u.jsx)(st,{copyright:t})})}const dt=r.memo(ut),pt=(0,R.fM)([F.a,x.oq,N.Tv,Ce.VQ,i.Jx,function(e){let{children:t}=e;return(0,u.jsx)(L.y_,{children:(0,u.jsx)(j.e,{children:(0,u.jsx)(O,{children:t})})})}]);function ft(e){let{children:t}=e;return(0,u.jsx)(pt,{children:t})}var mt=n(1107);function ht(e){let{error:t,tryAgain:n}=e;return(0,u.jsx)("main",{className:"container margin-vert--xl",children:(0,u.jsx)("div",{className:"row",children:(0,u.jsxs)("div",{className:"col col--6 col--offset-3",children:[(0,u.jsx)(mt.A,{as:"h1",className:"hero__title",children:(0,u.jsx)(s.A,{id:"theme.ErrorPageContent.title",description:"The title of the fallback page when the page crashed",children:"This page crashed."})}),(0,u.jsx)("div",{className:"margin-vert--lg",children:(0,u.jsx)(ze,{onClick:n,className:"button button--primary shadow--lw"})}),(0,u.jsx)("hr",{}),(0,u.jsx)("div",{className:"margin-vert--md",children:(0,u.jsx)(Be,{error:t})})]})})})}const gt={mainWrapper:"mainWrapper_z2l0"};function bt(e){const{children:t,noFooter:n,wrapperClassName:r,title:l,description:s}=e;return(0,b.J)(),(0,u.jsxs)(ft,{children:[(0,u.jsx)(i.be,{title:l,description:s}),(0,u.jsx)(v,{}),(0,u.jsx)(A,{}),(0,u.jsx)(Ke,{}),(0,u.jsx)("div",{id:d,className:(0,a.A)(g.G.wrapper.main,gt.mainWrapper,r),children:(0,u.jsx)(o.A,{fallback:e=>(0,u.jsx)(ht,{...e}),children:t})}),!n&&(0,u.jsx)(dt,{})]})}},3465:(e,t,n)=>{"use strict";n.d(t,{A:()=>u});n(6540);var r=n(5489),a=n(6025),o=n(4586),i=n(6342),l=n(1122),s=n(4848);function c(e){let{logo:t,alt:n,imageClassName:r}=e;const o={light:(0,a.A)(t.src),dark:(0,a.A)(t.srcDark||t.src)},i=(0,s.jsx)(l.A,{className:t.className,sources:o,height:t.height,width:t.width,alt:n,style:t.style});return r?(0,s.jsx)("div",{className:r,children:i}):i}function u(e){const{siteConfig:{title:t}}=(0,o.A)(),{navbar:{title:n,logo:l}}=(0,i.p)(),{imageClassName:u,titleClassName:d,...p}=e,f=(0,a.A)(l?.href||"/"),m=n?"":t,h=l?.alt??m;return(0,s.jsxs)(r.A,{to:f,...p,...l?.target&&{target:l.target},children:[l&&(0,s.jsx)(c,{logo:l,alt:h,imageClassName:u}),null!=n&&(0,s.jsx)("b",{className:d,children:n})]})}},1463:(e,t,n)=>{"use strict";n.d(t,{A:()=>o});n(6540);var r=n(5260),a=n(4848);function o(e){let{locale:t,version:n,tag:o}=e;const i=t;return(0,a.jsxs)(r.A,{children:[t&&(0,a.jsx)("meta",{name:"docusaurus_locale",content:t}),n&&(0,a.jsx)("meta",{name:"docusaurus_version",content:n}),o&&(0,a.jsx)("meta",{name:"docusaurus_tag",content:o}),i&&(0,a.jsx)("meta",{name:"docsearch:language",content:i}),n&&(0,a.jsx)("meta",{name:"docsearch:version",content:n}),o&&(0,a.jsx)("meta",{name:"docsearch:docusaurus_tag",content:o})]})}},1122:(e,t,n)=>{"use strict";n.d(t,{A:()=>u});var r=n(6540),a=n(4164),o=n(2303),i=n(5293);const l={themedComponent:"themedComponent_mlkZ","themedComponent--light":"themedComponent--light_NVdE","themedComponent--dark":"themedComponent--dark_xIcU"};var s=n(4848);function c(e){let{className:t,children:n}=e;const c=(0,o.A)(),{colorMode:u}=(0,i.G)();return(0,s.jsx)(s.Fragment,{children:(c?"dark"===u?["dark"]:["light"]:["light","dark"]).map((e=>{const o=n({theme:e,className:(0,a.A)(t,l.themedComponent,l[`themedComponent--${e}`])});return(0,s.jsx)(r.Fragment,{children:o},e)}))})}function u(e){const{sources:t,className:n,alt:r,...a}=e;return(0,s.jsx)(c,{className:n,children:e=>{let{theme:n,className:o}=e;return(0,s.jsx)("img",{src:t[n],alt:r,className:o,...a})}})}},1422:(e,t,n)=>{"use strict";n.d(t,{N:()=>b,u:()=>c});var r=n(6540),a=n(8193),o=n(205),i=n(3109),l=n(4848);const s="ease-in-out";function c(e){let{initialState:t}=e;const[n,a]=(0,r.useState)(t??!1),o=(0,r.useCallback)((()=>{a((e=>!e))}),[]);return{collapsed:n,setCollapsed:a,toggleCollapsed:o}}const u={display:"none",overflow:"hidden",height:"0px"},d={display:"block",overflow:"visible",height:"auto"};function p(e,t){const n=t?u:d;e.style.display=n.display,e.style.overflow=n.overflow,e.style.height=n.height}function f(e){let{collapsibleRef:t,collapsed:n,animation:a}=e;const o=(0,r.useRef)(!1);(0,r.useEffect)((()=>{const e=t.current;function r(){const t=e.scrollHeight,n=a?.duration??function(e){if((0,i.O)())return 1;const t=e/36;return Math.round(10*(4+15*t**.25+t/5))}(t);return{transition:`height ${n}ms ${a?.easing??s}`,height:`${t}px`}}function l(){const t=r();e.style.transition=t.transition,e.style.height=t.height}if(!o.current)return p(e,n),void(o.current=!0);return e.style.willChange="height",function(){const t=requestAnimationFrame((()=>{n?(l(),requestAnimationFrame((()=>{e.style.height=u.height,e.style.overflow=u.overflow}))):(e.style.display="block",requestAnimationFrame((()=>{l()})))}));return()=>cancelAnimationFrame(t)}()}),[t,n,a])}function m(e){if(!a.A.canUseDOM)return e?u:d}function h(e){let{as:t="div",collapsed:n,children:a,animation:o,onCollapseTransitionEnd:i,className:s,disableSSRStyle:c}=e;const u=(0,r.useRef)(null);return f({collapsibleRef:u,collapsed:n,animation:o}),(0,l.jsx)(t,{ref:u,style:c?void 0:m(n),onTransitionEnd:e=>{"height"===e.propertyName&&(p(u.current,n),i?.(n))},className:s,children:a})}function g(e){let{collapsed:t,...n}=e;const[a,i]=(0,r.useState)(!t),[s,c]=(0,r.useState)(t);return(0,o.A)((()=>{t||i(!0)}),[t]),(0,o.A)((()=>{a&&c(t)}),[a,t]),a?(0,l.jsx)(h,{...n,collapsed:s}):null}function b(e){let{lazy:t,...n}=e;const r=t?g:h;return(0,l.jsx)(r,{...n})}},5041:(e,t,n)=>{"use strict";n.d(t,{Mj:()=>h,oq:()=>m});var r=n(6540),a=n(2303),o=n(9466),i=n(9532),l=n(6342),s=n(4848);const c=(0,o.Wf)("docusaurus.announcement.dismiss"),u=(0,o.Wf)("docusaurus.announcement.id"),d=()=>"true"===c.get(),p=e=>c.set(String(e)),f=r.createContext(null);function m(e){let{children:t}=e;const n=function(){const{announcementBar:e}=(0,l.p)(),t=(0,a.A)(),[n,o]=(0,r.useState)((()=>!!t&&d()));(0,r.useEffect)((()=>{o(d())}),[]);const i=(0,r.useCallback)((()=>{p(!0),o(!0)}),[]);return(0,r.useEffect)((()=>{if(!e)return;const{id:t}=e;let n=u.get();"annoucement-bar"===n&&(n="announcement-bar");const r=t!==n;u.set(t),r&&p(!1),!r&&d()||o(!1)}),[e]),(0,r.useMemo)((()=>({isActive:!!e&&!n,close:i})),[e,n,i])}();return(0,s.jsx)(f.Provider,{value:n,children:t})}function h(){const e=(0,r.useContext)(f);if(!e)throw new i.dV("AnnouncementBarProvider");return e}},5293:(e,t,n)=>{"use strict";n.d(t,{G:()=>b,a:()=>g});var r=n(6540),a=n(8193),o=n(9532),i=n(9466),l=n(6342),s=n(4848);const c=r.createContext(void 0),u="theme",d=(0,i.Wf)(u),p={light:"light",dark:"dark"},f=e=>e===p.dark?p.dark:p.light,m=e=>a.A.canUseDOM?f(document.documentElement.getAttribute("data-theme")):f(e),h=e=>{d.set(f(e))};function g(e){let{children:t}=e;const n=function(){const{colorMode:{defaultMode:e,disableSwitch:t,respectPrefersColorScheme:n}}=(0,l.p)(),[a,o]=(0,r.useState)(m(e));(0,r.useEffect)((()=>{t&&d.del()}),[t]);const i=(0,r.useCallback)((function(t,r){void 0===r&&(r={});const{persist:a=!0}=r;t?(o(t),a&&h(t)):(o(n?window.matchMedia("(prefers-color-scheme: dark)").matches?p.dark:p.light:e),d.del())}),[n,e]);(0,r.useEffect)((()=>{document.documentElement.setAttribute("data-theme",f(a))}),[a]),(0,r.useEffect)((()=>{if(t)return;const e=e=>{if(e.key!==u)return;const t=d.get();null!==t&&i(f(t))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)}),[t,i]);const s=(0,r.useRef)(!1);return(0,r.useEffect)((()=>{if(t&&!n)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>{window.matchMedia("print").matches||s.current?s.current=window.matchMedia("print").matches:i(null)};return e.addListener(r),()=>e.removeListener(r)}),[i,t,n]),(0,r.useMemo)((()=>({colorMode:a,setColorMode:i,get isDarkTheme(){return a===p.dark},setLightTheme(){i(p.light)},setDarkTheme(){i(p.dark)}})),[a,i])}();return(0,s.jsx)(c.Provider,{value:n,children:t})}function b(){const e=(0,r.useContext)(c);if(null==e)throw new o.dV("ColorModeProvider","Please see https://docusaurus.io/docs/api/themes/configuration#use-color-mode.");return e}},5597:(e,t,n)=>{"use strict";n.d(t,{VQ:()=>b,g1:()=>v});var r=n(6540),a=n(8295),o=n(7065),i=n(6342),l=n(1754),s=n(9532),c=n(9466),u=n(4848);const d=e=>`docs-preferred-version-${e}`,p={save:(e,t,n)=>{(0,c.Wf)(d(e),{persistence:t}).set(n)},read:(e,t)=>(0,c.Wf)(d(e),{persistence:t}).get(),clear:(e,t)=>{(0,c.Wf)(d(e),{persistence:t}).del()}},f=e=>Object.fromEntries(e.map((e=>[e,{preferredVersionName:null}])));const m=r.createContext(null);function h(){const e=(0,a.Gy)(),t=(0,i.p)().docs.versionPersistence,n=(0,r.useMemo)((()=>Object.keys(e)),[e]),[o,l]=(0,r.useState)((()=>f(n)));(0,r.useEffect)((()=>{l(function(e){let{pluginIds:t,versionPersistence:n,allDocsData:r}=e;function a(e){const t=p.read(e,n);return r[e].versions.some((e=>e.name===t))?{preferredVersionName:t}:(p.clear(e,n),{preferredVersionName:null})}return Object.fromEntries(t.map((e=>[e,a(e)])))}({allDocsData:e,versionPersistence:t,pluginIds:n}))}),[e,t,n]);return[o,(0,r.useMemo)((()=>({savePreferredVersion:function(e,n){p.save(e,t,n),l((t=>({...t,[e]:{preferredVersionName:n}})))}})),[t])]}function g(e){let{children:t}=e;const n=h();return(0,u.jsx)(m.Provider,{value:n,children:t})}function b(e){let{children:t}=e;return l.C5?(0,u.jsx)(g,{children:t}):(0,u.jsx)(u.Fragment,{children:t})}function y(){const e=(0,r.useContext)(m);if(!e)throw new s.dV("DocsPreferredVersionContextProvider");return e}function v(e){void 0===e&&(e=o.W);const t=(0,a.ht)(e),[n,i]=y(),{preferredVersionName:l}=n[e];return{preferredVersion:t.versions.find((e=>e.name===l))??null,savePreferredVersionName:(0,r.useCallback)((t=>{i.savePreferredVersion(e,t)}),[i,e])}}},4207:(e,t,n)=>{"use strict";n.d(t,{V:()=>s,t:()=>c});var r=n(6540),a=n(9532),o=n(4848);const i=Symbol("EmptyContext"),l=r.createContext(i);function s(e){let{children:t,name:n,items:a}=e;const i=(0,r.useMemo)((()=>n&&a?{name:n,items:a}:null),[n,a]);return(0,o.jsx)(l.Provider,{value:i,children:t})}function c(){const e=(0,r.useContext)(l);if(e===i)throw new a.dV("DocsSidebarProvider");return e}},2252:(e,t,n)=>{"use strict";n.d(t,{n:()=>l,r:()=>s});var r=n(6540),a=n(9532),o=n(4848);const i=r.createContext(null);function l(e){let{children:t,version:n}=e;return(0,o.jsx)(i.Provider,{value:n,children:t})}function s(){const e=(0,r.useContext)(i);if(null===e)throw new a.dV("DocsVersionProvider");return e}},9876:(e,t,n)=>{"use strict";n.d(t,{e:()=>f,M:()=>m});var r=n(6540),a=n(5600),o=n(4581),i=n(6347),l=n(9532);function s(e){!function(e){const t=(0,i.W6)(),n=(0,l._q)(e);(0,r.useEffect)((()=>t.block(((e,t)=>n(e,t)))),[t,n])}(((t,n)=>{if("POP"===n)return e(t,n)}))}var c=n(6342),u=n(4848);const d=r.createContext(void 0);function p(){const e=function(){const e=(0,a.YL)(),{items:t}=(0,c.p)().navbar;return 0===t.length&&!e.component}(),t=(0,o.l)(),n=!e&&"mobile"===t,[i,l]=(0,r.useState)(!1);s((()=>{if(i)return l(!1),!1}));const u=(0,r.useCallback)((()=>{l((e=>!e))}),[]);return(0,r.useEffect)((()=>{"desktop"===t&&l(!1)}),[t]),(0,r.useMemo)((()=>({disabled:e,shouldRender:n,toggle:u,shown:i})),[e,n,u,i])}function f(e){let{children:t}=e;const n=p();return(0,u.jsx)(d.Provider,{value:n,children:t})}function m(){const e=r.useContext(d);if(void 0===e)throw new l.dV("NavbarMobileSidebarProvider");return e}},5600:(e,t,n)=>{"use strict";n.d(t,{GX:()=>c,YL:()=>s,y_:()=>l});var r=n(6540),a=n(9532),o=n(4848);const i=r.createContext(null);function l(e){let{children:t}=e;const n=(0,r.useState)({component:null,props:null});return(0,o.jsx)(i.Provider,{value:n,children:t})}function s(){const e=(0,r.useContext)(i);if(!e)throw new a.dV("NavbarSecondaryMenuContentProvider");return e[0]}function c(e){let{component:t,props:n}=e;const o=(0,r.useContext)(i);if(!o)throw new a.dV("NavbarSecondaryMenuContentProvider");const[,l]=o,s=(0,a.Be)(n);return(0,r.useEffect)((()=>{l({component:t,props:s})}),[l,t,s]),(0,r.useEffect)((()=>()=>l({component:null,props:null})),[l]),null}},4090:(e,t,n)=>{"use strict";n.d(t,{w:()=>a,J:()=>o});var r=n(6540);const a="navigation-with-keyboard";function o(){(0,r.useEffect)((()=>{function e(e){"keydown"===e.type&&"Tab"===e.key&&document.body.classList.add(a),"mousedown"===e.type&&document.body.classList.remove(a)}return document.addEventListener("keydown",e),document.addEventListener("mousedown",e),()=>{document.body.classList.remove(a),document.removeEventListener("keydown",e),document.removeEventListener("mousedown",e)}}),[])}},4581:(e,t,n)=>{"use strict";n.d(t,{l:()=>l});var r=n(6540),a=n(8193);const o={desktop:"desktop",mobile:"mobile",ssr:"ssr"},i=996;function l(){const[e,t]=(0,r.useState)((()=>"ssr"));return(0,r.useEffect)((()=>{function e(){t(function(){if(!a.A.canUseDOM)throw new Error("getWindowSize() should only be called after React hydration");return window.innerWidth>i?o.desktop:o.mobile}())}return e(),window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]),e}},7559:(e,t,n)=>{"use strict";n.d(t,{G:()=>r});const r={page:{blogListPage:"blog-list-page",blogPostPage:"blog-post-page",blogTagsListPage:"blog-tags-list-page",blogTagPostListPage:"blog-tags-post-list-page",docsDocPage:"docs-doc-page",docsTagsListPage:"docs-tags-list-page",docsTagDocListPage:"docs-tags-doc-list-page",mdxPage:"mdx-page"},wrapper:{main:"main-wrapper",blogPages:"blog-wrapper",docsPages:"docs-wrapper",mdxPages:"mdx-wrapper"},common:{editThisPage:"theme-edit-this-page",lastUpdated:"theme-last-updated",backToTopButton:"theme-back-to-top-button",codeBlock:"theme-code-block",admonition:"theme-admonition",unlistedBanner:"theme-unlisted-banner",admonitionType:e=>`theme-admonition-${e}`},layout:{},docs:{docVersionBanner:"theme-doc-version-banner",docVersionBadge:"theme-doc-version-badge",docBreadcrumbs:"theme-doc-breadcrumbs",docMarkdown:"theme-doc-markdown",docTocMobile:"theme-doc-toc-mobile",docTocDesktop:"theme-doc-toc-desktop",docFooter:"theme-doc-footer",docFooterTagsRow:"theme-doc-footer-tags-row",docFooterEditMetaRow:"theme-doc-footer-edit-meta-row",docSidebarContainer:"theme-doc-sidebar-container",docSidebarMenu:"theme-doc-sidebar-menu",docSidebarItemCategory:"theme-doc-sidebar-item-category",docSidebarItemLink:"theme-doc-sidebar-item-link",docSidebarItemCategoryLevel:e=>`theme-doc-sidebar-item-category-level-${e}`,docSidebarItemLinkLevel:e=>`theme-doc-sidebar-item-link-level-${e}`},blog:{}}},3109:(e,t,n)=>{"use strict";function r(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}n.d(t,{O:()=>r})},1754:(e,t,n)=>{"use strict";n.d(t,{Nr:()=>f,w8:()=>g,C5:()=>p,B5:()=>E,Vd:()=>x,QB:()=>S,fW:()=>k,OF:()=>w,Y:()=>y});var r=n(6540),a=n(6347),o=n(2831),i=n(8295),l=n(5597),s=n(2252),c=n(4207);function u(e){return Array.from(new Set(e))}var d=n(9169);const p=!!i.Gy;function f(e){return"link"!==e.type||e.unlisted?"category"===e.type?function(e){if(e.href&&!e.linkUnlisted)return e.href;for(const t of e.items){const e=f(t);if(e)return e}}(e):void 0:e.href}const m=(e,t)=>void 0!==e&&(0,d.ys)(e,t),h=(e,t)=>e.some((e=>g(e,t)));function g(e,t){return"link"===e.type?m(e.href,t):"category"===e.type&&(m(e.href,t)||h(e.items,t))}function b(e,t){switch(e.type){case"category":return g(e,t)||e.items.some((e=>b(e,t)));case"link":return!e.unlisted||g(e,t);default:return!0}}function y(e,t){return(0,r.useMemo)((()=>e.filter((e=>b(e,t)))),[e,t])}function v(e){let{sidebarItems:t,pathname:n,onlyCategories:r=!1}=e;const a=[];return function e(t){for(const o of t)if("category"===o.type&&((0,d.ys)(o.href,n)||e(o.items))||"link"===o.type&&(0,d.ys)(o.href,n)){return r&&"category"!==o.type||a.unshift(o),!0}return!1}(t),a}function w(){const e=(0,c.t)(),{pathname:t}=(0,a.zy)(),n=(0,i.vT)()?.pluginData.breadcrumbs;return!1!==n&&e?v({sidebarItems:e.items,pathname:t}):null}function x(e){const{activeVersion:t}=(0,i.zK)(e),{preferredVersion:n}=(0,l.g1)(e),a=(0,i.r7)(e);return(0,r.useMemo)((()=>u([t,n,a].filter(Boolean))),[t,n,a])}function k(e,t){const n=x(t);return(0,r.useMemo)((()=>{const t=n.flatMap((e=>e.sidebars?Object.entries(e.sidebars):[])),r=t.find((t=>t[0]===e));if(!r)throw new Error(`Can't find any sidebar with id "${e}" in version${n.length>1?"s":""} ${n.map((e=>e.name)).join(", ")}".\nAvailable sidebar ids are:\n- ${t.map((e=>e[0])).join("\n- ")}`);return r[1]}),[e,n])}function S(e,t){const n=x(t);return(0,r.useMemo)((()=>{const t=n.flatMap((e=>e.docs)),r=t.find((t=>t.id===e));if(!r){if(n.flatMap((e=>e.draftIds)).includes(e))return null;throw new Error(`Couldn't find any doc with id "${e}" in version${n.length>1?"s":""} "${n.map((e=>e.name)).join(", ")}".\nAvailable doc ids are:\n- ${u(t.map((e=>e.id))).join("\n- ")}`)}return r}),[e,n])}function E(e){let{route:t}=e;const n=(0,a.zy)(),r=(0,s.r)(),i=t.routes,l=i.find((e=>(0,a.B6)(n.pathname,e)));if(!l)return null;const c=l.sidebar,u=c?r.docsSidebars[c]:void 0;return{docElement:(0,o.v)(i),sidebarName:c,sidebarItems:u}}},1003:(e,t,n)=>{"use strict";n.d(t,{e3:()=>f,be:()=>d,Jx:()=>m});var r=n(6540),a=n(4164),o=n(5260),i=n(3102);function l(){const e=r.useContext(i.o);if(!e)throw new Error("Unexpected: no Docusaurus route context found");return e}var s=n(6025),c=n(4586);var u=n(4848);function d(e){let{title:t,description:n,keywords:r,image:a,children:i}=e;const l=function(e){const{siteConfig:t}=(0,c.A)(),{title:n,titleDelimiter:r}=t;return e?.trim().length?`${e.trim()} ${r} ${n}`:n}(t),{withBaseUrl:d}=(0,s.h)(),p=a?d(a,{absolute:!0}):void 0;return(0,u.jsxs)(o.A,{children:[t&&(0,u.jsx)("title",{children:l}),t&&(0,u.jsx)("meta",{property:"og:title",content:l}),n&&(0,u.jsx)("meta",{name:"description",content:n}),n&&(0,u.jsx)("meta",{property:"og:description",content:n}),r&&(0,u.jsx)("meta",{name:"keywords",content:Array.isArray(r)?r.join(","):r}),p&&(0,u.jsx)("meta",{property:"og:image",content:p}),p&&(0,u.jsx)("meta",{name:"twitter:image",content:p}),i]})}const p=r.createContext(void 0);function f(e){let{className:t,children:n}=e;const i=r.useContext(p),l=(0,a.A)(i,t);return(0,u.jsxs)(p.Provider,{value:l,children:[(0,u.jsx)(o.A,{children:(0,u.jsx)("html",{className:l})}),n]})}function m(e){let{children:t}=e;const n=l(),r=`plugin-${n.plugin.name.replace(/docusaurus-(?:plugin|theme)-(?:content-)?/gi,"")}`;const o=`plugin-id-${n.plugin.id}`;return(0,u.jsx)(f,{className:(0,a.A)(r,o),children:t})}},9532:(e,t,n)=>{"use strict";n.d(t,{Be:()=>c,ZC:()=>l,_q:()=>i,dV:()=>s,fM:()=>u});var r=n(6540),a=n(205),o=n(4848);function i(e){const t=(0,r.useRef)(e);return(0,a.A)((()=>{t.current=e}),[e]),(0,r.useCallback)((function(){return t.current(...arguments)}),[])}function l(e){const t=(0,r.useRef)();return(0,a.A)((()=>{t.current=e})),t.current}class s extends Error{constructor(e,t){super(),this.name="ReactContextError",this.message=`Hook ${this.stack?.split("\n")[1]?.match(/at (?:\w+\.)?(?\w+)/)?.groups.name??""} is called outside the <${e}>. ${t??""}`}}function c(e){const t=Object.entries(e);return t.sort(((e,t)=>e[0].localeCompare(t[0]))),(0,r.useMemo)((()=>e),t.flat())}function u(e){return t=>{let{children:n}=t;return(0,o.jsx)(o.Fragment,{children:e.reduceRight(((e,t)=>(0,o.jsx)(t,{children:e})),n)})}}},9169:(e,t,n)=>{"use strict";n.d(t,{Dt:()=>l,ys:()=>i});var r=n(6540),a=n(8328),o=n(4586);function i(e,t){const n=e=>(!e||e.endsWith("/")?e:`${e}/`)?.toLowerCase();return n(e)===n(t)}function l(){const{baseUrl:e}=(0,o.A)().siteConfig;return(0,r.useMemo)((()=>function(e){let{baseUrl:t,routes:n}=e;function r(e){return e.path===t&&!0===e.exact}function a(e){return e.path===t&&!e.exact}return function e(t){if(0===t.length)return;return t.find(r)||e(t.filter(a).flatMap((e=>e.routes??[])))}(n)}({routes:a.A,baseUrl:e})),[e])}},3104:(e,t,n)=>{"use strict";n.d(t,{Mq:()=>p,Tv:()=>c,gk:()=>f});var r=n(6540),a=n(8193),o=n(2303),i=(n(205),n(9532)),l=n(4848);const s=r.createContext(void 0);function c(e){let{children:t}=e;const n=function(){const e=(0,r.useRef)(!0);return(0,r.useMemo)((()=>({scrollEventsEnabledRef:e,enableScrollEvents:()=>{e.current=!0},disableScrollEvents:()=>{e.current=!1}})),[])}();return(0,l.jsx)(s.Provider,{value:n,children:t})}function u(){const e=(0,r.useContext)(s);if(null==e)throw new i.dV("ScrollControllerProvider");return e}const d=()=>a.A.canUseDOM?{scrollX:window.pageXOffset,scrollY:window.pageYOffset}:null;function p(e,t){void 0===t&&(t=[]);const{scrollEventsEnabledRef:n}=u(),a=(0,r.useRef)(d()),o=(0,i._q)(e);(0,r.useEffect)((()=>{const e=()=>{if(!n.current)return;const e=d();o(e,a.current),a.current=e},t={passive:!0};return e(),window.addEventListener("scroll",e,t),()=>window.removeEventListener("scroll",e,t)}),[o,n,...t])}function f(){const e=(0,r.useRef)(null),t=(0,o.A)()&&"smooth"===getComputedStyle(document.documentElement).scrollBehavior;return{startScroll:n=>{e.current=t?function(e){return window.scrollTo({top:e,behavior:"smooth"}),()=>{}}(n):function(e){let t=null;const n=document.documentElement.scrollTop>e;return function r(){const a=document.documentElement.scrollTop;(n&&a>e||!n&&at&&cancelAnimationFrame(t)}(n)},cancelScroll:()=>e.current?.()}}},2967:(e,t,n)=>{"use strict";n.d(t,{Cy:()=>r,tU:()=>a});n(4586);const r="default";function a(e,t){return`docs-${e}-${t}`}},9466:(e,t,n)=>{"use strict";n.d(t,{Wf:()=>s});n(6540);const r="localStorage";function a(e){let{key:t,oldValue:n,newValue:r,storage:a}=e;if(n===r)return;const o=document.createEvent("StorageEvent");o.initStorageEvent("storage",!1,!1,t,n,r,window.location.href,a),window.dispatchEvent(o)}function o(e){if(void 0===e&&(e=r),"undefined"==typeof window)throw new Error("Browser storage is not available on Node.js/Docusaurus SSR process.");if("none"===e)return null;try{return window[e]}catch(n){return t=n,i||(console.warn("Docusaurus browser storage is not available.\nPossible reasons: running Docusaurus in an iframe, in an incognito browser session, or using too strict browser privacy settings.",t),i=!0),null}var t}let i=!1;const l={get:()=>null,set:()=>{},del:()=>{},listen:()=>()=>{}};function s(e,t){if("undefined"==typeof window)return function(e){function t(){throw new Error(`Illegal storage API usage for storage key "${e}".\nDocusaurus storage APIs are not supposed to be called on the server-rendering process.\nPlease only call storage APIs in effects and event handlers.`)}return{get:t,set:t,del:t,listen:t}}(e);const n=o(t?.persistence);return null===n?l:{get:()=>{try{return n.getItem(e)}catch(t){return console.error(`Docusaurus storage error, can't get key=${e}`,t),null}},set:t=>{try{const r=n.getItem(e);n.setItem(e,t),a({key:e,oldValue:r,newValue:t,storage:n})}catch(r){console.error(`Docusaurus storage error, can't set ${e}=${t}`,r)}},del:()=>{try{const t=n.getItem(e);n.removeItem(e),a({key:e,oldValue:t,newValue:null,storage:n})}catch(t){console.error(`Docusaurus storage error, can't delete key=${e}`,t)}},listen:t=>{try{const r=r=>{r.storageArea===n&&r.key===e&&t(r)};return window.addEventListener("storage",r),()=>window.removeEventListener("storage",r)}catch(r){return console.error(`Docusaurus storage error, can't listen for changes of key=${e}`,r),()=>{}}}}}},2131:(e,t,n)=>{"use strict";n.d(t,{o:()=>i});var r=n(4586),a=n(6347),o=n(440);function i(){const{siteConfig:{baseUrl:e,url:t,trailingSlash:n},i18n:{defaultLocale:i,currentLocale:l}}=(0,r.A)(),{pathname:s}=(0,a.zy)(),c=(0,o.applyTrailingSlash)(s,{trailingSlash:n,baseUrl:e}),u=l===i?e:e.replace(`/${l}/`,"/"),d=c.replace(e,"");return{createUrl:function(e){let{locale:n,fullyQualified:r}=e;return`${r?t:""}${function(e){return e===i?`${u}`:`${u}${e}/`}(n)}${d}`}}}},5062:(e,t,n)=>{"use strict";n.d(t,{$:()=>i});var r=n(6540),a=n(6347),o=n(9532);function i(e){const t=(0,a.zy)(),n=(0,o.ZC)(t),i=(0,o._q)(e);(0,r.useEffect)((()=>{n&&t!==n&&i({location:t,previousLocation:n})}),[i,t,n])}},6342:(e,t,n)=>{"use strict";n.d(t,{p:()=>a});var r=n(4586);function a(){return(0,r.A)().siteConfig.themeConfig}},2983:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){const{trailingSlash:n,baseUrl:r}=t;if(e.startsWith("#"))return e;if(void 0===n)return e;const[a]=e.split(/[#?]/),o="/"===a||a===r?a:(i=a,n?function(e){return e.endsWith("/")?e:`${e}/`}(i):function(e){return e.endsWith("/")?e.slice(0,-1):e}(i));var i;return e.replace(a,o)}},253:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorCausalChain=void 0,t.getErrorCausalChain=function e(t){return t.cause?[t,...e(t.cause)]:[t]}},440:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorCausalChain=t.applyTrailingSlash=t.blogPostContainerID=void 0,t.blogPostContainerID="__blog-post-container";var a=n(2983);Object.defineProperty(t,"applyTrailingSlash",{enumerable:!0,get:function(){return r(a).default}});var o=n(253);Object.defineProperty(t,"getErrorCausalChain",{enumerable:!0,get:function(){return o.getErrorCausalChain}})},1513:(e,t,n)=>{"use strict";n.d(t,{zR:()=>w,TM:()=>C,yJ:()=>f,sC:()=>A,AO:()=>p});var r=n(8168);function a(e){return"/"===e.charAt(0)}function o(e,t){for(var n=t,r=n+1,a=e.length;r=0;p--){var f=i[p];"."===f?o(i,p):".."===f?(o(i,p),d++):d&&(o(i,p),d--)}if(!c)for(;d--;d)i.unshift("..");!c||""===i[0]||i[0]&&a(i[0])||i.unshift("");var m=i.join("/");return n&&"/"!==m.substr(-1)&&(m+="/"),m};var l=n(1561);function s(e){return"/"===e.charAt(0)?e:"/"+e}function c(e){return"/"===e.charAt(0)?e.substr(1):e}function u(e,t){return function(e,t){return 0===e.toLowerCase().indexOf(t.toLowerCase())&&-1!=="/?#".indexOf(e.charAt(t.length))}(e,t)?e.substr(t.length):e}function d(e){return"/"===e.charAt(e.length-1)?e.slice(0,-1):e}function p(e){var t=e.pathname,n=e.search,r=e.hash,a=t||"/";return n&&"?"!==n&&(a+="?"===n.charAt(0)?n:"?"+n),r&&"#"!==r&&(a+="#"===r.charAt(0)?r:"#"+r),a}function f(e,t,n,a){var o;"string"==typeof e?(o=function(e){var t=e||"/",n="",r="",a=t.indexOf("#");-1!==a&&(r=t.substr(a),t=t.substr(0,a));var o=t.indexOf("?");return-1!==o&&(n=t.substr(o),t=t.substr(0,o)),{pathname:t,search:"?"===n?"":n,hash:"#"===r?"":r}}(e),o.state=t):(void 0===(o=(0,r.A)({},e)).pathname&&(o.pathname=""),o.search?"?"!==o.search.charAt(0)&&(o.search="?"+o.search):o.search="",o.hash?"#"!==o.hash.charAt(0)&&(o.hash="#"+o.hash):o.hash="",void 0!==t&&void 0===o.state&&(o.state=t));try{o.pathname=decodeURI(o.pathname)}catch(l){throw l instanceof URIError?new URIError('Pathname "'+o.pathname+'" could not be decoded. This is likely caused by an invalid percent-encoding.'):l}return n&&(o.key=n),a?o.pathname?"/"!==o.pathname.charAt(0)&&(o.pathname=i(o.pathname,a.pathname)):o.pathname=a.pathname:o.pathname||(o.pathname="/"),o}function m(){var e=null;var t=[];return{setPrompt:function(t){return e=t,function(){e===t&&(e=null)}},confirmTransitionTo:function(t,n,r,a){if(null!=e){var o="function"==typeof e?e(t,n):e;"string"==typeof o?"function"==typeof r?r(o,a):a(!0):a(!1!==o)}else a(!0)},appendListener:function(e){var n=!0;function r(){n&&e.apply(void 0,arguments)}return t.push(r),function(){n=!1,t=t.filter((function(e){return e!==r}))}},notifyListeners:function(){for(var e=arguments.length,n=new Array(e),r=0;rt?n.splice(t,n.length-t,a):n.push(a),d({action:r,location:a,index:t,entries:n})}}))},replace:function(e,t){var r="REPLACE",a=f(e,t,h(),w.location);u.confirmTransitionTo(a,r,n,(function(e){e&&(w.entries[w.index]=a,d({action:r,location:a}))}))},go:v,goBack:function(){v(-1)},goForward:function(){v(1)},canGo:function(e){var t=w.index+e;return t>=0&&t{"use strict";var r=n(4363),a={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},o={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},i={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},l={};function s(e){return r.isMemo(e)?i:l[e.$$typeof]||a}l[r.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},l[r.Memo]=i;var c=Object.defineProperty,u=Object.getOwnPropertyNames,d=Object.getOwnPropertySymbols,p=Object.getOwnPropertyDescriptor,f=Object.getPrototypeOf,m=Object.prototype;e.exports=function e(t,n,r){if("string"!=typeof n){if(m){var a=f(n);a&&a!==m&&e(t,a,r)}var i=u(n);d&&(i=i.concat(d(n)));for(var l=s(t),h=s(n),g=0;g{"use strict";e.exports=function(e,t,n,r,a,o,i,l){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,a,o,i,l],u=0;(s=new Error(t.replace(/%s/g,(function(){return c[u++]})))).name="Invariant Violation"}throw s.framesToPop=1,s}}},4634:e=>{e.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}},689:function(e){e.exports=function(){"use strict";var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},n=function(){function e(e,t){for(var n=0;n1&&void 0!==arguments[1])||arguments[1],a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:5e3;t(this,e),this.ctx=n,this.iframes=r,this.exclude=a,this.iframesTimeout=o}return n(e,[{key:"getContexts",value:function(){var e=[];return(void 0!==this.ctx&&this.ctx?NodeList.prototype.isPrototypeOf(this.ctx)?Array.prototype.slice.call(this.ctx):Array.isArray(this.ctx)?this.ctx:"string"==typeof this.ctx?Array.prototype.slice.call(document.querySelectorAll(this.ctx)):[this.ctx]:[]).forEach((function(t){var n=e.filter((function(e){return e.contains(t)})).length>0;-1!==e.indexOf(t)||n||e.push(t)})),e}},{key:"getIframeContents",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){},r=void 0;try{var a=e.contentWindow;if(r=a.document,!a||!r)throw new Error("iframe inaccessible")}catch(o){n()}r&&t(r)}},{key:"isIframeBlank",value:function(e){var t="about:blank",n=e.getAttribute("src").trim();return e.contentWindow.location.href===t&&n!==t&&n}},{key:"observeIframeLoad",value:function(e,t,n){var r=this,a=!1,o=null,i=function i(){if(!a){a=!0,clearTimeout(o);try{r.isIframeBlank(e)||(e.removeEventListener("load",i),r.getIframeContents(e,t,n))}catch(l){n()}}};e.addEventListener("load",i),o=setTimeout(i,this.iframesTimeout)}},{key:"onIframeReady",value:function(e,t,n){try{"complete"===e.contentWindow.document.readyState?this.isIframeBlank(e)?this.observeIframeLoad(e,t,n):this.getIframeContents(e,t,n):this.observeIframeLoad(e,t,n)}catch(r){n()}}},{key:"waitForIframes",value:function(e,t){var n=this,r=0;this.forEachIframe(e,(function(){return!0}),(function(e){r++,n.waitForIframes(e.querySelector("html"),(function(){--r||t()}))}),(function(e){e||t()}))}},{key:"forEachIframe",value:function(t,n,r){var a=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},i=t.querySelectorAll("iframe"),l=i.length,s=0;i=Array.prototype.slice.call(i);var c=function(){--l<=0&&o(s)};l||c(),i.forEach((function(t){e.matches(t,a.exclude)?c():a.onIframeReady(t,(function(e){n(t)&&(s++,r(e)),c()}),c)}))}},{key:"createIterator",value:function(e,t,n){return document.createNodeIterator(e,t,n,!1)}},{key:"createInstanceOnIframe",value:function(t){return new e(t.querySelector("html"),this.iframes)}},{key:"compareNodeIframe",value:function(e,t,n){if(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING){if(null===t)return!0;if(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)return!0}return!1}},{key:"getIteratorNode",value:function(e){var t=e.previousNode();return{prevNode:t,node:(null===t||e.nextNode())&&e.nextNode()}}},{key:"checkIframeFilter",value:function(e,t,n,r){var a=!1,o=!1;return r.forEach((function(e,t){e.val===n&&(a=t,o=e.handled)})),this.compareNodeIframe(e,t,n)?(!1!==a||o?!1===a||o||(r[a].handled=!0):r.push({val:n,handled:!0}),!0):(!1===a&&r.push({val:n,handled:!1}),!1)}},{key:"handleOpenIframes",value:function(e,t,n,r){var a=this;e.forEach((function(e){e.handled||a.getIframeContents(e.val,(function(e){a.createInstanceOnIframe(e).forEachNode(t,n,r)}))}))}},{key:"iterateThroughNodes",value:function(e,t,n,r,a){for(var o=this,i=this.createIterator(t,e,r),l=[],s=[],c=void 0,u=void 0,d=function(){var e=o.getIteratorNode(i);return u=e.prevNode,c=e.node};d();)this.iframes&&this.forEachIframe(t,(function(e){return o.checkIframeFilter(c,u,e,l)}),(function(t){o.createInstanceOnIframe(t).forEachNode(e,(function(e){return s.push(e)}),r)})),s.push(c);s.forEach((function(e){n(e)})),this.iframes&&this.handleOpenIframes(l,e,n,r),a()}},{key:"forEachNode",value:function(e,t,n){var r=this,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},o=this.getContexts(),i=o.length;i||a(),o.forEach((function(o){var l=function(){r.iterateThroughNodes(e,o,t,n,(function(){--i<=0&&a()}))};r.iframes?r.waitForIframes(o,l):l()}))}}],[{key:"matches",value:function(e,t){var n="string"==typeof t?[t]:t,r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector;if(r){var a=!1;return n.every((function(t){return!r.call(e,t)||(a=!0,!1)})),a}return!1}}]),e}(),o=function(){function o(e){t(this,o),this.ctx=e,this.ie=!1;var n=window.navigator.userAgent;(n.indexOf("MSIE")>-1||n.indexOf("Trident")>-1)&&(this.ie=!0)}return n(o,[{key:"log",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"debug",r=this.opt.log;this.opt.debug&&"object"===(void 0===r?"undefined":e(r))&&"function"==typeof r[n]&&r[n]("mark.js: "+t)}},{key:"escapeStr",value:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}},{key:"createRegExp",value:function(e){return"disabled"!==this.opt.wildcards&&(e=this.setupWildcardsRegExp(e)),e=this.escapeStr(e),Object.keys(this.opt.synonyms).length&&(e=this.createSynonymsRegExp(e)),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),this.opt.diacritics&&(e=this.createDiacriticsRegExp(e)),e=this.createMergedBlanksRegExp(e),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.createJoinersRegExp(e)),"disabled"!==this.opt.wildcards&&(e=this.createWildcardsRegExp(e)),e=this.createAccuracyRegExp(e)}},{key:"createSynonymsRegExp",value:function(e){var t=this.opt.synonyms,n=this.opt.caseSensitive?"":"i",r=this.opt.ignoreJoiners||this.opt.ignorePunctuation.length?"\0":"";for(var a in t)if(t.hasOwnProperty(a)){var o=t[a],i="disabled"!==this.opt.wildcards?this.setupWildcardsRegExp(a):this.escapeStr(a),l="disabled"!==this.opt.wildcards?this.setupWildcardsRegExp(o):this.escapeStr(o);""!==i&&""!==l&&(e=e.replace(new RegExp("("+this.escapeStr(i)+"|"+this.escapeStr(l)+")","gm"+n),r+"("+this.processSynomyms(i)+"|"+this.processSynomyms(l)+")"+r))}return e}},{key:"processSynomyms",value:function(e){return(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),e}},{key:"setupWildcardsRegExp",value:function(e){return(e=e.replace(/(?:\\)*\?/g,(function(e){return"\\"===e.charAt(0)?"?":"\x01"}))).replace(/(?:\\)*\*/g,(function(e){return"\\"===e.charAt(0)?"*":"\x02"}))}},{key:"createWildcardsRegExp",value:function(e){var t="withSpaces"===this.opt.wildcards;return e.replace(/\u0001/g,t?"[\\S\\s]?":"\\S?").replace(/\u0002/g,t?"[\\S\\s]*?":"\\S*")}},{key:"setupIgnoreJoinersRegExp",value:function(e){return e.replace(/[^(|)\\]/g,(function(e,t,n){var r=n.charAt(t+1);return/[(|)\\]/.test(r)||""===r?e:e+"\0"}))}},{key:"createJoinersRegExp",value:function(e){var t=[],n=this.opt.ignorePunctuation;return Array.isArray(n)&&n.length&&t.push(this.escapeStr(n.join(""))),this.opt.ignoreJoiners&&t.push("\\u00ad\\u200b\\u200c\\u200d"),t.length?e.split(/\u0000+/).join("["+t.join("")+"]*"):e}},{key:"createDiacriticsRegExp",value:function(e){var t=this.opt.caseSensitive?"":"i",n=this.opt.caseSensitive?["a\xe0\xe1\u1ea3\xe3\u1ea1\u0103\u1eb1\u1eaf\u1eb3\u1eb5\u1eb7\xe2\u1ea7\u1ea5\u1ea9\u1eab\u1ead\xe4\xe5\u0101\u0105","A\xc0\xc1\u1ea2\xc3\u1ea0\u0102\u1eb0\u1eae\u1eb2\u1eb4\u1eb6\xc2\u1ea6\u1ea4\u1ea8\u1eaa\u1eac\xc4\xc5\u0100\u0104","c\xe7\u0107\u010d","C\xc7\u0106\u010c","d\u0111\u010f","D\u0110\u010e","e\xe8\xe9\u1ebb\u1ebd\u1eb9\xea\u1ec1\u1ebf\u1ec3\u1ec5\u1ec7\xeb\u011b\u0113\u0119","E\xc8\xc9\u1eba\u1ebc\u1eb8\xca\u1ec0\u1ebe\u1ec2\u1ec4\u1ec6\xcb\u011a\u0112\u0118","i\xec\xed\u1ec9\u0129\u1ecb\xee\xef\u012b","I\xcc\xcd\u1ec8\u0128\u1eca\xce\xcf\u012a","l\u0142","L\u0141","n\xf1\u0148\u0144","N\xd1\u0147\u0143","o\xf2\xf3\u1ecf\xf5\u1ecd\xf4\u1ed3\u1ed1\u1ed5\u1ed7\u1ed9\u01a1\u1edf\u1ee1\u1edb\u1edd\u1ee3\xf6\xf8\u014d","O\xd2\xd3\u1ece\xd5\u1ecc\xd4\u1ed2\u1ed0\u1ed4\u1ed6\u1ed8\u01a0\u1ede\u1ee0\u1eda\u1edc\u1ee2\xd6\xd8\u014c","r\u0159","R\u0158","s\u0161\u015b\u0219\u015f","S\u0160\u015a\u0218\u015e","t\u0165\u021b\u0163","T\u0164\u021a\u0162","u\xf9\xfa\u1ee7\u0169\u1ee5\u01b0\u1eeb\u1ee9\u1eed\u1eef\u1ef1\xfb\xfc\u016f\u016b","U\xd9\xda\u1ee6\u0168\u1ee4\u01af\u1eea\u1ee8\u1eec\u1eee\u1ef0\xdb\xdc\u016e\u016a","y\xfd\u1ef3\u1ef7\u1ef9\u1ef5\xff","Y\xdd\u1ef2\u1ef6\u1ef8\u1ef4\u0178","z\u017e\u017c\u017a","Z\u017d\u017b\u0179"]:["a\xe0\xe1\u1ea3\xe3\u1ea1\u0103\u1eb1\u1eaf\u1eb3\u1eb5\u1eb7\xe2\u1ea7\u1ea5\u1ea9\u1eab\u1ead\xe4\xe5\u0101\u0105A\xc0\xc1\u1ea2\xc3\u1ea0\u0102\u1eb0\u1eae\u1eb2\u1eb4\u1eb6\xc2\u1ea6\u1ea4\u1ea8\u1eaa\u1eac\xc4\xc5\u0100\u0104","c\xe7\u0107\u010dC\xc7\u0106\u010c","d\u0111\u010fD\u0110\u010e","e\xe8\xe9\u1ebb\u1ebd\u1eb9\xea\u1ec1\u1ebf\u1ec3\u1ec5\u1ec7\xeb\u011b\u0113\u0119E\xc8\xc9\u1eba\u1ebc\u1eb8\xca\u1ec0\u1ebe\u1ec2\u1ec4\u1ec6\xcb\u011a\u0112\u0118","i\xec\xed\u1ec9\u0129\u1ecb\xee\xef\u012bI\xcc\xcd\u1ec8\u0128\u1eca\xce\xcf\u012a","l\u0142L\u0141","n\xf1\u0148\u0144N\xd1\u0147\u0143","o\xf2\xf3\u1ecf\xf5\u1ecd\xf4\u1ed3\u1ed1\u1ed5\u1ed7\u1ed9\u01a1\u1edf\u1ee1\u1edb\u1edd\u1ee3\xf6\xf8\u014dO\xd2\xd3\u1ece\xd5\u1ecc\xd4\u1ed2\u1ed0\u1ed4\u1ed6\u1ed8\u01a0\u1ede\u1ee0\u1eda\u1edc\u1ee2\xd6\xd8\u014c","r\u0159R\u0158","s\u0161\u015b\u0219\u015fS\u0160\u015a\u0218\u015e","t\u0165\u021b\u0163T\u0164\u021a\u0162","u\xf9\xfa\u1ee7\u0169\u1ee5\u01b0\u1eeb\u1ee9\u1eed\u1eef\u1ef1\xfb\xfc\u016f\u016bU\xd9\xda\u1ee6\u0168\u1ee4\u01af\u1eea\u1ee8\u1eec\u1eee\u1ef0\xdb\xdc\u016e\u016a","y\xfd\u1ef3\u1ef7\u1ef9\u1ef5\xffY\xdd\u1ef2\u1ef6\u1ef8\u1ef4\u0178","z\u017e\u017c\u017aZ\u017d\u017b\u0179"],r=[];return e.split("").forEach((function(a){n.every((function(n){if(-1!==n.indexOf(a)){if(r.indexOf(n)>-1)return!1;e=e.replace(new RegExp("["+n+"]","gm"+t),"["+n+"]"),r.push(n)}return!0}))})),e}},{key:"createMergedBlanksRegExp",value:function(e){return e.replace(/[\s]+/gim,"[\\s]+")}},{key:"createAccuracyRegExp",value:function(e){var t=this,n="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\xa1\xbf",r=this.opt.accuracy,a="string"==typeof r?r:r.value,o="string"==typeof r?[]:r.limiters,i="";switch(o.forEach((function(e){i+="|"+t.escapeStr(e)})),a){case"partially":default:return"()("+e+")";case"complementary":return"()([^"+(i="\\s"+(i||this.escapeStr(n)))+"]*"+e+"[^"+i+"]*)";case"exactly":return"(^|\\s"+i+")("+e+")(?=$|\\s"+i+")"}}},{key:"getSeparatedKeywords",value:function(e){var t=this,n=[];return e.forEach((function(e){t.opt.separateWordSearch?e.split(" ").forEach((function(e){e.trim()&&-1===n.indexOf(e)&&n.push(e)})):e.trim()&&-1===n.indexOf(e)&&n.push(e)})),{keywords:n.sort((function(e,t){return t.length-e.length})),length:n.length}}},{key:"isNumeric",value:function(e){return Number(parseFloat(e))==e}},{key:"checkRanges",value:function(e){var t=this;if(!Array.isArray(e)||"[object Object]"!==Object.prototype.toString.call(e[0]))return this.log("markRanges() will only accept an array of objects"),this.opt.noMatch(e),[];var n=[],r=0;return e.sort((function(e,t){return e.start-t.start})).forEach((function(e){var a=t.callNoMatchOnInvalidRanges(e,r),o=a.start,i=a.end;a.valid&&(e.start=o,e.length=i-o,n.push(e),r=i)})),n}},{key:"callNoMatchOnInvalidRanges",value:function(e,t){var n=void 0,r=void 0,a=!1;return e&&void 0!==e.start?(r=(n=parseInt(e.start,10))+parseInt(e.length,10),this.isNumeric(e.start)&&this.isNumeric(e.length)&&r-t>0&&r-n>0?a=!0:(this.log("Ignoring invalid or overlapping range: "+JSON.stringify(e)),this.opt.noMatch(e))):(this.log("Ignoring invalid range: "+JSON.stringify(e)),this.opt.noMatch(e)),{start:n,end:r,valid:a}}},{key:"checkWhitespaceRanges",value:function(e,t,n){var r=void 0,a=!0,o=n.length,i=t-o,l=parseInt(e.start,10)-i;return(r=(l=l>o?o:l)+parseInt(e.length,10))>o&&(r=o,this.log("End range automatically set to the max value of "+o)),l<0||r-l<0||l>o||r>o?(a=!1,this.log("Invalid range: "+JSON.stringify(e)),this.opt.noMatch(e)):""===n.substring(l,r).replace(/\s+/g,"")&&(a=!1,this.log("Skipping whitespace only range: "+JSON.stringify(e)),this.opt.noMatch(e)),{start:l,end:r,valid:a}}},{key:"getTextNodes",value:function(e){var t=this,n="",r=[];this.iterator.forEachNode(NodeFilter.SHOW_TEXT,(function(e){r.push({start:n.length,end:(n+=e.textContent).length,node:e})}),(function(e){return t.matchesExclude(e.parentNode)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}),(function(){e({value:n,nodes:r})}))}},{key:"matchesExclude",value:function(e){return a.matches(e,this.opt.exclude.concat(["script","style","title","head","html"]))}},{key:"wrapRangeInTextNode",value:function(e,t,n){var r=this.opt.element?this.opt.element:"mark",a=e.splitText(t),o=a.splitText(n-t),i=document.createElement(r);return i.setAttribute("data-markjs","true"),this.opt.className&&i.setAttribute("class",this.opt.className),i.textContent=a.textContent,a.parentNode.replaceChild(i,a),o}},{key:"wrapRangeInMappedTextNode",value:function(e,t,n,r,a){var o=this;e.nodes.every((function(i,l){var s=e.nodes[l+1];if(void 0===s||s.start>t){if(!r(i.node))return!1;var c=t-i.start,u=(n>i.end?i.end:n)-i.start,d=e.value.substr(0,i.start),p=e.value.substr(u+i.start);if(i.node=o.wrapRangeInTextNode(i.node,c,u),e.value=d+p,e.nodes.forEach((function(t,n){n>=l&&(e.nodes[n].start>0&&n!==l&&(e.nodes[n].start-=u),e.nodes[n].end-=u)})),n-=u,a(i.node.previousSibling,i.start),!(n>i.end))return!1;t=i.end}return!0}))}},{key:"wrapMatches",value:function(e,t,n,r,a){var o=this,i=0===t?0:t+1;this.getTextNodes((function(t){t.nodes.forEach((function(t){t=t.node;for(var a=void 0;null!==(a=e.exec(t.textContent))&&""!==a[i];)if(n(a[i],t)){var l=a.index;if(0!==i)for(var s=1;s{"use strict";n.r(t)},1043:(e,t,n)=>{"use strict";n.r(t)},5947:function(e,t,n){var r,a;r=function(){var e,t,n={version:"0.2.0"},r=n.settings={minimum:.08,easing:"ease",positionUsing:"",speed:200,trickle:!0,trickleRate:.02,trickleSpeed:800,showSpinner:!0,barSelector:'[role="bar"]',spinnerSelector:'[role="spinner"]',parent:"body",template:'
'};function a(e,t,n){return en?n:e}function o(e){return 100*(-1+e)}function i(e,t,n){var a;return(a="translate3d"===r.positionUsing?{transform:"translate3d("+o(e)+"%,0,0)"}:"translate"===r.positionUsing?{transform:"translate("+o(e)+"%,0)"}:{"margin-left":o(e)+"%"}).transition="all "+t+"ms "+n,a}n.configure=function(e){var t,n;for(t in e)void 0!==(n=e[t])&&e.hasOwnProperty(t)&&(r[t]=n);return this},n.status=null,n.set=function(e){var t=n.isStarted();e=a(e,r.minimum,1),n.status=1===e?null:e;var o=n.render(!t),c=o.querySelector(r.barSelector),u=r.speed,d=r.easing;return o.offsetWidth,l((function(t){""===r.positionUsing&&(r.positionUsing=n.getPositioningCSS()),s(c,i(e,u,d)),1===e?(s(o,{transition:"none",opacity:1}),o.offsetWidth,setTimeout((function(){s(o,{transition:"all "+u+"ms linear",opacity:0}),setTimeout((function(){n.remove(),t()}),u)}),u)):setTimeout(t,u)})),this},n.isStarted=function(){return"number"==typeof n.status},n.start=function(){n.status||n.set(0);var e=function(){setTimeout((function(){n.status&&(n.trickle(),e())}),r.trickleSpeed)};return r.trickle&&e(),this},n.done=function(e){return e||n.status?n.inc(.3+.5*Math.random()).set(1):this},n.inc=function(e){var t=n.status;return t?("number"!=typeof e&&(e=(1-t)*a(Math.random()*t,.1,.95)),t=a(t+e,0,.994),n.set(t)):n.start()},n.trickle=function(){return n.inc(Math.random()*r.trickleRate)},e=0,t=0,n.promise=function(r){return r&&"resolved"!==r.state()?(0===t&&n.start(),e++,t++,r.always((function(){0==--t?(e=0,n.done()):n.set((e-t)/e)})),this):this},n.render=function(e){if(n.isRendered())return document.getElementById("nprogress");u(document.documentElement,"nprogress-busy");var t=document.createElement("div");t.id="nprogress",t.innerHTML=r.template;var a,i=t.querySelector(r.barSelector),l=e?"-100":o(n.status||0),c=document.querySelector(r.parent);return s(i,{transition:"all 0 linear",transform:"translate3d("+l+"%,0,0)"}),r.showSpinner||(a=t.querySelector(r.spinnerSelector))&&f(a),c!=document.body&&u(c,"nprogress-custom-parent"),c.appendChild(t),t},n.remove=function(){d(document.documentElement,"nprogress-busy"),d(document.querySelector(r.parent),"nprogress-custom-parent");var e=document.getElementById("nprogress");e&&f(e)},n.isRendered=function(){return!!document.getElementById("nprogress")},n.getPositioningCSS=function(){var e=document.body.style,t="WebkitTransform"in e?"Webkit":"MozTransform"in e?"Moz":"msTransform"in e?"ms":"OTransform"in e?"O":"";return t+"Perspective"in e?"translate3d":t+"Transform"in e?"translate":"margin"};var l=function(){var e=[];function t(){var n=e.shift();n&&n(t)}return function(n){e.push(n),1==e.length&&t()}}(),s=function(){var e=["Webkit","O","Moz","ms"],t={};function n(e){return e.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,(function(e,t){return t.toUpperCase()}))}function r(t){var n=document.body.style;if(t in n)return t;for(var r,a=e.length,o=t.charAt(0).toUpperCase()+t.slice(1);a--;)if((r=e[a]+o)in n)return r;return t}function a(e){return e=n(e),t[e]||(t[e]=r(e))}function o(e,t,n){t=a(t),e.style[t]=n}return function(e,t){var n,r,a=arguments;if(2==a.length)for(n in t)void 0!==(r=t[n])&&t.hasOwnProperty(n)&&o(e,n,r);else o(e,a[1],a[2])}}();function c(e,t){return("string"==typeof e?e:p(e)).indexOf(" "+t+" ")>=0}function u(e,t){var n=p(e),r=n+t;c(n,t)||(e.className=r.substring(1))}function d(e,t){var n,r=p(e);c(e,t)&&(n=r.replace(" "+t+" "," "),e.className=n.substring(1,n.length-1))}function p(e){return(" "+(e.className||"")+" ").replace(/\s+/gi," ")}function f(e){e&&e.parentNode&&e.parentNode.removeChild(e)}return n},void 0===(a="function"==typeof r?r.call(t,n,t,e):r)||(e.exports=a)},5302:(e,t,n)=>{var r=n(4634);e.exports=f,e.exports.parse=o,e.exports.compile=function(e,t){return l(o(e,t),t)},e.exports.tokensToFunction=l,e.exports.tokensToRegExp=p;var a=new RegExp(["(\\\\.)","([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))"].join("|"),"g");function o(e,t){for(var n,r=[],o=0,i=0,l="",u=t&&t.delimiter||"/";null!=(n=a.exec(e));){var d=n[0],p=n[1],f=n.index;if(l+=e.slice(i,f),i=f+d.length,p)l+=p[1];else{var m=e[i],h=n[2],g=n[3],b=n[4],y=n[5],v=n[6],w=n[7];l&&(r.push(l),l="");var x=null!=h&&null!=m&&m!==h,k="+"===v||"*"===v,S="?"===v||"*"===v,E=n[2]||u,_=b||y;r.push({name:g||o++,prefix:h||"",delimiter:E,optional:S,repeat:k,partial:x,asterisk:!!w,pattern:_?c(_):w?".*":"[^"+s(E)+"]+?"})}}return i{e.exports&&(e.exports={core:{meta:{path:"components/prism-core.js",option:"mandatory"},core:"Core"},themes:{meta:{path:"themes/{id}.css",link:"index.html?theme={id}",exclusive:!0},prism:{title:"Default",option:"default"},"prism-dark":"Dark","prism-funky":"Funky","prism-okaidia":{title:"Okaidia",owner:"ocodia"},"prism-twilight":{title:"Twilight",owner:"remybach"},"prism-coy":{title:"Coy",owner:"tshedor"},"prism-solarizedlight":{title:"Solarized Light",owner:"hectormatos2011 "},"prism-tomorrow":{title:"Tomorrow Night",owner:"Rosey"}},languages:{meta:{path:"components/prism-{id}",noCSS:!0,examplesPath:"examples/prism-{id}",addCheckAll:!0},markup:{title:"Markup",alias:["html","xml","svg","mathml","ssml","atom","rss"],aliasTitles:{html:"HTML",xml:"XML",svg:"SVG",mathml:"MathML",ssml:"SSML",atom:"Atom",rss:"RSS"},option:"default"},css:{title:"CSS",option:"default",modify:"markup"},clike:{title:"C-like",option:"default"},javascript:{title:"JavaScript",require:"clike",modify:"markup",optional:"regex",alias:"js",option:"default"},abap:{title:"ABAP",owner:"dellagustin"},abnf:{title:"ABNF",owner:"RunDevelopment"},actionscript:{title:"ActionScript",require:"javascript",modify:"markup",owner:"Golmote"},ada:{title:"Ada",owner:"Lucretia"},agda:{title:"Agda",owner:"xy-ren"},al:{title:"AL",owner:"RunDevelopment"},antlr4:{title:"ANTLR4",alias:"g4",owner:"RunDevelopment"},apacheconf:{title:"Apache Configuration",owner:"GuiTeK"},apex:{title:"Apex",require:["clike","sql"],owner:"RunDevelopment"},apl:{title:"APL",owner:"ngn"},applescript:{title:"AppleScript",owner:"Golmote"},aql:{title:"AQL",owner:"RunDevelopment"},arduino:{title:"Arduino",require:"cpp",alias:"ino",owner:"dkern"},arff:{title:"ARFF",owner:"Golmote"},armasm:{title:"ARM Assembly",alias:"arm-asm",owner:"RunDevelopment"},arturo:{title:"Arturo",alias:"art",optional:["bash","css","javascript","markup","markdown","sql"],owner:"drkameleon"},asciidoc:{alias:"adoc",title:"AsciiDoc",owner:"Golmote"},aspnet:{title:"ASP.NET (C#)",require:["markup","csharp"],owner:"nauzilus"},asm6502:{title:"6502 Assembly",owner:"kzurawel"},asmatmel:{title:"Atmel AVR Assembly",owner:"cerkit"},autohotkey:{title:"AutoHotkey",owner:"aviaryan"},autoit:{title:"AutoIt",owner:"Golmote"},avisynth:{title:"AviSynth",alias:"avs",owner:"Zinfidel"},"avro-idl":{title:"Avro IDL",alias:"avdl",owner:"RunDevelopment"},awk:{title:"AWK",alias:"gawk",aliasTitles:{gawk:"GAWK"},owner:"RunDevelopment"},bash:{title:"Bash",alias:["sh","shell"],aliasTitles:{sh:"Shell",shell:"Shell"},owner:"zeitgeist87"},basic:{title:"BASIC",owner:"Golmote"},batch:{title:"Batch",owner:"Golmote"},bbcode:{title:"BBcode",alias:"shortcode",aliasTitles:{shortcode:"Shortcode"},owner:"RunDevelopment"},bbj:{title:"BBj",owner:"hyyan"},bicep:{title:"Bicep",owner:"johnnyreilly"},birb:{title:"Birb",require:"clike",owner:"Calamity210"},bison:{title:"Bison",require:"c",owner:"Golmote"},bnf:{title:"BNF",alias:"rbnf",aliasTitles:{rbnf:"RBNF"},owner:"RunDevelopment"},bqn:{title:"BQN",owner:"yewscion"},brainfuck:{title:"Brainfuck",owner:"Golmote"},brightscript:{title:"BrightScript",owner:"RunDevelopment"},bro:{title:"Bro",owner:"wayward710"},bsl:{title:"BSL (1C:Enterprise)",alias:"oscript",aliasTitles:{oscript:"OneScript"},owner:"Diversus23"},c:{title:"C",require:"clike",owner:"zeitgeist87"},csharp:{title:"C#",require:"clike",alias:["cs","dotnet"],owner:"mvalipour"},cpp:{title:"C++",require:"c",owner:"zeitgeist87"},cfscript:{title:"CFScript",require:"clike",alias:"cfc",owner:"mjclemente"},chaiscript:{title:"ChaiScript",require:["clike","cpp"],owner:"RunDevelopment"},cil:{title:"CIL",owner:"sbrl"},cilkc:{title:"Cilk/C",require:"c",alias:"cilk-c",owner:"OpenCilk"},cilkcpp:{title:"Cilk/C++",require:"cpp",alias:["cilk-cpp","cilk"],owner:"OpenCilk"},clojure:{title:"Clojure",owner:"troglotit"},cmake:{title:"CMake",owner:"mjrogozinski"},cobol:{title:"COBOL",owner:"RunDevelopment"},coffeescript:{title:"CoffeeScript",require:"javascript",alias:"coffee",owner:"R-osey"},concurnas:{title:"Concurnas",alias:"conc",owner:"jasontatton"},csp:{title:"Content-Security-Policy",owner:"ScottHelme"},cooklang:{title:"Cooklang",owner:"ahue"},coq:{title:"Coq",owner:"RunDevelopment"},crystal:{title:"Crystal",require:"ruby",owner:"MakeNowJust"},"css-extras":{title:"CSS Extras",require:"css",modify:"css",owner:"milesj"},csv:{title:"CSV",owner:"RunDevelopment"},cue:{title:"CUE",owner:"RunDevelopment"},cypher:{title:"Cypher",owner:"RunDevelopment"},d:{title:"D",require:"clike",owner:"Golmote"},dart:{title:"Dart",require:"clike",owner:"Golmote"},dataweave:{title:"DataWeave",owner:"machaval"},dax:{title:"DAX",owner:"peterbud"},dhall:{title:"Dhall",owner:"RunDevelopment"},diff:{title:"Diff",owner:"uranusjr"},django:{title:"Django/Jinja2",require:"markup-templating",alias:"jinja2",owner:"romanvm"},"dns-zone-file":{title:"DNS zone file",owner:"RunDevelopment",alias:"dns-zone"},docker:{title:"Docker",alias:"dockerfile",owner:"JustinBeckwith"},dot:{title:"DOT (Graphviz)",alias:"gv",optional:"markup",owner:"RunDevelopment"},ebnf:{title:"EBNF",owner:"RunDevelopment"},editorconfig:{title:"EditorConfig",owner:"osipxd"},eiffel:{title:"Eiffel",owner:"Conaclos"},ejs:{title:"EJS",require:["javascript","markup-templating"],owner:"RunDevelopment",alias:"eta",aliasTitles:{eta:"Eta"}},elixir:{title:"Elixir",owner:"Golmote"},elm:{title:"Elm",owner:"zwilias"},etlua:{title:"Embedded Lua templating",require:["lua","markup-templating"],owner:"RunDevelopment"},erb:{title:"ERB",require:["ruby","markup-templating"],owner:"Golmote"},erlang:{title:"Erlang",owner:"Golmote"},"excel-formula":{title:"Excel Formula",alias:["xlsx","xls"],owner:"RunDevelopment"},fsharp:{title:"F#",require:"clike",owner:"simonreynolds7"},factor:{title:"Factor",owner:"catb0t"},false:{title:"False",owner:"edukisto"},"firestore-security-rules":{title:"Firestore security rules",require:"clike",owner:"RunDevelopment"},flow:{title:"Flow",require:"javascript",owner:"Golmote"},fortran:{title:"Fortran",owner:"Golmote"},ftl:{title:"FreeMarker Template Language",require:"markup-templating",owner:"RunDevelopment"},gml:{title:"GameMaker Language",alias:"gamemakerlanguage",require:"clike",owner:"LiarOnce"},gap:{title:"GAP (CAS)",owner:"RunDevelopment"},gcode:{title:"G-code",owner:"RunDevelopment"},gdscript:{title:"GDScript",owner:"RunDevelopment"},gedcom:{title:"GEDCOM",owner:"Golmote"},gettext:{title:"gettext",alias:"po",owner:"RunDevelopment"},gherkin:{title:"Gherkin",owner:"hason"},git:{title:"Git",owner:"lgiraudel"},glsl:{title:"GLSL",require:"c",owner:"Golmote"},gn:{title:"GN",alias:"gni",owner:"RunDevelopment"},"linker-script":{title:"GNU Linker Script",alias:"ld",owner:"RunDevelopment"},go:{title:"Go",require:"clike",owner:"arnehormann"},"go-module":{title:"Go module",alias:"go-mod",owner:"RunDevelopment"},gradle:{title:"Gradle",require:"clike",owner:"zeabdelkhalek-badido18"},graphql:{title:"GraphQL",optional:"markdown",owner:"Golmote"},groovy:{title:"Groovy",require:"clike",owner:"robfletcher"},haml:{title:"Haml",require:"ruby",optional:["css","css-extras","coffeescript","erb","javascript","less","markdown","scss","textile"],owner:"Golmote"},handlebars:{title:"Handlebars",require:"markup-templating",alias:["hbs","mustache"],aliasTitles:{mustache:"Mustache"},owner:"Golmote"},haskell:{title:"Haskell",alias:"hs",owner:"bholst"},haxe:{title:"Haxe",require:"clike",optional:"regex",owner:"Golmote"},hcl:{title:"HCL",owner:"outsideris"},hlsl:{title:"HLSL",require:"c",owner:"RunDevelopment"},hoon:{title:"Hoon",owner:"matildepark"},http:{title:"HTTP",optional:["csp","css","hpkp","hsts","javascript","json","markup","uri"],owner:"danielgtaylor"},hpkp:{title:"HTTP Public-Key-Pins",owner:"ScottHelme"},hsts:{title:"HTTP Strict-Transport-Security",owner:"ScottHelme"},ichigojam:{title:"IchigoJam",owner:"BlueCocoa"},icon:{title:"Icon",owner:"Golmote"},"icu-message-format":{title:"ICU Message Format",owner:"RunDevelopment"},idris:{title:"Idris",alias:"idr",owner:"KeenS",require:"haskell"},ignore:{title:".ignore",owner:"osipxd",alias:["gitignore","hgignore","npmignore"],aliasTitles:{gitignore:".gitignore",hgignore:".hgignore",npmignore:".npmignore"}},inform7:{title:"Inform 7",owner:"Golmote"},ini:{title:"Ini",owner:"aviaryan"},io:{title:"Io",owner:"AlesTsurko"},j:{title:"J",owner:"Golmote"},java:{title:"Java",require:"clike",owner:"sherblot"},javadoc:{title:"JavaDoc",require:["markup","java","javadoclike"],modify:"java",optional:"scala",owner:"RunDevelopment"},javadoclike:{title:"JavaDoc-like",modify:["java","javascript","php"],owner:"RunDevelopment"},javastacktrace:{title:"Java stack trace",owner:"RunDevelopment"},jexl:{title:"Jexl",owner:"czosel"},jolie:{title:"Jolie",require:"clike",owner:"thesave"},jq:{title:"JQ",owner:"RunDevelopment"},jsdoc:{title:"JSDoc",require:["javascript","javadoclike","typescript"],modify:"javascript",optional:["actionscript","coffeescript"],owner:"RunDevelopment"},"js-extras":{title:"JS Extras",require:"javascript",modify:"javascript",optional:["actionscript","coffeescript","flow","n4js","typescript"],owner:"RunDevelopment"},json:{title:"JSON",alias:"webmanifest",aliasTitles:{webmanifest:"Web App Manifest"},owner:"CupOfTea696"},json5:{title:"JSON5",require:"json",owner:"RunDevelopment"},jsonp:{title:"JSONP",require:"json",owner:"RunDevelopment"},jsstacktrace:{title:"JS stack trace",owner:"sbrl"},"js-templates":{title:"JS Templates",require:"javascript",modify:"javascript",optional:["css","css-extras","graphql","markdown","markup","sql"],owner:"RunDevelopment"},julia:{title:"Julia",owner:"cdagnino"},keepalived:{title:"Keepalived Configure",owner:"dev-itsheng"},keyman:{title:"Keyman",owner:"mcdurdin"},kotlin:{title:"Kotlin",alias:["kt","kts"],aliasTitles:{kts:"Kotlin Script"},require:"clike",owner:"Golmote"},kumir:{title:"KuMir (\u041a\u0443\u041c\u0438\u0440)",alias:"kum",owner:"edukisto"},kusto:{title:"Kusto",owner:"RunDevelopment"},latex:{title:"LaTeX",alias:["tex","context"],aliasTitles:{tex:"TeX",context:"ConTeXt"},owner:"japborst"},latte:{title:"Latte",require:["clike","markup-templating","php"],owner:"nette"},less:{title:"Less",require:"css",optional:"css-extras",owner:"Golmote"},lilypond:{title:"LilyPond",require:"scheme",alias:"ly",owner:"RunDevelopment"},liquid:{title:"Liquid",require:"markup-templating",owner:"cinhtau"},lisp:{title:"Lisp",alias:["emacs","elisp","emacs-lisp"],owner:"JuanCaicedo"},livescript:{title:"LiveScript",owner:"Golmote"},llvm:{title:"LLVM IR",owner:"porglezomp"},log:{title:"Log file",optional:"javastacktrace",owner:"RunDevelopment"},lolcode:{title:"LOLCODE",owner:"Golmote"},lua:{title:"Lua",owner:"Golmote"},magma:{title:"Magma (CAS)",owner:"RunDevelopment"},makefile:{title:"Makefile",owner:"Golmote"},markdown:{title:"Markdown",require:"markup",optional:"yaml",alias:"md",owner:"Golmote"},"markup-templating":{title:"Markup templating",require:"markup",owner:"Golmote"},mata:{title:"Mata",owner:"RunDevelopment"},matlab:{title:"MATLAB",owner:"Golmote"},maxscript:{title:"MAXScript",owner:"RunDevelopment"},mel:{title:"MEL",owner:"Golmote"},mermaid:{title:"Mermaid",owner:"RunDevelopment"},metafont:{title:"METAFONT",owner:"LaeriExNihilo"},mizar:{title:"Mizar",owner:"Golmote"},mongodb:{title:"MongoDB",owner:"airs0urce",require:"javascript"},monkey:{title:"Monkey",owner:"Golmote"},moonscript:{title:"MoonScript",alias:"moon",owner:"RunDevelopment"},n1ql:{title:"N1QL",owner:"TMWilds"},n4js:{title:"N4JS",require:"javascript",optional:"jsdoc",alias:"n4jsd",owner:"bsmith-n4"},"nand2tetris-hdl":{title:"Nand To Tetris HDL",owner:"stephanmax"},naniscript:{title:"Naninovel Script",owner:"Elringus",alias:"nani"},nasm:{title:"NASM",owner:"rbmj"},neon:{title:"NEON",owner:"nette"},nevod:{title:"Nevod",owner:"nezaboodka"},nginx:{title:"nginx",owner:"volado"},nim:{title:"Nim",owner:"Golmote"},nix:{title:"Nix",owner:"Golmote"},nsis:{title:"NSIS",owner:"idleberg"},objectivec:{title:"Objective-C",require:"c",alias:"objc",owner:"uranusjr"},ocaml:{title:"OCaml",owner:"Golmote"},odin:{title:"Odin",owner:"edukisto"},opencl:{title:"OpenCL",require:"c",modify:["c","cpp"],owner:"Milania1"},openqasm:{title:"OpenQasm",alias:"qasm",owner:"RunDevelopment"},oz:{title:"Oz",owner:"Golmote"},parigp:{title:"PARI/GP",owner:"Golmote"},parser:{title:"Parser",require:"markup",owner:"Golmote"},pascal:{title:"Pascal",alias:"objectpascal",aliasTitles:{objectpascal:"Object Pascal"},owner:"Golmote"},pascaligo:{title:"Pascaligo",owner:"DefinitelyNotAGoat"},psl:{title:"PATROL Scripting Language",owner:"bertysentry"},pcaxis:{title:"PC-Axis",alias:"px",owner:"RunDevelopment"},peoplecode:{title:"PeopleCode",alias:"pcode",owner:"RunDevelopment"},perl:{title:"Perl",owner:"Golmote"},php:{title:"PHP",require:"markup-templating",owner:"milesj"},phpdoc:{title:"PHPDoc",require:["php","javadoclike"],modify:"php",owner:"RunDevelopment"},"php-extras":{title:"PHP Extras",require:"php",modify:"php",owner:"milesj"},"plant-uml":{title:"PlantUML",alias:"plantuml",owner:"RunDevelopment"},plsql:{title:"PL/SQL",require:"sql",owner:"Golmote"},powerquery:{title:"PowerQuery",alias:["pq","mscript"],owner:"peterbud"},powershell:{title:"PowerShell",owner:"nauzilus"},processing:{title:"Processing",require:"clike",owner:"Golmote"},prolog:{title:"Prolog",owner:"Golmote"},promql:{title:"PromQL",owner:"arendjr"},properties:{title:".properties",owner:"Golmote"},protobuf:{title:"Protocol Buffers",require:"clike",owner:"just-boris"},pug:{title:"Pug",require:["markup","javascript"],optional:["coffeescript","ejs","handlebars","less","livescript","markdown","scss","stylus","twig"],owner:"Golmote"},puppet:{title:"Puppet",owner:"Golmote"},pure:{title:"Pure",optional:["c","cpp","fortran"],owner:"Golmote"},purebasic:{title:"PureBasic",require:"clike",alias:"pbfasm",owner:"HeX0R101"},purescript:{title:"PureScript",require:"haskell",alias:"purs",owner:"sriharshachilakapati"},python:{title:"Python",alias:"py",owner:"multipetros"},qsharp:{title:"Q#",require:"clike",alias:"qs",owner:"fedonman"},q:{title:"Q (kdb+ database)",owner:"Golmote"},qml:{title:"QML",require:"javascript",owner:"RunDevelopment"},qore:{title:"Qore",require:"clike",owner:"temnroegg"},r:{title:"R",owner:"Golmote"},racket:{title:"Racket",require:"scheme",alias:"rkt",owner:"RunDevelopment"},cshtml:{title:"Razor C#",alias:"razor",require:["markup","csharp"],optional:["css","css-extras","javascript","js-extras"],owner:"RunDevelopment"},jsx:{title:"React JSX",require:["markup","javascript"],optional:["jsdoc","js-extras","js-templates"],owner:"vkbansal"},tsx:{title:"React TSX",require:["jsx","typescript"]},reason:{title:"Reason",require:"clike",owner:"Golmote"},regex:{title:"Regex",owner:"RunDevelopment"},rego:{title:"Rego",owner:"JordanSh"},renpy:{title:"Ren'py",alias:"rpy",owner:"HyuchiaDiego"},rescript:{title:"ReScript",alias:"res",owner:"vmarcosp"},rest:{title:"reST (reStructuredText)",owner:"Golmote"},rip:{title:"Rip",owner:"ravinggenius"},roboconf:{title:"Roboconf",owner:"Golmote"},robotframework:{title:"Robot Framework",alias:"robot",owner:"RunDevelopment"},ruby:{title:"Ruby",require:"clike",alias:"rb",owner:"samflores"},rust:{title:"Rust",owner:"Golmote"},sas:{title:"SAS",optional:["groovy","lua","sql"],owner:"Golmote"},sass:{title:"Sass (Sass)",require:"css",optional:"css-extras",owner:"Golmote"},scss:{title:"Sass (SCSS)",require:"css",optional:"css-extras",owner:"MoOx"},scala:{title:"Scala",require:"java",owner:"jozic"},scheme:{title:"Scheme",owner:"bacchus123"},"shell-session":{title:"Shell session",require:"bash",alias:["sh-session","shellsession"],owner:"RunDevelopment"},smali:{title:"Smali",owner:"RunDevelopment"},smalltalk:{title:"Smalltalk",owner:"Golmote"},smarty:{title:"Smarty",require:"markup-templating",optional:"php",owner:"Golmote"},sml:{title:"SML",alias:"smlnj",aliasTitles:{smlnj:"SML/NJ"},owner:"RunDevelopment"},solidity:{title:"Solidity (Ethereum)",alias:"sol",require:"clike",owner:"glachaud"},"solution-file":{title:"Solution file",alias:"sln",owner:"RunDevelopment"},soy:{title:"Soy (Closure Template)",require:"markup-templating",owner:"Golmote"},sparql:{title:"SPARQL",require:"turtle",owner:"Triply-Dev",alias:"rq"},"splunk-spl":{title:"Splunk SPL",owner:"RunDevelopment"},sqf:{title:"SQF: Status Quo Function (Arma 3)",require:"clike",owner:"RunDevelopment"},sql:{title:"SQL",owner:"multipetros"},squirrel:{title:"Squirrel",require:"clike",owner:"RunDevelopment"},stan:{title:"Stan",owner:"RunDevelopment"},stata:{title:"Stata Ado",require:["mata","java","python"],owner:"RunDevelopment"},iecst:{title:"Structured Text (IEC 61131-3)",owner:"serhioromano"},stylus:{title:"Stylus",owner:"vkbansal"},supercollider:{title:"SuperCollider",alias:"sclang",owner:"RunDevelopment"},swift:{title:"Swift",owner:"chrischares"},systemd:{title:"Systemd configuration file",owner:"RunDevelopment"},"t4-templating":{title:"T4 templating",owner:"RunDevelopment"},"t4-cs":{title:"T4 Text Templates (C#)",require:["t4-templating","csharp"],alias:"t4",owner:"RunDevelopment"},"t4-vb":{title:"T4 Text Templates (VB)",require:["t4-templating","vbnet"],owner:"RunDevelopment"},tap:{title:"TAP",owner:"isaacs",require:"yaml"},tcl:{title:"Tcl",owner:"PeterChaplin"},tt2:{title:"Template Toolkit 2",require:["clike","markup-templating"],owner:"gflohr"},textile:{title:"Textile",require:"markup",optional:"css",owner:"Golmote"},toml:{title:"TOML",owner:"RunDevelopment"},tremor:{title:"Tremor",alias:["trickle","troy"],owner:"darach",aliasTitles:{trickle:"trickle",troy:"troy"}},turtle:{title:"Turtle",alias:"trig",aliasTitles:{trig:"TriG"},owner:"jakubklimek"},twig:{title:"Twig",require:"markup-templating",owner:"brandonkelly"},typescript:{title:"TypeScript",require:"javascript",optional:"js-templates",alias:"ts",owner:"vkbansal"},typoscript:{title:"TypoScript",alias:"tsconfig",aliasTitles:{tsconfig:"TSConfig"},owner:"dkern"},unrealscript:{title:"UnrealScript",alias:["uscript","uc"],owner:"RunDevelopment"},uorazor:{title:"UO Razor Script",owner:"jaseowns"},uri:{title:"URI",alias:"url",aliasTitles:{url:"URL"},owner:"RunDevelopment"},v:{title:"V",require:"clike",owner:"taggon"},vala:{title:"Vala",require:"clike",optional:"regex",owner:"TemplarVolk"},vbnet:{title:"VB.Net",require:"basic",owner:"Bigsby"},velocity:{title:"Velocity",require:"markup",owner:"Golmote"},verilog:{title:"Verilog",owner:"a-rey"},vhdl:{title:"VHDL",owner:"a-rey"},vim:{title:"vim",owner:"westonganger"},"visual-basic":{title:"Visual Basic",alias:["vb","vba"],aliasTitles:{vba:"VBA"},owner:"Golmote"},warpscript:{title:"WarpScript",owner:"RunDevelopment"},wasm:{title:"WebAssembly",owner:"Golmote"},"web-idl":{title:"Web IDL",alias:"webidl",owner:"RunDevelopment"},wgsl:{title:"WGSL",owner:"Dr4gonthree"},wiki:{title:"Wiki markup",require:"markup",owner:"Golmote"},wolfram:{title:"Wolfram language",alias:["mathematica","nb","wl"],aliasTitles:{mathematica:"Mathematica",nb:"Mathematica Notebook"},owner:"msollami"},wren:{title:"Wren",owner:"clsource"},xeora:{title:"Xeora",require:"markup",alias:"xeoracube",aliasTitles:{xeoracube:"XeoraCube"},owner:"freakmaxi"},"xml-doc":{title:"XML doc (.net)",require:"markup",modify:["csharp","fsharp","vbnet"],owner:"RunDevelopment"},xojo:{title:"Xojo (REALbasic)",owner:"Golmote"},xquery:{title:"XQuery",require:"markup",owner:"Golmote"},yaml:{title:"YAML",alias:"yml",owner:"hason"},yang:{title:"YANG",owner:"RunDevelopment"},zig:{title:"Zig",owner:"RunDevelopment"}},plugins:{meta:{path:"plugins/{id}/prism-{id}",link:"plugins/{id}/"},"line-highlight":{title:"Line Highlight",description:"Highlights specific lines and/or line ranges."},"line-numbers":{title:"Line Numbers",description:"Line number at the beginning of code lines.",owner:"kuba-kubula"},"show-invisibles":{title:"Show Invisibles",description:"Show hidden characters such as tabs and line breaks.",optional:["autolinker","data-uri-highlight"]},autolinker:{title:"Autolinker",description:"Converts URLs and emails in code to clickable links. Parses Markdown links in comments."},wpd:{title:"WebPlatform Docs",description:'Makes tokens link to WebPlatform.org documentation. The links open in a new tab.'},"custom-class":{title:"Custom Class",description:"This plugin allows you to prefix Prism's default classes (.comment can become .namespace--comment) or replace them with your defined ones (like .editor__comment). You can even add new classes.",owner:"dvkndn",noCSS:!0},"file-highlight":{title:"File Highlight",description:"Fetch external files and highlight them with Prism. Used on the Prism website itself.",noCSS:!0},"show-language":{title:"Show Language",description:"Display the highlighted language in code blocks (inline code does not show the label).",owner:"nauzilus",noCSS:!0,require:"toolbar"},"jsonp-highlight":{title:"JSONP Highlight",description:"Fetch content with JSONP and highlight some interesting content (e.g. GitHub/Gists or Bitbucket API).",noCSS:!0,owner:"nauzilus"},"highlight-keywords":{title:"Highlight Keywords",description:"Adds special CSS classes for each keyword for fine-grained highlighting.",owner:"vkbansal",noCSS:!0},"remove-initial-line-feed":{title:"Remove initial line feed",description:"Removes the initial line feed in code blocks.",owner:"Golmote",noCSS:!0},"inline-color":{title:"Inline color",description:"Adds a small inline preview for colors in style sheets.",require:"css-extras",owner:"RunDevelopment"},previewers:{title:"Previewers",description:"Previewers for angles, colors, gradients, easing and time.",require:"css-extras",owner:"Golmote"},autoloader:{title:"Autoloader",description:"Automatically loads the needed languages to highlight the code blocks.",owner:"Golmote",noCSS:!0},"keep-markup":{title:"Keep Markup",description:"Prevents custom markup from being dropped out during highlighting.",owner:"Golmote",optional:"normalize-whitespace",noCSS:!0},"command-line":{title:"Command Line",description:"Display a command line with a prompt and, optionally, the output/response from the commands.",owner:"chriswells0"},"unescaped-markup":{title:"Unescaped Markup",description:"Write markup without having to escape anything."},"normalize-whitespace":{title:"Normalize Whitespace",description:"Supports multiple operations to normalize whitespace in code blocks.",owner:"zeitgeist87",optional:"unescaped-markup",noCSS:!0},"data-uri-highlight":{title:"Data-URI Highlight",description:"Highlights data-URI contents.",owner:"Golmote",noCSS:!0},toolbar:{title:"Toolbar",description:"Attach a toolbar for plugins to easily register buttons on the top of a code block.",owner:"mAAdhaTTah"},"copy-to-clipboard":{title:"Copy to Clipboard Button",description:"Add a button that copies the code block to the clipboard when clicked.",owner:"mAAdhaTTah",require:"toolbar",noCSS:!0},"download-button":{title:"Download Button",description:"A button in the toolbar of a code block adding a convenient way to download a code file.",owner:"Golmote",require:"toolbar",noCSS:!0},"match-braces":{title:"Match braces",description:"Highlights matching braces.",owner:"RunDevelopment"},"diff-highlight":{title:"Diff Highlight",description:"Highlights the code inside diff blocks.",owner:"RunDevelopment",require:"diff"},"filter-highlight-all":{title:"Filter highlightAll",description:"Filters the elements the highlightAll and highlightAllUnder methods actually highlight.",owner:"RunDevelopment",noCSS:!0},treeview:{title:"Treeview",description:"A language with special styles to highlight file system tree structures.",owner:"Golmote"}}})},8722:(e,t,n)=>{const r=n(6969),a=n(8380),o=new Set;function i(e){void 0===e?e=Object.keys(r.languages).filter((e=>"meta"!=e)):Array.isArray(e)||(e=[e]);const t=[...o,...Object.keys(Prism.languages)];a(r,e,t).load((e=>{if(!(e in r.languages))return void(i.silent||console.warn("Language does not exist: "+e));const t="./prism-"+e;delete n.c[n(3157).resolve(t)],delete Prism.languages[e],n(3157)(t),o.add(e)}))}i.silent=!1,e.exports=i},9700:()=>{!function(e){function t(e,t){return"___"+e.toUpperCase()+t+"___"}Object.defineProperties(e.languages["markup-templating"]={},{buildPlaceholders:{value:function(n,r,a,o){if(n.language===r){var i=n.tokenStack=[];n.code=n.code.replace(a,(function(e){if("function"==typeof o&&!o(e))return e;for(var a,l=i.length;-1!==n.code.indexOf(a=t(r,l));)++l;return i[l]=e,a})),n.grammar=e.languages.markup}}},tokenizePlaceholders:{value:function(n,r){if(n.language===r&&n.tokenStack){n.grammar=e.languages[r];var a=0,o=Object.keys(n.tokenStack);!function i(l){for(var s=0;s=o.length);s++){var c=l[s];if("string"==typeof c||c.content&&"string"==typeof c.content){var u=o[a],d=n.tokenStack[u],p="string"==typeof c?c:c.content,f=t(r,u),m=p.indexOf(f);if(m>-1){++a;var h=p.substring(0,m),g=new e.Token(r,e.tokenize(d,n.grammar),"language-"+r,d),b=p.substring(m+f.length),y=[];h&&y.push.apply(y,i([h])),y.push(g),b&&y.push.apply(y,i([b])),"string"==typeof c?l.splice.apply(l,[s,1].concat(y)):c.content=y}}else c.content&&i(c.content)}return l}(n.tokens)}}}})}(Prism)},8692:(e,t,n)=>{var r={"./":8722};function a(e){var t=o(e);return n(t)}function o(e){if(!n.o(r,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return r[e]}a.keys=function(){return Object.keys(r)},a.resolve=o,e.exports=a,a.id=8692},3157:(e,t,n)=>{var r={"./":8722};function a(e){var t=o(e);return n(t)}function o(e){if(!n.o(r,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return r[e]}a.keys=function(){return Object.keys(r)},a.resolve=o,e.exports=a,a.id=3157},8380:e=>{"use strict";var t=function(){var e=function(){};function t(e,t){Array.isArray(e)?e.forEach(t):null!=e&&t(e,0)}function n(e){for(var t={},n=0,r=e.length;n "));var l={},s=e[r];if(s){function c(t){if(!(t in e))throw new Error(r+" depends on an unknown component "+t);if(!(t in l))for(var i in a(t,o),l[t]=!0,n[t])l[i]=!0}t(s.require,c),t(s.optional,c),t(s.modify,c)}n[r]=l,o.pop()}}return function(e){var t=n[e];return t||(a(e,r),t=n[e]),t}}function a(e){for(var t in e)return!0;return!1}return function(o,i,l){var s=function(e){var t={};for(var n in e){var r=e[n];for(var a in r)if("meta"!=a){var o=r[a];t[a]="string"==typeof o?{title:o}:o}}return t}(o),c=function(e){var n;return function(r){if(r in e)return r;if(!n)for(var a in n={},e){var o=e[a];t(o&&o.alias,(function(t){if(t in n)throw new Error(t+" cannot be alias for both "+a+" and "+n[t]);if(t in e)throw new Error(t+" cannot be alias of "+a+" because it is a component.");n[t]=a}))}return n[r]||r}}(s);i=i.map(c),l=(l||[]).map(c);var u=n(i),d=n(l);i.forEach((function e(n){var r=s[n];t(r&&r.require,(function(t){t in d||(u[t]=!0,e(t))}))}));for(var p,f=r(s),m=u;a(m);){for(var h in p={},m){var g=s[h];t(g&&g.modify,(function(e){e in d&&(p[e]=!0)}))}for(var b in d)if(!(b in u))for(var y in f(b))if(y in u){p[b]=!0;break}for(var v in m=p)u[v]=!0}var w={getIds:function(){var e=[];return w.load((function(t){e.push(t)})),e},load:function(t,n){return function(t,n,r,a){var o=a?a.series:void 0,i=a?a.parallel:e,l={},s={};function c(e){if(e in l)return l[e];s[e]=!0;var a,u=[];for(var d in t(e))d in n&&u.push(d);if(0===u.length)a=r(e);else{var p=i(u.map((function(e){var t=c(e);return delete s[e],t})));o?a=o(p,(function(){return r(e)})):r(e)}return l[e]=a}for(var u in n)c(u);var d=[];for(var p in s)d.push(l[p]);return i(d)}(f,u,t,n)}};return w}}();e.exports=t},2694:(e,t,n)=>{"use strict";var r=n(6925);function a(){}function o(){}o.resetWarningCache=a,e.exports=function(){function e(e,t,n,a,o,i){if(i!==r){var l=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw l.name="Invariant Violation",l}}function t(){return e}e.isRequired=e;var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:o,resetWarningCache:a};return n.PropTypes=n,n}},5556:(e,t,n)=>{e.exports=n(2694)()},6925:e=>{"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},2551:(e,t,n)=>{"use strict";var r=n(6540),a=n(9982);function o(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n