From 347b6ff2a4d00be1d5fdb3da310a033aefae0599 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 31 Mar 2023 19:45:16 +0000 Subject: [PATCH] 14.6.0 --- CHANGELOG.md | 6 +- dist/es/custom-index.js | 27 ++++- dist/es/custom-index.js.map | 2 +- dist/es/doc-cache.js | 5 + dist/es/doc-cache.js.map | 2 +- dist/es/plugin-helpers.js | 6 ++ dist/es/plugin-helpers.js.map | 2 +- .../graphql-schema-from-rx-schema.js | 7 ++ .../graphql-schema-from-rx-schema.js.map | 2 +- dist/es/plugins/utils/utils-array.js | 3 + dist/es/plugins/utils/utils-array.js.map | 2 +- dist/es/plugins/utils/utils-rxdb-version.js | 2 +- .../plugins/utils/utils-rxdb-version.js.map | 2 +- dist/es/rx-collection.js | 9 ++ dist/es/rx-collection.js.map | 2 +- dist/es/rx-database.js | 37 +++++++ dist/es/rx-database.js.map | 2 +- dist/es/rx-query.js | 14 +++ dist/es/rx-query.js.map | 2 +- dist/es/types/rx-query.d.js | 19 ++++ dist/es/types/rx-query.d.js.map | 2 +- dist/lib/custom-index.js | 27 ++++- dist/lib/custom-index.js.map | 2 +- dist/lib/doc-cache.js | 3 + dist/lib/doc-cache.js.map | 2 +- dist/lib/plugin-helpers.js | 5 + dist/lib/plugin-helpers.js.map | 2 +- .../graphql-schema-from-rx-schema.js | 6 ++ .../graphql-schema-from-rx-schema.js.map | 2 +- dist/lib/plugins/replication-p2p/index.js | 3 +- dist/lib/plugins/replication-p2p/index.js.map | 2 +- dist/lib/plugins/utils/utils-array.js | 4 + dist/lib/plugins/utils/utils-array.js.map | 2 +- dist/lib/plugins/utils/utils-rxdb-version.js | 2 +- .../plugins/utils/utils-rxdb-version.js.map | 2 +- dist/lib/rx-collection.js | 9 ++ dist/lib/rx-collection.js.map | 2 +- dist/lib/rx-database.js | 37 +++++++ dist/lib/rx-database.js.map | 2 +- dist/lib/rx-query.js | 14 +++ dist/lib/rx-query.js.map | 2 +- dist/rxdb.browserify.js | 101 +++++++++++++++++- dist/rxdb.browserify.min.js | 2 +- dist/types/custom-index.d.ts | 2 + dist/types/plugins/utils/utils-array.d.ts | 1 + .../plugins/utils/utils-rxdb-version.d.ts | 2 +- docs/index.html | 13 ++- docs/landingpage.js | 10 +- docs/premium.js | 10 +- package.json | 2 +- src/plugins/utils/utils-rxdb-version.ts | 2 +- 51 files changed, 376 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37c6b314d63..12a28a3a187 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,13 +2,17 @@ # RxDB Changelog -- FIX wrong index generation on some number fields that do not have decimals. + +### 14.6.0 (31 March 2023) + +- FIX wrong index generation on some number fields that do not have decimals. + ### 14.5.2 (30 March 2023) - ADD method `getPrimaryKeyFromIndexableString()` diff --git a/dist/es/custom-index.js b/dist/es/custom-index.js index a8e9afa4949..24837a370bd 100644 --- a/dist/es/custom-index.js +++ b/dist/es/custom-index.js @@ -72,9 +72,6 @@ export function getIndexableStringMonad(schema, index) { } else { // is number var parsedLengths = props.parsedLengths; - if (!fieldValue) { - fieldValue = 0; - } str += getNumberIndexString(parsedLengths, fieldValue); } } @@ -94,6 +91,8 @@ export function getStringLengthOfIndexNumber(schemaPart) { decimals = multipleOfParts[1].length; } return { + minimum, + maximum, nonDecimals, decimals, roundedMinimum: minimum @@ -122,12 +121,32 @@ export function getPrimaryKeyFromIndexableString(indexableString, primaryKeyLeng return primaryKey; } export function getNumberIndexString(parsedLengths, fieldValue) { + /** + * Ensure that the given value is in the boundaries + * of the schema, otherwise it would create a broken index string. + * This can happen for example if you have a minimum of 0 + * and run a query like + * selector { + * numField: { $gt: -1000 } + * } + */ + if (typeof fieldValue === 'undefined') { + fieldValue = 0; + } + if (fieldValue < parsedLengths.minimum) { + fieldValue = parsedLengths.minimum; + } + if (fieldValue > parsedLengths.maximum) { + fieldValue = parsedLengths.maximum; + } var str = ''; var nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString(); str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0'); var splitByDecimalPoint = fieldValue.toString().split('.'); var decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0'; - str += decimalValueAsString.padEnd(parsedLengths.decimals, '0'); + if (parsedLengths.decimals > 0) { + str += decimalValueAsString.padEnd(parsedLengths.decimals, '0'); + } return str; } export function getStartIndexStringFromLowerBound(schema, index, lowerBound, inclusiveStart) { diff --git a/dist/es/custom-index.js.map b/dist/es/custom-index.js.map index ebf0df13dd1..2f7fc16a142 100644 --- a/dist/es/custom-index.js.map +++ b/dist/es/custom-index.js.map @@ -1 +1 @@ -{"version":3,"file":"custom-index.js","names":["getSchemaByObjectPath","ensureNotFalsy","objectPathMonad","INDEX_MAX","INDEX_MIN","getIndexMeta","schema","index","fieldNameProperties","map","fieldName","schemaPart","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","getIndexableStringMonad","ret","docData","str","i","length","props","fieldValue","padEnd","maxLength","boolToStr","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trimEnd","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n) {\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n return fieldNameProperties;\n}\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n const fieldNameProperties = getIndexMeta(schema, index);\n\n /**\n * @hotPath Performance of this function is very critical!\n */\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n for (let i = 0; i < fieldNameProperties.length; ++i) {\n const props = fieldNameProperties[i];\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n let fieldValue = props.getValueFn(docData);\n if (type === 'string') {\n // is string\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n // is boolean\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n // is number\n const parsedLengths = props.parsedLengths as ParsedLengths;\n if (!fieldValue) {\n fieldValue = 0;\n }\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n }\n return str;\n };\n return ret;\n}\n\ndeclare type ParsedLengths = {\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\nexport function getIndexStringLength(\n schema: RxJsonSchema>,\n index: string[]\n): number {\n const fieldNameProperties = getIndexMeta(schema, index);\n let length = 0;\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n if (type === 'string') {\n length += schemaPart.maxLength as number;\n } else if (type === 'boolean') {\n length += 1;\n } else {\n const parsedLengths = props.parsedLengths as ParsedLengths;\n length = length + parsedLengths.nonDecimals + parsedLengths.decimals;\n }\n\n });\n return length;\n}\n\n\nexport function getPrimaryKeyFromIndexableString(\n indexableString: string,\n primaryKeyLength: number\n): string {\n const paddedPrimaryKey = indexableString.slice(primaryKeyLength * -1);\n const primaryKey = paddedPrimaryKey.trimEnd();\n return primaryKey;\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,qBAAqB,QAAQ,oBAAoB;AAM1D,SACIC,cAAc,EACdC,eAAe,QAEZ,iBAAiB;AACxB,SAASC,SAAS,EAAEC,SAAS,QAAQ,iBAAiB;AAGtD,OAAO,SAASC,YAAYA,CACxBC,MAA+C,EAC/CC,KAAe,EACjB;EACE;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAACC,SAAS,IAAI;IACzB,IAAMC,UAAU,GAAGX,qBAAqB,CACpCM,MAAM,EACNI,SAAS,CACZ;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIC,KAAK,CAAC,iBAAiB,GAAGF,SAAS,CAAC;IAClD;IACA,IAAMG,IAAI,GAAGF,UAAU,CAACE,IAAI;IAC5B,IAAIC,aAAwC;IAC5C,IAAID,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,SAAS,EAAE;MACzCC,aAAa,GAAGC,4BAA4B,CACxCJ,UAAU,CACb;IACL;IAEA,OAAO;MACHD,SAAS;MACTC,UAAU;MACVG,aAAa;MACbE,cAAc,EAAEN,SAAS,CAACO,QAAQ,CAAC,GAAG,CAAC;MACvCC,UAAU,EAAEhB,eAAe,CAACQ,SAAS;IACzC,CAAC;EACL,CAAC,CAAC;EACF,OAAOF,mBAAmB;AAC9B;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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AAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOS,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"custom-index.js","names":["getSchemaByObjectPath","ensureNotFalsy","objectPathMonad","INDEX_MAX","INDEX_MIN","getIndexMeta","schema","index","fieldNameProperties","map","fieldName","schemaPart","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","getIndexableStringMonad","ret","docData","str","i","length","props","fieldValue","padEnd","maxLength","boolToStr","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trimEnd","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n) {\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n return fieldNameProperties;\n}\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n const fieldNameProperties = getIndexMeta(schema, index);\n\n /**\n * @hotPath Performance of this function is very critical!\n */\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n for (let i = 0; i < fieldNameProperties.length; ++i) {\n const props = fieldNameProperties[i];\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n let fieldValue = props.getValueFn(docData);\n if (type === 'string') {\n // is string\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n // is boolean\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n // is number\n const parsedLengths = props.parsedLengths as ParsedLengths;\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n }\n return str;\n };\n return ret;\n}\n\n\n\ndeclare type ParsedLengths = {\n minimum: number;\n maximum: number;\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n minimum,\n maximum,\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\nexport function getIndexStringLength(\n schema: RxJsonSchema>,\n index: string[]\n): number {\n const fieldNameProperties = getIndexMeta(schema, index);\n let length = 0;\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n if (type === 'string') {\n length += schemaPart.maxLength as number;\n } else if (type === 'boolean') {\n length += 1;\n } else {\n const parsedLengths = props.parsedLengths as ParsedLengths;\n length = length + parsedLengths.nonDecimals + parsedLengths.decimals;\n }\n\n });\n return length;\n}\n\n\nexport function getPrimaryKeyFromIndexableString(\n indexableString: string,\n primaryKeyLength: number\n): string {\n const paddedPrimaryKey = indexableString.slice(primaryKeyLength * -1);\n const primaryKey = paddedPrimaryKey.trimEnd();\n return primaryKey;\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n /**\n * Ensure that the given value is in the boundaries\n * of the schema, otherwise it would create a broken index string.\n * This can happen for example if you have a minimum of 0\n * and run a query like\n * selector {\n * numField: { $gt: -1000 }\n * }\n */\n if (typeof fieldValue === 'undefined') {\n fieldValue = 0;\n }\n if (fieldValue < parsedLengths.minimum) {\n fieldValue = parsedLengths.minimum;\n }\n if (fieldValue > parsedLengths.maximum) {\n fieldValue = parsedLengths.maximum;\n }\n\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n if (parsedLengths.decimals > 0) {\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n }\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,qBAAqB,QAAQ,oBAAoB;AAM1D,SACIC,cAAc,EACdC,eAAe,QAEZ,iBAAiB;AACxB,SAASC,SAAS,EAAEC,SAAS,QAAQ,iBAAiB;AAGtD,OAAO,SAASC,YAAYA,CACxBC,MAA+C,EAC/CC,KAAe,EACjB;EACE;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAACC,SAAS,IAAI;IACzB,IAAMC,UAAU,GAAGX,qBAAqB,CACpCM,MAAM,EACNI,SAAS,CACZ;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIC,KAAK,CAAC,iBAAiB,GAAGF,SAAS,CAAC;IAClD;IACA,IAAMG,IAAI,GAAGF,UAAU,CAACE,IAAI;IAC5B,IAAIC,aAAwC;IAC5C,IAAID,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,SAAS,EAAE;MACzCC,aAAa,GAAGC,4BAA4B,CACxCJ,UAAU,CACb;IACL;IAEA,OAAO;MACHD,SAAS;MACTC,UAAU;MACVG,aAAa;MACbE,cAAc,EAAEN,SAAS,CAACO,QAAQ,CAAC,GAAG,CAAC;MACvCC,UAAU,EAAEhB,eAAe,CAACQ,SAAS;IACzC,CAAC;EACL,CAAC,CAAC;EACF,OAAOF,mBAAmB;AAC9B;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASW,uBAAuBA,CACnCb,MAA+C,EAC/CC,KAAe,EAC+B;E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G,GAAG,GAAG,GAAG;UACzC5C,GAAG,IAAIwC,QAAQ,CAACC,MAAM,CAACjD,aAAa,CAACwB,WAAW,GAAGxB,aAAa,CAAC4B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHpB,GAAG,IAAIQ,oBAAoB,CACvBhB,aAAa,EACb+C,KAAK,CACR;QACL;QACA;MACJ;QACI,MAAM,IAAIjD,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOS,GAAG;AACd"} \ No newline at end of file diff --git a/dist/es/doc-cache.js b/dist/es/doc-cache.js index cbe1b5ccb53..0018403e737 100644 --- a/dist/es/doc-cache.js +++ b/dist/es/doc-cache.js @@ -1,6 +1,11 @@ import { getFromMapOrCreate, getFromMapOrThrow, getHeightOfRevision } from './plugins/utils'; import { overwritable } from './overwritable'; import { getDocumentDataOfRxChangeEvent } from './rx-change-event'; + +/** + * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + */ + /** * The DocumentCache stores RxDocument objects * by their primary key and revision. diff --git a/dist/es/doc-cache.js.map b/dist/es/doc-cache.js.map index 01b6825b9d1..792bc38556d 100644 --- a/dist/es/doc-cache.js.map +++ b/dist/es/doc-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"doc-cache.js","names":["getFromMapOrCreate","getFromMapOrThrow","getHeightOfRevision","overwritable","getDocumentDataOfRxChangeEvent","DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","documentByRevisionHeight","delete","revisionHeight","size","undefined","subscribe","changeEvent","documentId","documentData","latestDoc","_proto","prototype","getCachedRxDocument","docData","_rev","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","deepFreezeWhenDevMode","set","createWeakRefWithFallback","register","getLatestDocumentData","getLatestDocumentDataIfExists","HAS_WEAK_REF","WeakRef","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision\n} from './plugins/utils';\nimport {\n overwritable\n} from './overwritable';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\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 documentByRevisionHeight: 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 latestDoc: 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 private 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.documentByRevisionHeight.delete(docMeta.revisionHeight);\n if (cacheItem.documentByRevisionHeight.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 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.latestDoc = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n */\n public getCachedRxDocument(docData: RxDocumentData): RxDocument {\n const docId: string = (docData as any)[this.primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n this.cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const cachedRxDocumentWeakRef: WeakRef> | undefined = cacheItem.documentByRevisionHeight.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = overwritable.deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = this.documentCreator(docData) as RxDocument;\n cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n\n if (this.registry) {\n this.registry.register(cachedRxDocument, {\n docId,\n revisionHeight\n });\n }\n }\n return cachedRxDocument;\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.latestDoc;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.latestDoc;\n }\n }\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n documentByRevisionHeight: new Map(),\n latestDoc: docData\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';\nfunction createWeakRefWithFallback(obj: T): WeakRef {\n if (HAS_WEAK_REF) {\n return new WeakRef(obj) as any;\n } else {\n return {\n deref() {\n return obj;\n }\n } as any;\n }\n}\n"],"mappings":"AAKA,SACIA,kBAAkB,EAClBC,iBAAiB,EACjBC,mBAAmB,QAChB,iBAAiB;AACxB,SACIC,YAAY,QACT,gBAAgB;AACvB,SAASC,8BAA8B,QAAQ,mBAAmB;AAqClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,aAAa;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI,SAAAA,cACoBC,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA,KAhCKC,gBAAgB,GAAG,IAAIC,GAAG,EAA4C;IAAA,KAQrEC,QAAQ,GAAqD,OAAOC,oBAAoB,KAAK,UAAU,GAC3G,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,wBAAwB,CAACC,MAAM,CAACL,OAAO,CAACM,cAAc,CAAC;QACjE,IAAIJ,SAAS,CAACE,wBAAwB,CAACG,IAAI,KAAK,CAAC,EAAE;UAC/C;AACpB;AACA;AACA;UACoB,IAAI,CAACX,gBAAgB,CAACS,MAAM,CAACJ,KAAK,CAAC;QACvC;MACJ;IACJ,CAAC,CAAC,GACFO,SAAS;IAAA,KAGOf,WAAmB,GAAnBA,WAAmB;IAAA,KACnBC,QAA8C,GAA9CA,QAA8C;IAAA,KAIvDC,eAA0F,GAA1FA,eAA0F;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;UACrCpB,KAAK;UACLK;QACJ,CAAC,CAAC;MACN;IACJ;IACA,OAAOe,gBAAgB;EAC3B;;EAEA;AACJ;AACA,KAFI;EAAAP,MAAA,CAGOa,qBAAqB,GAA5B,SAAAA,sBAA6B1B,KAAa,EAA6B;IACnE,IAAMC,SAAS,GAAGd,iBAAiB,CAAC,IAAI,CAACQ,gBAAgB,EAAEK,KAAK,CAAC;IACjE,OAAOC,SAAS,CAACW,SAAS;EAC9B,CAAC;EAAAC,MAAA,CAEMc,6BAA6B,GAApC,SAAAA,8BAAqC3B,KAAa,EAAyC;IACvF,IAAMC,SAAS,GAAG,IAAI,CAACN,gBAAgB,CAACO,GAAG,CAACF,KAAK,CAAC;IAClD,IAAIC,SAAS,EAAE;MACX,OAAOA,SAAS,CAACW,SAAS;IAC9B;EACJ,CAAC;EAAA,OAAArB,aAAA;AAAA;AAIL,SAAS2B,eAAeA,CAAwBF,OAAkC,EAAoC;EAClH,OAAO;IACHb,wBAAwB,EAAE,IAAIP,GAAG,EAAE;IACnCgB,SAAS,EAAEI;EACf,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA;AACA,IAAMY,YAAY,GAAG,OAAOC,OAAO,KAAK,UAAU;AAClD,SAASL,yBAAyBA,CAAmBM,GAAM,EAAc;EACrE,IAAIF,YAAY,EAAE;IACd,OAAO,IAAIC,OAAO,CAACC,GAAG,CAAC;EAC3B,CAAC,MAAM;IACH,OAAO;MACHT,KAAKA,CAAA,EAAG;QACJ,OAAOS,GAAG;MACd;IACJ,CAAC;EACL;AACJ"} \ No newline at end of file +{"version":3,"file":"doc-cache.js","names":["getFromMapOrCreate","getFromMapOrThrow","getHeightOfRevision","overwritable","getDocumentDataOfRxChangeEvent","DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","documentByRevisionHeight","delete","revisionHeight","size","undefined","subscribe","changeEvent","documentId","documentData","latestDoc","_proto","prototype","getCachedRxDocument","docData","_rev","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","deepFreezeWhenDevMode","set","createWeakRefWithFallback","register","getLatestDocumentData","getLatestDocumentDataIfExists","HAS_WEAK_REF","WeakRef","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision\n} from './plugins/utils';\nimport {\n overwritable\n} from './overwritable';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\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 documentByRevisionHeight: 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 latestDoc: 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 private 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.documentByRevisionHeight.delete(docMeta.revisionHeight);\n if (cacheItem.documentByRevisionHeight.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 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.latestDoc = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n */\n public getCachedRxDocument(docData: RxDocumentData): RxDocument {\n const docId: string = (docData as any)[this.primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n this.cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const cachedRxDocumentWeakRef: WeakRef> | undefined = cacheItem.documentByRevisionHeight.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = overwritable.deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = this.documentCreator(docData) as RxDocument;\n cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n\n if (this.registry) {\n this.registry.register(cachedRxDocument, {\n docId,\n revisionHeight\n });\n }\n }\n return cachedRxDocument;\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.latestDoc;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.latestDoc;\n }\n }\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n documentByRevisionHeight: new Map(),\n latestDoc: docData\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';\nfunction createWeakRefWithFallback(obj: T): WeakRef {\n if (HAS_WEAK_REF) {\n return new WeakRef(obj) as any;\n } else {\n return {\n deref() {\n return obj;\n }\n } as any;\n }\n}\n"],"mappings":"AAKA,SACIA,kBAAkB,EAClBC,iBAAiB,EACjBC,mBAAmB,QAChB,iBAAiB;AACxB,SACIC,YAAY,QACT,gBAAgB;AACvB,SAASC,8BAA8B,QAAQ,mBAAmB;;AA6BlE;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,aAAa;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI,SAAAA,cACoBC,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA,KAhCKC,gBAAgB,GAAG,IAAIC,GAAG,EAA4C;IAAA,KAQrEC,QAAQ,GAAqD,OAAOC,oBAAoB,KAAK,UAAU,GAC3G,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,wBAAwB,CAACC,MAAM,CAACL,OAAO,CAACM,cAAc,CAAC;QACjE,IAAIJ,SAAS,CAACE,wBAAwB,CAACG,IAAI,KAAK,CAAC,EAAE;UAC/C;AACpB;AACA;AACA;UACoB,IAAI,CAACX,gBAAgB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CAACE,wBAAwB,CAACoB,GAAG,CAAClB,cAAc,EAAEmB,yBAAyB,CAACJ,gBAAgB,CAAC,CAAC;MAEnG,IAAI,IAAI,CAACvB,QAAQ,EAAE;QACf,IAAI,CAACA,QAAQ,CAAC4B,QAAQ,CAACL,gBAAgB,EAAE;UACrCpB,KAAK;UACLK;QACJ,CAAC,CAAC;MACN;IACJ;IACA,OAAOe,gBAAgB;EAC3B;;EAEA;AACJ;AACA,KAFI;EAAAP,MAAA,CAGOa,qBAAqB,GAA5B,SAAAA,sBAA6B1B,KAAa,EAA6B;IACnE,IAAMC,SAAS,GAAGd,iBAAiB,CAAC,IAAI,CAACQ,gBAAgB,EAAEK,KAAK,CAAC;IACjE,OAAOC,SAAS,CAACW,SAAS;EAC9B,CAAC;EAAAC,MAAA,CAEMc,6BAA6B,GAApC,SAAAA,8BAAqC3B,KAAa,EAAyC;IACvF,IAAMC,SAAS,GAAG,IAAI,CAACN,gBAAgB,CAACO,GAAG,CAACF,KAAK,CAAC;IAClD,IAAIC,SAAS,EAAE;MACX,OAAOA,SAAS,CAACW,SAAS;IAC9B;EACJ,CAAC;EAAA,OAAArB,aAAA;AAAA;AAIL,SAAS2B,eAAeA,CAAwBF,OAAkC,EAAoC;EAClH,OAAO;IACHb,wBAAwB,EAAE,IAAIP,GAAG,EAAE;IACnCgB,SAAS,EAAEI;EACf,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA;AACA,IAAMY,YAAY,GAAG,OAAOC,OAAO,KAAK,UAAU;AAClD,SAASL,yBAAyBA,CAAmBM,GAAM,EAAc;EACrE,IAAIF,YAAY,EAAE;IACd,OAAO,IAAIC,OAAO,CAACC,GAAG,CAAC;EAC3B,CAAC,MAAM;IACH,OAAO;MACHT,KAAKA,CAAA,EAAG;QACJ,OAAOS,GAAG;MACd;IACJ,CAAC;EACL;AACJ"} \ No newline at end of file diff --git a/dist/es/plugin-helpers.js b/dist/es/plugin-helpers.js index b0a4776d9cd..a2868f08c6e 100644 --- a/dist/es/plugin-helpers.js +++ b/dist/es/plugin-helpers.js @@ -2,6 +2,12 @@ import { filter, mergeMap, tap } from 'rxjs/operators'; import { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper'; import { defaultHashSha256, flatClone, getFromMapOrCreate, requestIdleCallbackIfAvailable } from './plugins/utils'; import { BehaviorSubject, firstValueFrom } from 'rxjs'; + +/** + * Returns the validation errors. + * If document is fully valid, returns an empty array. + */ + /** * cache the validators by the schema-hash * so we can reuse them when multiple collections have the same schema diff --git a/dist/es/plugin-helpers.js.map b/dist/es/plugin-helpers.js.map index 6588e22e21c..3946dfd493f 100644 --- a/dist/es/plugin-helpers.js.map +++ b/dist/es/plugin-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin-helpers.js","names":["filter","mergeMap","tap","getPrimaryFieldOfPrimaryKey","defaultHashSha256","flatClone","getFromMapOrCreate","requestIdleCallbackIfAvailable","BehaviorSubject","firstValueFrom","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","initValidator","schema","hash","JSON","stringify","args","Object","assign","storage","createStorageInstance","params","instance","primaryPath","primaryKey","validatorCached","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","documentInDb","previous","processingChangesCount$","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","entries","k","v2","err","pipe","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","data","findDocumentsById","ids","deleted","findResult","key","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","next","getValue","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","id","conflictResultionTasks","task","assumedMasterState","input","newDocumentState","realMasterState","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport { WrappedRxStorageInstance } from './rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n defaultHashSha256,\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = defaultHashSha256(JSON.stringify(schema));\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n hash,\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ error: {}, success: {} });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error[validationError.documentId] = validationError;\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: instance.schema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: (limit, checkpoint) => {\n return instance.getChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n conflictResultionTasks: () => {\n return instance.conflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n },\n resolveConflictResultionTask: (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return instance.resolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return instance.resolveConflictResultionTask(useSolution);\n }\n };\n\n return wrappedInstance;\n}\n"],"mappings":"AAAA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,GAAG,QAAQ,gBAAgB;AACtD,SAASC,2BAA2B,QAAQ,oBAAoB;AAmBhE,SACIC,iBAAiB,EACjBC,SAAS,EACTC,kBAAkB,EAClBC,8BAA8B,QAC3B,iBAAiB;AACxB,SAASC,eAAe,EAAEC,cAAc,QAAQ,MAAM;AAetD;AACA;AACA;AACA;AACA,IAAMC,gCAA6E,GAAG,IAAIC,GAAG,EAAE;;AAE/F;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6BA;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ;AACA;AACIC,YAAoB,EACE;EACtB,IAAMC,eAAe,GAAGT,kBAAkB,CACtCI,gCAAgC,EAChCI,YAAY,EACZ,MAAM,IAAIH,GAAG,EAAE,CAClB;EAED,SAASK,aAAaA,CAClBC,MAAyB,EACR;IACjB,IAAMC,IAAI,GAAGd,iBAAiB,CAACe,IAAI,CAACC,SAAS,CAACH,MAAM,CAAC,CAAC;IACtD,OAAOX,kBAAkB,CACrBS,eAAe,EACfG,IAAI,EACJ,MAAML,YAAY,CAACI,MAAM,CAAC,CAC7B;EACL;EAEA,OAAQI,IAAI,IAAK;IACb,OAAOC,MAAM,CAACC,MAAM,CAChB,CAAC,CAAC,EACFF,IAAI,CAACG,OAAO,EACZ;MACI,MAAMC,qBAAqBA,CACvBC,MAAuD,EACzD;QACE,IAAMC,QAAQ,GAAG,MAAMN,IAAI,CAACG,OAAO,CAACC,qBAAqB,CAACC,MAAM,CAAC;QACjE,IAAME,WAAW,GAAGzB,2BAA2B,CAACuB,M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AAQ,EAAE,GAAG,CAAC,CAAC,CAAC,CAClF;IACL,CAAC;IACDc,sBAAsB,EAAEA,CAAA,KAAM;MAC1B,OAAOhG,QAAQ,CAACgG,sBAAsB,EAAE,CAACnC,IAAI,CACzCvF,QAAQ,CAAC,MAAO2H,IAAI,IAAK;QACrB,IAAMC,kBAAkB,GAAG,MAAM9D,WAAW,CAAC6D,IAAI,CAACE,KAAK,CAACD,kBAAkB,CAAC;QAC3E,IAAME,gBAAgB,GAAG,MAAMhE,WAAW,CAAC6D,IAAI,CAACE,KAAK,CAACC,gBAAgB,CAAC;QACvE,IAAMC,eAAe,GAAG,MAAMjE,WAAW,CAAC6D,IAAI,CAACE,KAAK,CAACE,eAAe,CAAC;QACrE,OAAO;UACHN,EAAE,EAAEE,IAAI,CAACF,EAAE;UACXvF,OAAO,EAAEyF,IAAI,CAACzF,OAAO;UACrB2F,KAAK,EAAE;YACHD,kBAAkB;YAClBG,eAAe;YACfD;UACJ;QACJ,CAAC;MACL,CAAC,CAAC,CACL;IACL,CAAC;IACDE,4BAA4B,EAAGC,YAAY,IAAK;MAC5C,IAAIA,YAAY,CAACC,MAAM,CAACC,OAAO,EAAE;QAC7B,OAAOzG,QAAQ,CAACsG,4BAA4B,CAACC,YAAY,CAAC;MAC9D;MACA,IAAMG,WAAW,GAAG;QAChBX,EAAE,EAAEQ,YAAY,CAACR,EAAE;QACnBS,MAAM,EAAE;UACJC,OAAO,EAAE,KAAK;UACdlB,YAAY,EAAEgB,YAAY,CAACC,MAAM,CAACjB;QACtC;MACJ,CAAC;MACD,OAAOvF,QAAQ,CAACsG,4BAA4B,CAACI,WAAW,CAAC;IAC7D;EACJ,CAAC;EAED,OAAOhE,eAAe;AAC1B"} \ No newline at end of file +{"version":3,"file":"plugin-helpers.js","names":["filter","mergeMap","tap","getPrimaryFieldOfPrimaryKey","defaultHashSha256","flatClone","getFromMapOrCreate","requestIdleCallbackIfAvailable","BehaviorSubject","firstValueFrom","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","initValidator","schema","hash","JSON","stringify","args","Object","assign","storage","createStorageInstance","params","instance","primaryPath","primaryKey","validatorCached","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","documentInDb","previous","processingChangesCount$","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","entries","k","v2","err","pipe","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","data","findDocumentsById","ids","deleted","findResult","key","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","next","getValue","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","id","conflictResultionTasks","task","assumedMasterState","input","newDocumentState","realMasterState","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport { WrappedRxStorageInstance } from './rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n defaultHashSha256,\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = defaultHashSha256(JSON.stringify(schema));\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n hash,\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ error: {}, success: {} });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error[validationError.documentId] = validationError;\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: instance.schema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: (limit, checkpoint) => {\n return instance.getChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n conflictResultionTasks: () => {\n return instance.conflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n },\n resolveConflictResultionTask: (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return instance.resolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return instance.resolveConflictResultionTask(useSolution);\n }\n };\n\n return wrappedInstance;\n}\n"],"mappings":"AAAA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,GAAG,QAAQ,gBAAgB;AACtD,SAASC,2BAA2B,QAAQ,oBAAoB;AAmBhE,SACIC,iBAAiB,EACjBC,SAAS,EACTC,kBAAkB,EAClBC,8BAA8B,QAC3B,iBAAiB;AACxB,SAASC,eAAe,EAAEC,cAAc,QAAQ,MAAM;;AAStD;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA,IAAMC,gCAA6E,GAAG,IAAIC,GAAG,EAAE;;AAE/F;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6BA;AACzC;AAC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eAAe;YACfD;UACJ;QACJ,CAAC;MACL,CAAC,CAAC,CACL;IACL,CAAC;IACDE,4BAA4B,EAAGC,YAAY,IAAK;MAC5C,IAAIA,YAAY,CAACC,MAAM,CAACC,OAAO,EAAE;QAC7B,OAAOzG,QAAQ,CAACsG,4BAA4B,CAACC,YAAY,CAAC;MAC9D;MACA,IAAMG,WAAW,GAAG;QAChBX,EAAE,EAAEQ,YAAY,CAACR,EAAE;QACnBS,MAAM,EAAE;UACJC,OAAO,EAAE,KAAK;UACdlB,YAAY,EAAEgB,YAAY,CAACC,MAAM,CAACjB;QACtC;MACJ,CAAC;MACD,OAAOvF,QAAQ,CAACsG,4BAA4B,CAACI,WAAW,CAAC;IAC7D;EACJ,CAAC;EAED,OAAOhE,eAAe;AAC1B"} \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js index f933a94413c..ce74acce4d7 100644 --- a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js +++ b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js @@ -1,6 +1,13 @@ import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema'; import { fillWithDefaultSettings } from '../../rx-schema-helper'; import { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils'; + +/** + * just type some common types + * to have better IDE autocomplete, + * all strings are allowed + */ + // we use two spaces because get-graphql-from-jsonschema does also export var SPACING = ' '; diff --git a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map index 56fcc661f15..ab03e08f342 100644 --- a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map +++ b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["getGraphqlSchemaFromJsonSchema","fillWithDefaultSettings","clone","ensureNotFalsy","flatClone","ucfirst","SPACING","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ucCollectionName","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","keys","startsWith","deletedField","withRevisions","strip","cloned","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":"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BAAmBA,CAAIL,MAAuB,EAAEkE,KAAe,EAA4B;EAChG,IAAMC,MAAW,GAAGvF,KAAK,CAACoB,MAAM,CAAC;EACjCkE,KAAK,CAACtE,OAAO,CAACwB,GAAG,IAAI;IACjB,OAAO+C,MAAM,CAACtD,UAAU,CAACO,GAAG,CAAC;EACjC,CAAC,CAAC;EACF,OAAO+C,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA,SAAStC,uBAAuBA,CAACD,GAAW,EAAE1B,gBAAwB,EAAU;EAC5E,OAAO0B,GAAG,CAACwC,OAAO,CAAC,GAAG,GAAGlE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file +{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["getGraphqlSchemaFromJsonSchema","fillWithDefaultSettings","clone","ensureNotFalsy","flatClone","ucfirst","SPACING","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ucCollectionName","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","keys","startsWith","deletedField","withRevisions","strip","cloned","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":"AAAA,SAASA,8BAA8B,QAAQ,6BAA6B;AAE5E,SAASC,uBAAuB,QAAQ,wBAAwB;AAGhE,SAASC,KAAK,EAAEC,cAAc,EAAEC,SAAS,EAAEC,OAAO,QAAQ,qBAAqB;;AAY/E;AACA;AACA;AACA;AACA;;AAsCA;AACA,OAAO,IAAMC,OAAO,GAAG,IAAI;;AAE3B;AACA;AACA;AACA,OAAO,SAASC,yBAAyBA,CACrCC,KAAqC,EACN;EAC/B,IAAMC,GAAoC,GAAG;IACzCC,QAAQ,EAAE,EAAE;IACZC,OAAO,EAAE,EAAE;IACXC,SAAS,EAAE,EAAE;IACbC,aAAa,EAAE,EAAE;IACjBC,MAAM,EAAE,EAAE;IACVC,KAAK,EAAE;EACX,CAAC;EAEDC,MAAM,CAACC,OAAO,CAACT,KAAK,CAAC,CAACU,OAAO,CAAC,CAAC,CAACC,cAAc,EAAEC,kBAAkB,CAAC,KAAK;IACpEA,kBAAkB,GAAGC,eAAe,CAACD,kBAAkB,CAAC;IAExD,IAAME,MAAM,GAAGF,kBAAkB,CAACE,MAAM;IACxC,IAAMC,QAAkB,GAAG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AAM,EAAE;IAClBrD,QAAQ,CAACqD,MAAM,GAAG,QAAQ;EAC9B;EACA,IAAI,CAACrD,QAAQ,CAACiC,OAAO,EAAE;IACnBjC,QAAQ,CAACiC,OAAO,GAAG,SAAS;EAChC;EACA,IAAI,CAAChD,KAAK,CAAC6C,YAAY,EAAE;IACrB7C,KAAK,CAAC6C,YAAY,GAAG,EAAE;EAC3B;EAGA,IAAI,CAAC7C,KAAK,CAAC+E,aAAa,EAAE;IACtB/E,KAAK,CAAC+E,aAAa,GAAG,KAAK;EAC/B;EAEA,IAAI,CAAC/E,KAAK,CAACoB,eAAe,EAAE;IACxBpB,KAAK,CAACoB,eAAe,GAAG,EAAE;EAC9B;EACA,IAAI,CAACpB,KAAK,CAACoD,gBAAgB,EAAE;IACzBpD,KAAK,CAACoD,gBAAgB,GAAG,EAAE;EAC/B;EAEA,OAAOpD,KAAK;AAChB;AAEA,SAASmB,mBAAmBA,CAAIL,MAAuB,EAAEkE,KAAe,EAA4B;EAChG,IAAMC,MAAW,GAAGvF,KAAK,CAACoB,MAAM,CAAC;EACjCkE,KAAK,CAACtE,OAAO,CAACwB,GAAG,IAAI;IACjB,OAAO+C,MAAM,CAACtD,UAAU,CAACO,GAAG,CAAC;EACjC,CAAC,CAAC;EACF,OAAO+C,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA,SAAStC,uBAAuBA,CAACD,GAAW,EAAE1B,gBAAwB,EAAU;EAC5E,OAAO0B,GAAG,CAACwC,OAAO,CAAC,GAAG,GAAGlE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-array.js b/dist/es/plugins/utils/utils-array.js index bb07cc3cceb..914611df30a 100644 --- a/dist/es/plugins/utils/utils-array.js +++ b/dist/es/plugins/utils/utils-array.js @@ -96,4 +96,7 @@ export function sumNumberArray(array) { } return count; } +export function maxOfNumbers(arr) { + return Math.max(...arr); +} //# sourceMappingURL=utils-array.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-array.js.map b/dist/es/plugins/utils/utils-array.js.map index 780229031f7..5f1841a8123 100644 --- a/dist/es/plugins/utils/utils-array.js.map +++ b/dist/es/plugins/utils/utils-array.js.map @@ -1 +1 @@ -{"version":3,"file":"utils-array.js","names":["lastOfArray","ar","length","shuffleArray","arr","slice","sort","Math","random","toArray","input","Array","isArray","batchArray","array","batchSize","ret","batch","splice","push","removeOneFromArrayIfMatches","condition","i","done","isMaybeReadonlyArray","x","arrayFilterNotEmpty","value","undefined","countUntilNotMatching","matchingFn","count","idx","item","matching","asyncFilter","predicate","filters","Promise","all","map","filter","index","sumNumberArray"],"sources":["../../../../src/plugins/utils/utils-array.ts"],"sourcesContent":["import type {\n MaybePromise,\n MaybeReadonly\n} from '../../types';\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.slice(0).sort(() => (Math.random() - 0.5));\n}\n\nexport function toArray(input: T | T[] | Readonly | Readonly): T[] {\n return Array.isArray(input) ? (input as any[]).slice(0) : [input];\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n\nexport function countUntilNotMatching(\n ar: T[],\n matchingFn: (v: T, idx: number) => boolean\n): number {\n let count = 0;\n let idx = -1;\n for (const item of ar) {\n idx = idx + 1;\n const matching = matchingFn(item, idx);\n if (matching) {\n count = count + 1;\n } else {\n break;\n }\n }\n return count;\n}\n\nexport async function asyncFilter(array: T[], predicate: (item: T, index: number, a: T[]) => MaybePromise): Promise {\n const filters = await Promise.all(\n array.map(predicate)\n );\n\n return array.filter((...[, index]) => filters[index]);\n}\n\n/**\n * @link https://stackoverflow.com/a/3762735\n */\nexport function sumNumberArray(array: number[]): number {\n let count = 0;\n for (let i = array.length; i--;) {\n count += array[i];\n }\n return count;\n}\n"],"mappings":"AAKA,OAAO,SAASA,WAAWA,CAAIC,EAAO,EAAiB;EACnD,OAAOA,EAAE,CAACA,EAAE,CAACC,MAAM,GAAG,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACA,OAAO,SAASC,YAAYA,CAAIC,GAAQ,EAAO;EAC3C,OAAOA,GAAG,CAACC,KAAK,CAAC,CAAC,CAAC,CAACC,IAAI,CAAC,MAAOC,IAAI,CAACC,MAAM,EAAE,GAAG,GAAI,CAAC;AACzD;AAEA,OAAO,SAASC,OAAOA,CAAIC,KAA4C,EAAO;EAC1E,OAAOC,KAAK,CAACC,OAAO,CAACF,KAAK,CAAC,GAAIA,KAAK,CAAWL,KAAK,CAAC,CAAC,CAAC,GAAG,CA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CAAC;EACb,IAAIC,GAAG,GAAG,CAAC,CAAC;EACZ,KAAK,IAAMC,KAAI,IAAIhC,EAAE,EAAE;IACnB+B,GAAG,GAAGA,GAAG,GAAG,CAAC;IACb,IAAME,QAAQ,GAAGJ,UAAU,CAACG,KAAI,EAAED,GAAG,CAAC;IACtC,IAAIE,QAAQ,EAAE;MACVH,KAAK,GAAGA,KAAK,GAAG,CAAC;IACrB,CAAC,MAAM;MACH;IACJ;EACJ;EACA,OAAOA,KAAK;AAChB;AAEA,OAAO,eAAeI,WAAWA,CAAIrB,KAAU,EAAEsB,SAAoE,EAAgB;EACjI,IAAMC,OAAO,GAAG,MAAMC,OAAO,CAACC,GAAG,CAC7BzB,KAAK,CAAC0B,GAAG,CAACJ,SAAS,CAAC,CACvB;EAED,OAAOtB,KAAK,CAAC2B,MAAM,CAAC,CAAC,GAAG,GAAGC,KAAK,CAAC,KAAKL,OAAO,CAACK,KAAK,CAAC,CAAC;AACzD;;AAEA;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAAC7B,KAAe,EAAU;EACpD,IAAIiB,KAAK,GAAG,CAAC;EACb,KAAK,IAAIT,CAAC,GAAGR,KAAK,CAACZ,MAAM,EAAEoB,CAAC,EAAE,GAAG;IAC7BS,KAAK,IAAIjB,KAAK,CAACQ,CAAC,CAAC;EACrB;EACA,OAAOS,KAAK;AAChB"} \ No newline at end of file +{"version":3,"file":"utils-array.js","names":["lastOfArray","ar","length","shuffleArray","arr","slice","sort","Math","random","toArray","input","Array","isArray","batchArray","array","batchSize","ret","batch","splice","push","removeOneFromArrayIfMatches","condition","i","done","isMaybeReadonlyArray","x","arrayFilterNotEmpty","value","undefined","countUntilNotMatching","matchingFn","count","idx","item","matching","asyncFilter","predicate","filters","Promise","all","map","filter","index","sumNumberArray","maxOfNumbers","max"],"sources":["../../../../src/plugins/utils/utils-array.ts"],"sourcesContent":["import type {\n MaybePromise,\n MaybeReadonly\n} from '../../types';\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.slice(0).sort(() => (Math.random() - 0.5));\n}\n\nexport function toArray(input: T | T[] | Readonly | Readonly): T[] {\n return Array.isArray(input) ? (input as any[]).slice(0) : [input];\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n\nexport function countUntilNotMatching(\n ar: T[],\n matchingFn: (v: T, idx: number) => boolean\n): number {\n let count = 0;\n let idx = -1;\n for (const item of ar) {\n idx = idx + 1;\n const matching = matchingFn(item, idx);\n if (matching) {\n count = count + 1;\n } else {\n break;\n }\n }\n return count;\n}\n\nexport async function asyncFilter(array: T[], predicate: (item: T, index: number, a: T[]) => MaybePromise): Promise {\n const filters = await Promise.all(\n array.map(predicate)\n );\n\n return array.filter((...[, index]) => filters[index]);\n}\n\n/**\n * @link https://stackoverflow.com/a/3762735\n */\nexport function sumNumberArray(array: number[]): number {\n let count = 0;\n for (let i = array.length; i--;) {\n count += array[i];\n }\n return count;\n}\n\nexport function maxOfNumbers(arr: number[]): number {\n return Math.max(...arr);\n}\n"],"mappings":"AAKA,OAAO,SAASA,WAAWA,CAAIC,EAAO,EAAiB;EACnD,OAAOA,EAAE,CAACA,EAAE,CAACC,MAAM,GAAG,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACA,OAAO,SAASC,YAAYA,CAAIC,GAAQ,EAAO;EAC3C,OAAOA,GAAG,CAACC,KAAK,CAAC,CAAC,CAAC,CAACC,IAAI,CAAC,MAAOC,IAAI,CAACC,MAAM,EAAE,GAAG,GAAI,CAAC;AACzD;AAEA,OAAO,SAASC,OAAOA,CAAIC,KAA4C,EAAO;EAC1E,OAAOC,KAAK,CAACC,OAAO,CAACF,KAAK,CAAC,GAAIA,KAAK,CAAWL,KAAK,CAAC,CAAC,CAAC,GAAG,CAACK,KAAK,CAAC;AACrE;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASG,UAAUA,CAAIC,KAAU,EAAEC,SAAiB,EAAS;EAChED,KAAK,GAAGA,KAAK,CAACT,KAAK,CAAC,CAAC,CAAC;EACtB,IAAMW,GAAU,GAAG,EAAE;EACrB,OAAOF,KAAK,CAACZ,MAAM,EAAE;IACjB,IAAMe,KAAK,GAAGH,KAAK,CAACI,MAAM,CAAC,CAAC,EAAEH,SAAS,CAAC;IACxCC,GAAG,CAACG,IAAI,CAACF,KAAK,CAAC;EACnB;EACA,OAAOD,GAAG;AACd;;AAEA;AACA;AACA;AACA,OAAO,SAASI,2BAA2BA,CAAInB,EAAO,EAAEoB,SAA4B,EAAO;EACvFpB,EAAE,GAAGA,EAAE,CAACI,KAAK,EAAE;EAC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,CAAC2B,MAAM,CAAC,CAAC,GAAG,GAAGC,KAAK,CAAC,KAAKL,OAAO,CAACK,KAAK,CAAC,CAAC;AACzD;;AAEA;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAAC7B,KAAe,EAAU;EACpD,IAAIiB,KAAK,GAAG,CAAC;EACb,KAAK,IAAIT,CAAC,GAAGR,KAAK,CAACZ,MAAM,EAAEoB,CAAC,EAAE,GAAG;IAC7BS,KAAK,IAAIjB,KAAK,CAACQ,CAAC,CAAC;EACrB;EACA,OAAOS,KAAK;AAChB;AAEA,OAAO,SAASa,YAAYA,CAACxC,GAAa,EAAU;EAChD,OAAOG,IAAI,CAACsC,GAAG,CAAC,GAAGzC,GAAG,CAAC;AAC3B"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-rxdb-version.js b/dist/es/plugins/utils/utils-rxdb-version.js index 0728a89e108..906761685fd 100644 --- a/dist/es/plugins/utils/utils-rxdb-version.js +++ b/dist/es/plugins/utils/utils-rxdb-version.js @@ -1,5 +1,5 @@ /** * This file is replaced in the 'npm run build:version' script. */ -export var RXDB_VERSION = '14.5.2'; +export var RXDB_VERSION = '14.6.0'; //# sourceMappingURL=utils-rxdb-version.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-rxdb-version.js.map b/dist/es/plugins/utils/utils-rxdb-version.js.map index 2ba453ad331..d35f21a981b 100644 --- a/dist/es/plugins/utils/utils-rxdb-version.js.map +++ b/dist/es/plugins/utils/utils-rxdb-version.js.map @@ -1 +1 @@ -{"version":3,"file":"utils-rxdb-version.js","names":["RXDB_VERSION"],"sources":["../../../../src/plugins/utils/utils-rxdb-version.ts"],"sourcesContent":["/**\n * This file is replaced in the 'npm run build:version' script.\n */\nexport const RXDB_VERSION = '14.5.2';\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,IAAMA,YAAY,GAAG,QAAQ"} \ No newline at end of file +{"version":3,"file":"utils-rxdb-version.js","names":["RXDB_VERSION"],"sources":["../../../../src/plugins/utils/utils-rxdb-version.ts"],"sourcesContent":["/**\n * This file is replaced in the 'npm run build:version' script.\n */\nexport const RXDB_VERSION = '14.6.0';\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,IAAMA,YAAY,GAAG,QAAQ"} \ No newline at end of file diff --git a/dist/es/rx-collection.js b/dist/es/rx-collection.js index e38f2520071..2b26b94d024 100644 --- a/dist/es/rx-collection.js +++ b/dist/es/rx-collection.js @@ -512,6 +512,15 @@ export var RxCollectionBase = /*#__PURE__*/function () { get: function () { return this.$.pipe(filter(cE => cE.operation === 'DELETE')); } + + // defaults + + /** + * When the collection is destroyed, + * these functions will be called an awaited. + * Used to automatically clean up stuff that + * belongs to this collection. + */ }, { key: "asRxCollection", get: function () { diff --git a/dist/es/rx-collection.js.map b/dist/es/rx-collection.js.map index c14b858f73e..60cfdce8969 100644 --- a/dist/es/rx-collection.js.map +++ b/dist/es/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","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","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","migrationNeeded","getDataMigrator","migrate","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","useDocs","useDocData","docs","hasHooks","Promise","all","doc","docsMap","insertRows","set","row","document","results","bulkWrite","rxDocuments","Object","values","writtenDocData","getCachedRxDocument","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","forEach","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","successIds","keys","bulkUpsert","insertData","useJsonByDocId","useJson","ret","slice","updatedDocs","status","collection","writeError","documentId","writeData","docDataInDb","documentInDb","newDoc","incrementalModify","concat","upsert","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","query","findOne","selector","limit","isArray","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","res","timeout","setTimeout","delete","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","hashFunction","_createClass","operation","colProto","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","devMode","isDevMode","entries","funName","defineProperty","version","creator","catch","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs/operators';\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';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocumentCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n MigrationState,\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} from './types';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\nimport { IncrementalWriteQueue } from './incremental-write';\nimport { beforeDocumentUpdateWrite } from './rx-document';\nimport { overwritable } from './overwritable';\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> {\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: KeyFunctionMap = {},\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 };\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 // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().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 docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[primaryPath] as any, 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 = Object.values(results.success)\n .map((writtenDocData) => this._docCache.getCachedRxDocument(writtenDocData));\n\n if (this.hasHooks('post', 'insert')) {\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: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\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 (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[] = Object.keys(results.success);\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: Object.values(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 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 let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('VD2', {\n collection: this.name,\n writeError: error\n });\n }\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n return newDoc;\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[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 > {\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 > {\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 // 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 as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\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 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.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,gBAAgB;AAEvB,SACIC,OAAO,EACPC,SAAS,EACTC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,QACjB,iBAAiB;AACxB,SACIC,0BAA0B,EAC1BC,iCAAiC,EACjCC,wBAAwB,QACrB,wBAAwB;AAC/B,SACIC,aAAa,EACbC,gBAAgB,QACb,YAAY;AACnB,SACIC,UAAU,EACVC,cAAc,QACX,YAAY;AAInB,SACIC,aAAa,QACV,aAAa;AACpB,SAEIC,gBAAgB,EAChBC,6BAA6B,QAC1B,eAAe;AACtB,SAEIC,uBAAuB,QACpB,uBAAuB;AAC9B,SACIC,mBAAmB,EACnBC,cAAc,QACX,SAAS;AA0ChB,SACIC,mBAAmB,QAChB,+BAA+B;AACtC,SACIC,yBAAyB,EACzBC,iCAAiC,EACjCC,0BAA0B,QAEvB,qBAAqB;AAC5B,SAASC,sBAAsB,QAAQ,wBAAwB;AAC/D,SAASC,qBAAqB,QAAQ,qBAAqB;AAC3D,SAASC,yBAAyB,QAAQ,eAAe;AACzD,SAASC,YAAY,QAAQ,gBAAgB;AAE7C,IAAMC,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;AAExB,WAAaC,gBAAgB;EAQzB;AACJ;AACA;;EAKI,SAAAA,iBACWC,QAAyE,EACzEC,IAAY,EACZC,MAAgC,EAChCC,uBAAwF,EACxFC,uBAAgD,GAAG,CAAC,CAAQ,EAC5DC,mBAAmC,GAAG,CAAC,CAAC,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Ac,CAAC,oBAAoB,EAAE;QACjC+I,UAAU;QACVyF,OAAO,EAAE;UACL1N,IAAI;UACJC,MAAM;UACNU,eAAe;UACfR,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtBsM,cAAc;UACdrM;QACJ;MACJ,CAAC,CAAC;MACF,OAAOwH,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAIC0F,KAAK,CAACC,GAAG,IAAI;MACV,OAAOjN,eAAe,CAAC+K,KAAK,EAAE,CACzBzH,IAAI,CAAC,MAAMsB,OAAO,CAACsI,MAAM,CAACD,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASE,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYjO,gBAAgB;AAC1C"} \ 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","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","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","migrationNeeded","getDataMigrator","migrate","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","useDocs","useDocData","docs","hasHooks","Promise","all","doc","docsMap","insertRows","set","row","document","results","bulkWrite","rxDocuments","Object","values","writtenDocData","getCachedRxDocument","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","forEach","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","successIds","keys","bulkUpsert","insertData","useJsonByDocId","useJson","ret","slice","updatedDocs","status","collection","writeError","documentId","writeData","docDataInDb","documentInDb","newDoc","incrementalModify","concat","upsert","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","query","findOne","selector","limit","isArray","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","res","timeout","setTimeout","delete","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","hashFunction","_createClass","operation","colProto","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","devMode","isDevMode","entries","funName","defineProperty","version","creator","catch","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs/operators';\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';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocumentCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n MigrationState,\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} from './types';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\nimport { IncrementalWriteQueue } from './incremental-write';\nimport { beforeDocumentUpdateWrite } from './rx-document';\nimport { overwritable } from './overwritable';\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> {\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: KeyFunctionMap = {},\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 };\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 // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().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 docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[primaryPath] as any, 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 = Object.values(results.success)\n .map((writtenDocData) => this._docCache.getCachedRxDocument(writtenDocData));\n\n if (this.hasHooks('post', 'insert')) {\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: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\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 (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[] = Object.keys(results.success);\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: Object.values(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 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 let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('VD2', {\n collection: this.name,\n writeError: error\n });\n }\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n return newDoc;\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[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 > {\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 > {\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 // 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 as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\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 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.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,gBAAgB;AAEvB,SACIC,OAAO,EACPC,SAAS,EACTC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,QACjB,iBAAiB;AACxB,SACIC,0BAA0B,EAC1BC,iCAAiC,EACjCC,wBAAwB,QACrB,wBAAwB;AAC/B,SACIC,aAAa,EACbC,gBAAgB,QACb,YAAY;AACnB,SACIC,UAAU,EACVC,cAAc,QACX,YAAY;AAInB,SACIC,aAAa,QACV,aAAa;AACpB,SAEIC,gBAAgB,EAChBC,6BAA6B,QAC1B,eAAe;AACtB,SAEIC,uBAAuB,QACpB,uBAAuB;AAC9B,SACIC,mBAAmB,EACnBC,cAAc,QACX,SAAS;AA0ChB,SACIC,mBAAmB,QAChB,+BAA+B;AACtC,SACIC,yBAAyB,EACzBC,iCAAiC,EACjCC,0BAA0B,QAEvB,qBAAqB;AAC5B,SAASC,sBAAsB,QAAQ,wBAAwB;AAC/D,SAASC,qBAAqB,QAAQ,qBAAqB;AAC3D,SAASC,yBAAyB,QAAQ,eAAe;AACzD,SAASC,YAAY,QAAQ,gBAAgB;AAE7C,IAAMC,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;AAExB,WAAaC,gBAAgB;EAQzB;AACJ;AACA;;EAKI,SAAAA,iBACWC,QAAyE,EACzEC,IAAY,EACZC,MAAgC,EAChCC,uBAAwF,EACxFC,uBAAgD,GAAG,CAAC,CAAQ,EAC5DC,mBAAmC,GAAG,CAAC,CAAC,EACxCC,OAAuB,GA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,CAAC,MAAM;MACR/E,cAAc,CAAC,oBAAoB,EAAE;QACjC+I,UAAU;QACVyF,OAAO,EAAE;UACL1N,IAAI;UACJC,MAAM;UACNU,eAAe;UACfR,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtBsM,cAAc;UACdrM;QACJ;MACJ,CAAC,CAAC;MACF,OAAOwH,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAIC0F,KAAK,CAACC,GAAG,IAAI;MACV,OAAOjN,eAAe,CAAC+K,KAAK,EAAE,CACzBzH,IAAI,CAAC,MAAMsB,OAAO,CAACsI,MAAM,CAACD,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASE,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYjO,gBAAgB;AAC1C"} \ No newline at end of file diff --git a/dist/es/rx-database.js b/dist/es/rx-database.js index ab3a3c85c1e..ba0cc040395 100644 --- a/dist/es/rx-database.js +++ b/dist/es/rx-database.js @@ -326,6 +326,43 @@ export var RxDatabaseBase = /*#__PURE__*/function () { get: function () { return this.observable$; } + + /** + * Because having unhandled exceptions would fail, + * we have to store the async errors of the constructor here + * so we can throw them later. + */ + + /** + * When the database is destroyed, + * these functions will be called an awaited. + * Used to automatically clean up stuff that + * belongs to this collection. + */ + + /** + * Unique token that is stored with the data. + * Used to detect if the dataset has been deleted + * and if two RxDatabase instances work on the same dataset or not. + * + * Because reading and writing the storageToken runs in the hot path + * of database creation, we do not await the storageWrites but instead + * work with the promise when we need the value. + */ + + /** + * Stores the whole state of the internal storage token document. + * We need this in some plugins. + */ + + /** + * Contains the ids of all event bulks that have been emitted + * by the database. + * Used to detect duplicates that come in again via BroadcastChannel + * or other streams. + * TODO instead of having this here, we should add a test to ensure each RxStorage + * behaves equal and does never emit duplicate eventBulks. + */ }, { key: "asRxDatabase", get: function () { diff --git a/dist/es/rx-database.js.map b/dist/es/rx-database.js.map index a67f96584a0..78355a77872 100644 --- a/dist/es/rx-database.js.map +++ b/dist/es/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["IdleQueue","pluginMissing","flatClone","PROMISE_RESOLVE_FALSE","randomCouchString","ensureNotFalsy","getDefaultRevision","getDefaultRxDocumentMeta","defaultHashSha256","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","idleQueue","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","eventBulks$","observable$","pipe","changeEventBulk","events","storageToken","storageTokenDocument","emittedEventBulkIds","asRxDatabase","catch","err","push","then","doc","data","_proto","prototype","$emit","has","id","add","next","removeCollectionDoc","schema","writeDoc","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","forEach","args","collectionName","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","database","hookData","conflictHandler","putDocsResult","ensureNoStartupErrors","error","_id","status","writeError","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","Promise","all","keys","map","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","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","statics","collectionNames","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 AllMigrationStates,\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} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\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';\nimport { removeCollectionStorages } from './rx-collection-helper';\nimport { overwritable } from './overwritable';\n\n/**\n * stores the used database 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> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\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 ) {\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 _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 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 Object.entries(collectionCreators).forEach(([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: 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 const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, 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 !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\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 /**\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');\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.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));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/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>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256\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);\n }\n USED_DATABASE_NAMES.add(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(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 ) 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): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\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 ))\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,QACd,iBAAiB;AACxB,SACIC,UAAU,QACP,YAAY;AACnB,SACIC,cAAc,QAEX,aAAa;AACpB,SACIC,cAAc,EACdC,mBAAmB,QAChB,SAAS;AAChB,SACIC,OAAO,QAGJ,MAAM;AACb,SACIC,QAAQ,QACL,gBAAgB;AACvB,SACIC,kBAAkB,QACf,iBAAiB;AACxB,SACIC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,EACzBC,qBAAqB,QAElB,qBAAqB;AAE5B,SAASC,YAAY,QAAQ,eAAe;AAC5C,SACIC,gCAAgC,EAChCC,yBAAyB,EACzBC,+BAA+B,EAC/BC,2BAA2B,EAC3BC,qBAAqB,EACrBC,sBAAsB,QACnB,8BAA8B;AACrC,SAASC,wBAAwB,QAAQ,wBAAwB;AACjE,SAASC,YAAY,QAAQ,gBAAgB;;AAE7C;AACA;AACA;AACA;AACA,IAAMC,mBAAgC,GAAG,IAAIC,GAAG,EAAE;AAElD,IAAIC,QAAQ,GAAG,CAAC;AAEhB,WAAaC,cAAc;EAQvB;AACJ;AACA;AACA;AACA;;E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AAC,sBAAsB,EAAE;IAC9CgJ,YAAY;IACZzH;EACJ,CAAC,CAAC;EAEF,MAAMmI,0BAA0B,CAACjB,MAAM,EAAE;EACzC,OAAOqB,sBAAsB;AACjC;AAEA,OAAO,SAASG,YAAYA,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAY9I,cAAc;AACxC;AAEA,OAAO,SAAS+I,OAAOA,CAAA,EAAW;EAC9B,OAAOhJ,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeiJ,iCAAiCA,CACnDrE,QAAoB,EACJ;EAChB,IAAMsE,QAAQ,GAAG,MAAMtE,QAAQ,CAACjD,oBAAoB;EACpD,OAAOuH,QAAQ,CAAC/G,IAAI,CAACgH,aAAa,KAAKvE,QAAQ,CAACzE,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAe6E,qBAAqBA,CACvCqD,UAAyC,EAC3C;EACE,MAAMA,UAAU,CAAC3G,YAAY;EAC7B,IAAI2G,UAAU,CAACpH,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMoH,UAAU,CAACpH,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ"} \ No newline at end of file +{"version":3,"file":"rx-database.js","names":["IdleQueue","pluginMissing","flatClone","PROMISE_RESOLVE_FALSE","randomCouchString","ensureNotFalsy","getDefaultRevision","getDefaultRxDocumentMeta","defaultHashSha256","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","idleQueue","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","eventBulks$","observable$","pipe","changeEventBulk","events","storageToken","storageTokenDocument","emittedEventBulkIds","asRxDatabase","catch","err","push","then","doc","data","_proto","prototype","$emit","has","id","add","next","removeCollectionDoc","schema","writeDoc","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","forEach","args","collectionName","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","database","hookData","conflictHandler","putDocsResult","ensureNoStartupErrors","error","_id","status","writeError","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","Promise","all","keys","map","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","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","statics","collectionNames","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 AllMigrationStates,\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} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\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';\nimport { removeCollectionStorages } from './rx-collection-helper';\nimport { overwritable } from './overwritable';\n\n/**\n * stores the used database 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> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\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 ) {\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 _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 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 Object.entries(collectionCreators).forEach(([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: 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 const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, 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 !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\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 /**\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');\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.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));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/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>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256\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);\n }\n USED_DATABASE_NAMES.add(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(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 ) 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): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\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 ))\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,QACd,iBA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AAMtE,QAAQ,CAACjD,oBAAoB;EACpD,OAAOuH,QAAQ,CAAC/G,IAAI,CAACgH,aAAa,KAAKvE,QAAQ,CAACzE,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAe6E,qBAAqBA,CACvCqD,UAAyC,EAC3C;EACE,MAAMA,UAAU,CAAC3G,YAAY;EAC7B,IAAI2G,UAAU,CAACpH,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMoH,UAAU,CAACpH,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ"} \ No newline at end of file diff --git a/dist/es/rx-query.js b/dist/es/rx-query.js index 5324f21a188..a61eb355d91 100644 --- a/dist/es/rx-query.js +++ b/dist/es/rx-query.js @@ -49,6 +49,13 @@ export var RxQueryBase = /*#__PURE__*/function () { this.isFindOneByIdQuery = isFindOneByIdQuery(this.collection.schema.primaryPath, mangoQuery); } var _proto = RxQueryBase.prototype; + /** + * Returns an observable that emits the results + * This should behave like an rxjs-BehaviorSubject which means: + * - Emit the current result-set on subscribe + * - Emit the new result-set when an RxChangeEvent comes in + * - Do not emit anything before the first result-set was created (no null) + */ /** * set the new result-data as result-docs of the query * @param newResultData json-docs that were received from the storage @@ -323,6 +330,13 @@ export var RxQueryBase = /*#__PURE__*/function () { } // stores the changeEvent-number of the last handled change-event + + // time stamps on when the last full exec over the database has run + // used to properly handle events that happen while the find-query is running + /** + * ensures that the exec-runs + * are not run in parallel + */ }, { key: "queryMatcher", get: function () { diff --git a/dist/es/rx-query.js.map b/dist/es/rx-query.js.map index dde5f6201de..bf5cee10563 100644 --- a/dist/es/rx-query.js.map +++ b/dist/es/rx-query.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.js","names":["BehaviorSubject","firstValueFrom","merge","mergeMap","filter","map","startWith","distinctUntilChanged","shareReplay","sortObject","stringifyFilter","pluginMissing","overwriteGetterForCaching","now","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","ensureNotFalsy","areRxDocumentArraysEqual","newRxError","runPluginHooks","calculateNewResults","triggerCacheReplacement","getQueryMatcher","normalizeMangoQuery","_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","docsData","docsMap","Map","docsDataMap","count","docs","time","Array","from","values","docData","_docCache","getCachedRxDocument","doc","set","primary","_data","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","mode","database","allowSlowCount","queryObj","ids","selector","$in","ret","mustBeQueried","forEach","getLatestDocumentDataIfExists","_deleted","push","findDocumentsById","Object","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","$","toString","stringObj","value","JSON","stringify","hookInput","rxQuery","jsonSchema","storage","statics","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","useResult","slice","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","latestAfter","resolve","docIds","docId","queryResult","documents","keys","$eq","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 stringifyFilter,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\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} from './types';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\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: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docsMap: Map>;\n docs: RxDocument[];\n count: number;\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 time: number;\n } | 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.docs.length === 0 ? null : useResult.docs[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.docs.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\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\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsMap: new Map(),\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const docsDataMap = new Map();\n const docsMap = new Map();\n const docs = newResultData.map(docData => this.collection._docCache.getCachedRxDocument(docData));\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 */\n const docsData = docs.map(doc => {\n docsDataMap.set(doc.primary, doc._data);\n docsMap.set(doc.primary, doc);\n return doc._data;\n });\n\n this._result = {\n docsData,\n docsMap,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\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 Object.values(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)\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, stringifyFilter);\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 runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\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\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\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 * 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 docs.push(docData);\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n const docsMap = await collection.storageInstance.findDocumentsById(docIds, false);\n Object.values(docsMap).forEach(docData => {\n docs.push(docData);\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 docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n docData = docsMap[docId];\n }\n if (docData) {\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,eAAe,EACfC,aAAa,EACbC,yBAAyB,EACzBC,GAAG,EACHC,qBAAqB,EACrBC,0BAA0B,EAC1BC,cAAc,EACdC,wBAAwB,QACrB,iBAAiB;AACxB,SACIC,UAAU,QACP,YAAY;AACnB,SACIC,cAAc,QACX,SAAS;AAehB,SAASC,mBAAmB,QAAQ,gBAAgB;AACpD,SAASC,uBAAuB,QAAQ,eAAe;AACvD,SAASC,eAAe,EAAEC,mBAAmB,QAAQ,mBAAmB;AAExE,IAAIC,WAAW,GAAG,CAAC;AACnB,IAAMC,UAAU,GAAG,SAAAA,CAAA,EAAoB;EACnC,OAAO,EAAED,WAAW;AACxB,CAAC;AAED,WAAaE,WAAW;EAQpB;AACJ;AACA;;EAII;;EAKA;;EAMA;AACJ;AACA;AACA;;EAiBI,SAAAA,YACWC,EAAa,EACbC,UAA2C,EAC3CC,UAAmC;EAC1C;EACOC,KAAU,GAAG,CAAC,CAAC,EACxB;IAAA,KA7CKC,EAAE,GAAWN,UAAU,EAAE;IAAA,KAKzBO,sBAAsB,GAAW,CAAC;IAAA,KAClCC,aAAa,GAAGpB,GAAG,EAAE;IAAA,KAGrBqB,gBAAgB,GAAG,CAAC;IAAA,KAEpBC,QAAQ,GAAG,KAAK;IAAA,KAGhBC,SAAS,GAAG,IAAIpC,eAAe,CAAC,IAAI,CAAC;IAAA,KASrCqC,OAAO,GAaH,IAAI;IAAA,KAqFRC,kBAAkB,GAAgB,CAAC,CAAC;IAAA,KAIpCC,cAAc,GAAW,CAAC;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EACA,IACI,CAACA,KAAK,CAAC0B,IAAI,IACX1B,KAAK,CAAChB,QAAQ,IACdS,MAAM,CAACkF,IAAI,CAAC3E,KAAK,CAAChB,QAAQ,CAAC,CAACX,MAAM,KAAK,CAAC,IACxC2B,KAAK,CAAChB,QAAQ,CAACjC,WAAW,CAAC,EAC7B;IACE,IAAMsD,KAAU,GAAGL,KAAK,CAAChB,QAAQ,CAACjC,WAAW,CAAC;IAC9C,IAAI,OAAOsD,KAAK,KAAK,QAAQ,EAAE;MAC3B,OAAOA,KAAK;IAChB,CAAC,MAAM,IACHZ,MAAM,CAACkF,IAAI,CAACtE,KAAK,CAAC,CAAChC,MAAM,KAAK,CAAC,IAC/B,OAAOgC,KAAK,CAACuE,GAAG,KAAK,QAAQ,EAC/B;MACE,OAAOvE,KAAK,CAACuE,GAAG;IACpB;;IAEA;IACA,IACInF,MAAM,CAACkF,IAAI,CAACtE,KAAK,CAAC,CAAChC,MAAM,KAAK,CAAC,IAC/BV,KAAK,CAACsD,OAAO,CAACZ,KAAK,CAACuE,GAAG,CAAC;IACxB;IACA,CAAEvE,KAAK,CAACuE,GAAG,CAAWC,IAAI,CAACC,CAAC,IAAI,OAAOA,CAAC,KAAK,QAAQ,CAAC,EACxD;MACE,OAAOzE,KAAK,CAACuE,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIA,OAAO,SAASG,SAASA,CAACC,GAAQ,EAAW;EACzC,OAAOA,GAAG,YAAYpJ,WAAW;AACrC"} \ No newline at end of file +{"version":3,"file":"rx-query.js","names":["BehaviorSubject","firstValueFrom","merge","mergeMap","filter","map","startWith","distinctUntilChanged","shareReplay","sortObject","stringifyFilter","pluginMissing","overwriteGetterForCaching","now","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","ensureNotFalsy","areRxDocumentArraysEqual","newRxError","runPluginHooks","calculateNewResults","triggerCacheReplacement","getQueryMatcher","normalizeMangoQuery","_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","docsData","docsMap","Map","docsDataMap","count","docs","time","Array","from","values","docData","_docCache","getCachedRxDocument","doc","set","primary","_data","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","mode","database","allowSlowCount","queryObj","ids","selector","$in","ret","mustBeQueried","forEach","getLatestDocumentDataIfExists","_deleted","push","findDocumentsById","Object","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","$","toString","stringObj","value","JSON","stringify","hookInput","rxQuery","jsonSchema","storage","statics","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","useResult","slice","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","latestAfter","resolve","docIds","docId","queryResult","documents","keys","$eq","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 stringifyFilter,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\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} from './types';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\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: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docsMap: Map>;\n docs: RxDocument[];\n count: number;\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 time: number;\n } | 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.docs.length === 0 ? null : useResult.docs[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.docs.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\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\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsMap: new Map(),\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const docsDataMap = new Map();\n const docsMap = new Map();\n const docs = newResultData.map(docData => this.collection._docCache.getCachedRxDocument(docData));\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 */\n const docsData = docs.map(doc => {\n docsDataMap.set(doc.primary, doc._data);\n docsMap.set(doc.primary, doc);\n return doc._data;\n });\n\n this._result = {\n docsData,\n docsMap,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\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 Object.values(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)\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, stringifyFilter);\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 runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\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\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\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 * 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 docs.push(docData);\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n const docsMap = await collection.storageInstance.findDocumentsById(docIds, false);\n Object.values(docsMap).forEach(docData => {\n docs.push(docData);\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 docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n docData = docsMap[docId];\n }\n if (docData) {\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}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AK,CAAChB,QAAQ,IACdS,MAAM,CAACkF,IAAI,CAAC3E,KAAK,CAAChB,QAAQ,CAAC,CAACX,MAAM,KAAK,CAAC,IACxC2B,KAAK,CAAChB,QAAQ,CAACjC,WAAW,CAAC,EAC7B;IACE,IAAMsD,KAAU,GAAGL,KAAK,CAAChB,QAAQ,CAACjC,WAAW,CAAC;IAC9C,IAAI,OAAOsD,KAAK,KAAK,QAAQ,EAAE;MAC3B,OAAOA,KAAK;IAChB,CAAC,MAAM,IACHZ,MAAM,CAACkF,IAAI,CAACtE,KAAK,CAAC,CAAChC,MAAM,KAAK,CAAC,IAC/B,OAAOgC,KAAK,CAACuE,GAAG,KAAK,QAAQ,EAC/B;MACE,OAAOvE,KAAK,CAACuE,GAAG;IACpB;;IAEA;IACA,IACInF,MAAM,CAACkF,IAAI,CAACtE,KAAK,CAAC,CAAChC,MAAM,KAAK,CAAC,IAC/BV,KAAK,CAACsD,OAAO,CAACZ,KAAK,CAACuE,GAAG,CAAC;IACxB;IACA,CAAEvE,KAAK,CAACuE,GAAG,CAAWC,IAAI,CAACC,CAAC,IAAI,OAAOA,CAAC,KAAK,QAAQ,CAAC,EACxD;MACE,OAAOzE,KAAK,CAACuE,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIA,OAAO,SAASG,SAASA,CAACC,GAAQ,EAAW;EACzC,OAAOA,GAAG,YAAYpJ,WAAW;AACrC"} \ No newline at end of file diff --git a/dist/es/types/rx-query.d.js b/dist/es/types/rx-query.d.js index 6771c15c1ef..a0a32ab6cdd 100644 --- a/dist/es/types/rx-query.d.js +++ b/dist/es/types/rx-query.d.js @@ -1,2 +1,21 @@ import { RxQueryBase } from '../rx-query'; + +/** + * Typed Mango Query Selector + * @link https://github.com/mongodb/node-mongodb-native/blob/26bce4a8debb65df5a42dc8599e886c9c83de10d/src/mongo_types.ts + * @link https://stackoverflow.com/a/58436959/3443137 + */ + +/* + * The MongoDB query library is huge and we do not need all the operators. + * If you add an operator here, make sure that you properly add a test in + * the file /test/unit/rx-storage-query-correctness.test.ts + * + * @link https://github.com/kofrasa/mingo#es6 + */ + +/** + * Discussion was at: + * @link https://github.com/pubkey/rxdb/issues/1972 + */ //# sourceMappingURL=rx-query.d.js.map \ No newline at end of file diff --git a/dist/es/types/rx-query.d.js.map b/dist/es/types/rx-query.d.js.map index 2fd56d1fd01..80fedf7696f 100644 --- a/dist/es/types/rx-query.d.js.map +++ b/dist/es/types/rx-query.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.d.js","names":["RxQueryBase"],"sources":["../../../src/types/rx-query.d.ts"],"sourcesContent":["import {\n RxQueryBase\n} from '../rx-query';\nimport { StringKeys } from './util';\n\n/**\n * Typed Mango Query Selector\n * @link https://github.com/mongodb/node-mongodb-native/blob/26bce4a8debb65df5a42dc8599e886c9c83de10d/src/mongo_types.ts\n * @link https://stackoverflow.com/a/58436959/3443137\n */\n\ntype Join = K extends string | number ?\n P extends string | number ?\n `${K}${'' extends P ? '' : '.'}${P}`\n : never : never;\n\nexport type Paths = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: K extends string | number ?\n `${K}` | (Paths extends infer R ? Join : never)\n : never\n }[keyof T] : '';\n\nexport type Leaves = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: Join> }[keyof T] : '';\ntype Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]];\n\nexport type PropertyType = string extends Property\n ? unknown\n : Property extends keyof Type\n ? Type[Property]\n : Property extends `${number}`\n ? Type extends ReadonlyArray\n ? ArrayType\n : unknown\n : Property extends `${infer Key}.${infer Rest}`\n ? Key extends `${number}`\n ? Type extends ReadonlyArray\n ? PropertyType\n : unknown\n : Key extends keyof Type\n ? Type[Key] extends Map\n ? MapType\n : PropertyType\n : unknown\n : unknown;\n\n\n/*\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport interface MangoQueryOperators {\n $eq?: PathValueType;\n $gt?: PathValueType;\n $gte?: PathValueType;\n $lt?: PathValueType;\n $lte?: PathValueType;\n $ne?: PathValueType;\n $in?: PathValueType[];\n $nin?: PathValueType[];\n $regex?: string | RegExp;\n $options?: string;\n $exists?: boolean;\n $type?: 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object';\n $mod?: number;\n $not?: PathValueType;\n $size?: number;\n $elemMatch?: MangoQuerySelector;\n}\n\nexport type MangoQuerySelector = Partial<{\n [Property in Paths]: MangoQueryOperators | PropertyType;\n}> & {\n $and?: MangoQuerySelector[];\n $or?: MangoQuerySelector[];\n $nor?: MangoQuerySelector[];\n};\n\n/**\n * Discussion was at:\n * @link https://github.com/pubkey/rxdb/issues/1972\n */\nexport type MangoQuerySortDirection = 'asc' | 'desc';\nexport type MangoQuerySortPart = {\n [k in StringKeys | string]: MangoQuerySortDirection;\n};\n\nexport type MangoQuerySelectorAndIndex = {\n /**\n * Selector is optional,\n * if not given, the query matches all documents\n * that are not _deleted=true.\n */\n selector?: MangoQuerySelector;\n /**\n * By default, the RxStorage implementation\n * decides which index to use when running the query.\n *\n * For better performance, a different index might be defined\n * by setting it in the query.\n * How this improves performance and if the defined index is used,\n * depends on the RxStorage implementation.\n */\n index?: string | string[];\n};\n\nexport type MangoQueryNoLimit = MangoQuerySelectorAndIndex & {\n /**\n * Sorting of the results.\n * If no sort is set, RxDB will sort by the primary key.\n * Also if sort is set, RxDB will add primaryKey sorting\n * if the primaryKey was not in the sort parameters before.\n * This ensures that there is a deterministic sorting of the\n * results, not mather at which order the documents have been\n * inserted into the storage.\n */\n sort?: MangoQuerySortPart[];\n};\n\nexport type MangoQuery = MangoQueryNoLimit & {\n skip?: number;\n limit?: number;\n};\n\nexport type RxQueryOP = 'find' | 'findOne' | 'count' | 'findByIds';\n\nexport declare class RxQuery extends RxQueryBase {\n equals(queryObj: any): RxQuery;\n eq(queryObj: any): RxQuery;\n or(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n nor(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n and(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n gt(queryObj: any): RxQuery;\n gte(queryObj: any): RxQuery;\n lt(queryObj: any): RxQuery;\n lte(queryObj: any): RxQuery;\n ne(queryObj: any): RxQuery;\n in(queryObj: any[]): RxQuery;\n nin(queryObj: any[]): RxQuery;\n all(queryObj: any): RxQuery;\n regex(queryObj: RegExp): RxQuery;\n exists(queryObj: any): RxQuery;\n elemMatch(queryObj: any): RxQuery;\n mod(p1: any, p2: any, p3: any): RxQuery;\n}\n"],"mappings":"AAAA,SACIA,WAAW,QACR,aAAa"} \ No newline at end of file +{"version":3,"file":"rx-query.d.js","names":["RxQueryBase"],"sources":["../../../src/types/rx-query.d.ts"],"sourcesContent":["import {\n RxQueryBase\n} from '../rx-query';\nimport { StringKeys } from './util';\n\n/**\n * Typed Mango Query Selector\n * @link https://github.com/mongodb/node-mongodb-native/blob/26bce4a8debb65df5a42dc8599e886c9c83de10d/src/mongo_types.ts\n * @link https://stackoverflow.com/a/58436959/3443137\n */\n\ntype Join = K extends string | number ?\n P extends string | number ?\n `${K}${'' extends P ? '' : '.'}${P}`\n : never : never;\n\nexport type Paths = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: K extends string | number ?\n `${K}` | (Paths extends infer R ? Join : never)\n : never\n }[keyof T] : '';\n\nexport type Leaves = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: Join> }[keyof T] : '';\ntype Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]];\n\nexport type PropertyType = string extends Property\n ? unknown\n : Property extends keyof Type\n ? Type[Property]\n : Property extends `${number}`\n ? Type extends ReadonlyArray\n ? ArrayType\n : unknown\n : Property extends `${infer Key}.${infer Rest}`\n ? Key extends `${number}`\n ? Type extends ReadonlyArray\n ? PropertyType\n : unknown\n : Key extends keyof Type\n ? Type[Key] extends Map\n ? MapType\n : PropertyType\n : unknown\n : unknown;\n\n\n/*\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport interface MangoQueryOperators {\n $eq?: PathValueType;\n $gt?: PathValueType;\n $gte?: PathValueType;\n $lt?: PathValueType;\n $lte?: PathValueType;\n $ne?: PathValueType;\n $in?: PathValueType[];\n $nin?: PathValueType[];\n $regex?: string | RegExp;\n $options?: string;\n $exists?: boolean;\n $type?: 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object';\n $mod?: number;\n $not?: PathValueType;\n $size?: number;\n $elemMatch?: MangoQuerySelector;\n}\n\nexport type MangoQuerySelector = Partial<{\n [Property in Paths]: MangoQueryOperators | PropertyType;\n}> & {\n $and?: MangoQuerySelector[];\n $or?: MangoQuerySelector[];\n $nor?: MangoQuerySelector[];\n};\n\n/**\n * Discussion was at:\n * @link https://github.com/pubkey/rxdb/issues/1972\n */\nexport type MangoQuerySortDirection = 'asc' | 'desc';\nexport type MangoQuerySortPart = {\n [k in StringKeys | string]: MangoQuerySortDirection;\n};\n\nexport type MangoQuerySelectorAndIndex = {\n /**\n * Selector is optional,\n * if not given, the query matches all documents\n * that are not _deleted=true.\n */\n selector?: MangoQuerySelector;\n /**\n * By default, the RxStorage implementation\n * decides which index to use when running the query.\n *\n * For better performance, a different index might be defined\n * by setting it in the query.\n * How this improves performance and if the defined index is used,\n * depends on the RxStorage implementation.\n */\n index?: string | string[];\n};\n\nexport type MangoQueryNoLimit = MangoQuerySelectorAndIndex & {\n /**\n * Sorting of the results.\n * If no sort is set, RxDB will sort by the primary key.\n * Also if sort is set, RxDB will add primaryKey sorting\n * if the primaryKey was not in the sort parameters before.\n * This ensures that there is a deterministic sorting of the\n * results, not mather at which order the documents have been\n * inserted into the storage.\n */\n sort?: MangoQuerySortPart[];\n};\n\nexport type MangoQuery = MangoQueryNoLimit & {\n skip?: number;\n limit?: number;\n};\n\nexport type RxQueryOP = 'find' | 'findOne' | 'count' | 'findByIds';\n\nexport declare class RxQuery extends RxQueryBase {\n equals(queryObj: any): RxQuery;\n eq(queryObj: any): RxQuery;\n or(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n nor(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n and(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n gt(queryObj: any): RxQuery;\n gte(queryObj: any): RxQuery;\n lt(queryObj: any): RxQuery;\n lte(queryObj: any): RxQuery;\n ne(queryObj: any): RxQuery;\n in(queryObj: any[]): RxQuery;\n nin(queryObj: any[]): RxQuery;\n all(queryObj: any): RxQuery;\n regex(queryObj: RegExp): RxQuery;\n exists(queryObj: any): RxQuery;\n elemMatch(queryObj: any): RxQuery;\n mod(p1: any, p2: any, p3: any): RxQuery;\n}\n"],"mappings":"AAAA,SACIA,WAAW,QACR,aAAa;;AAGpB;AACA;AACA;AACA;AACA;;AAuCA;AACA;AACA;AACA;AACA;AACA;AACA;;AA4BA;AACA;AACA;AACA"} \ No newline at end of file diff --git a/dist/lib/custom-index.js b/dist/lib/custom-index.js index 65f5b29af3c..56eb24ec3e4 100644 --- a/dist/lib/custom-index.js +++ b/dist/lib/custom-index.js @@ -85,9 +85,6 @@ function getIndexableStringMonad(schema, index) { } else { // is number var parsedLengths = props.parsedLengths; - if (!fieldValue) { - fieldValue = 0; - } str += getNumberIndexString(parsedLengths, fieldValue); } } @@ -107,6 +104,8 @@ function getStringLengthOfIndexNumber(schemaPart) { decimals = multipleOfParts[1].length; } return { + minimum, + maximum, nonDecimals, decimals, roundedMinimum: minimum @@ -135,12 +134,32 @@ function getPrimaryKeyFromIndexableString(indexableString, primaryKeyLength) { return primaryKey; } function getNumberIndexString(parsedLengths, fieldValue) { + /** + * Ensure that the given value is in the boundaries + * of the schema, otherwise it would create a broken index string. + * This can happen for example if you have a minimum of 0 + * and run a query like + * selector { + * numField: { $gt: -1000 } + * } + */ + if (typeof fieldValue === 'undefined') { + fieldValue = 0; + } + if (fieldValue < parsedLengths.minimum) { + fieldValue = parsedLengths.minimum; + } + if (fieldValue > parsedLengths.maximum) { + fieldValue = parsedLengths.maximum; + } var str = ''; var nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString(); str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0'); var splitByDecimalPoint = fieldValue.toString().split('.'); var decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0'; - str += decimalValueAsString.padEnd(parsedLengths.decimals, '0'); + if (parsedLengths.decimals > 0) { + str += decimalValueAsString.padEnd(parsedLengths.decimals, '0'); + } return str; } function getStartIndexStringFromLowerBound(schema, index, lowerBound, inclusiveStart) { diff --git a/dist/lib/custom-index.js.map b/dist/lib/custom-index.js.map index 652bb446327..62ebae224f9 100644 --- a/dist/lib/custom-index.js.map +++ b/dist/lib/custom-index.js.map @@ -1 +1 @@ -{"version":3,"file":"custom-index.js","names":["_rxSchemaHelper","require","_utils","_queryPlanner","getIndexMeta","schema","index","fieldNameProperties","map","fieldName","schemaPart","getSchemaByObjectPath","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","objectPathMonad","getIndexableStringMonad","ret","docData","str","i","length","props","fieldValue","padEnd","maxLength","boolToStr","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trimEnd","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","ensureNotFalsy","INDEX_MAX","INDEX_MIN","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n) {\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n return fieldNameProperties;\n}\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n const fieldNameProperties = getIndexMeta(schema, index);\n\n /**\n * @hotPath Performance of this function is very critical!\n */\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n for (let i = 0; i < fieldNameProperties.length; ++i) {\n const props = fieldNameProperties[i];\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n let fieldValue = props.getValueFn(docData);\n if (type === 'string') {\n // is string\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n // is boolean\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n // is number\n const parsedLengths = props.parsedLengths as ParsedLengths;\n if (!fieldValue) {\n fieldValue = 0;\n }\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n }\n return str;\n };\n return ret;\n}\n\ndeclare type ParsedLengths = {\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\nexport function getIndexStringLength(\n schema: RxJsonSchema>,\n index: string[]\n): number {\n const fieldNameProperties = getIndexMeta(schema, index);\n let length = 0;\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n if (type === 'string') {\n length += schemaPart.maxLength as number;\n } else if (type === 'boolean') {\n length += 1;\n } else {\n const parsedLengths = props.parsedLengths as ParsedLengths;\n length = length + parsedLengths.nonDecimals + parsedLengths.decimals;\n }\n\n });\n return length;\n}\n\n\nexport function getPrimaryKeyFromIndexableString(\n indexableString: string,\n primaryKeyLength: number\n): string {\n const paddedPrimaryKey = indexableString.slice(primaryKeyLength * -1);\n const primaryKey = paddedPrimaryKey.trimEnd();\n return primaryKey;\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":";;;;;;;;;;;;;AAMA,IAAAA,eAAA,GAAAC,OAAA;AAMA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,aAAA,GAAAF,OAAA;AAjBA;AACA;AACA;AACA;AACA;;AAgBO,SAASG,YAAYA,CACxBC,MAA+C,EAC/CC,KAAe,EACjB;EACE;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAACC,SAAS,IAAI;IACzB,IAAMC,UAAU,GAAG,IAAAC,qCAAqB,EACpCN,MAAM,EACNI,SAAS,CACZ;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIE,KAAK,CAAC,iBAAiB,GAAGH,SAAS,CAAC;IAClD;IACA,IAAMI,IAAI,GAAGH,UAAU,CAACG,IAAI;IAC5B,IAAIC,aAAwC;IAC5C,IAAID,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,SAAS,EAAE;MACzCC,aAAa,GAAGC,4BAA4B,CACxCL,UAAU,CACb;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G,GAAG,GAAG;UACzC/C,GAAG,IAAI2C,QAAQ,CAACC,MAAM,CAACrD,aAAa,CAACyB,WAAW,GAAGzB,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHpB,GAAG,IAAIQ,oBAAoB,CACvBjB,aAAa,EACbgD,KAAK,CACR;QACL;QACA;MACJ;QACI,MAAM,IAAIlD,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOU,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"custom-index.js","names":["_rxSchemaHelper","require","_utils","_queryPlanner","getIndexMeta","schema","index","fieldNameProperties","map","fieldName","schemaPart","getSchemaByObjectPath","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","objectPathMonad","getIndexableStringMonad","ret","docData","str","i","length","props","fieldValue","padEnd","maxLength","boolToStr","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trimEnd","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","ensureNotFalsy","INDEX_MAX","INDEX_MIN","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n) {\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n return fieldNameProperties;\n}\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n const fieldNameProperties = getIndexMeta(schema, index);\n\n /**\n * @hotPath Performance of this function is very critical!\n */\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n for (let i = 0; i < fieldNameProperties.length; ++i) {\n const props = fieldNameProperties[i];\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n let fieldValue = props.getValueFn(docData);\n if (type === 'string') {\n // is string\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n // is boolean\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n // is number\n const parsedLengths = props.parsedLengths as ParsedLengths;\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n }\n return str;\n };\n return ret;\n}\n\n\n\ndeclare type ParsedLengths = {\n minimum: number;\n maximum: number;\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n minimum,\n maximum,\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\nexport function getIndexStringLength(\n schema: RxJsonSchema>,\n index: string[]\n): number {\n const fieldNameProperties = getIndexMeta(schema, index);\n let length = 0;\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n if (type === 'string') {\n length += schemaPart.maxLength as number;\n } else if (type === 'boolean') {\n length += 1;\n } else {\n const parsedLengths = props.parsedLengths as ParsedLengths;\n length = length + parsedLengths.nonDecimals + parsedLengths.decimals;\n }\n\n });\n return length;\n}\n\n\nexport function getPrimaryKeyFromIndexableString(\n indexableString: string,\n primaryKeyLength: number\n): string {\n const paddedPrimaryKey = indexableString.slice(primaryKeyLength * -1);\n const primaryKey = paddedPrimaryKey.trimEnd();\n return primaryKey;\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n /**\n * Ensure that the given value is in the boundaries\n * of the schema, otherwise it would create a broken index string.\n * This can happen for example if you have a minimum of 0\n * and run a query like\n * selector {\n * numField: { $gt: -1000 }\n * }\n */\n if (typeof fieldValue === 'undefined') {\n fieldValue = 0;\n }\n if (fieldValue < parsedLengths.minimum) {\n fieldValue = parsedLengths.minimum;\n }\n if (fieldValue > parsedLengths.maximum) {\n fieldValue = parsedLengths.maximum;\n }\n\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n if (parsedLengths.decimals > 0) {\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n }\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":";;;;;;;;;;;;;AAMA,IAAAA,eAAA,GAAAC,OAAA;AAMA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,aAAA,GAAAF,OAAA;AAjBA;AACA;AACA;AACA;AACA;;AAgBO,SAASG,YAAYA,CACxBC,MAA+C,EAC/CC,KAAe,EACjB;EACE;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAACC,SAAS,IAAI;IACzB,IAAMC,UAAU,GAAG,IAAAC,qCAAqB,EACpCN,MAAM,EACNI,SAAS,CACZ;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIE,KAAK,CAAC,iBAAiB,GAAGH,SAAS,CAAC;IAClD;IACA,IAAMI,IAAI,GAAGH,UAAU,CAACG,IAAI;IAC5B,IAAIC,aAAwC;IAC5C,IAAID,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,SAAS,EAAE;MACzCC,aAAa,GAAGC,4BAA4B,CACxCL,UAAU,CACb;IACL;IAEA,OAAO;MACHD,SAAS;MACTC,UAAU;MACVI,aAAa;MACb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AS,GAAGgC,KAAK,GAAG,GAAG,GAAG,GAAG;UACnCvC,GAAG,IAAIO,SAAS;QACpB;QACA;MACJ,KAAK,QAAQ;MACb,KAAK,SAAS;QACV,IAAMhB,aAAa,GAAGC,4BAA4B,CAC9CL,UAAU,CACb;QACD,IAAIoD,KAAK,KAAK,IAAI,IAAIA,KAAK,KAAKE,uBAAS,EAAE;UACvC,IAAME,QAAQ,GAAGI,YAAY,GAAG,GAAG,GAAG,GAAG;UACzC/C,GAAG,IAAI2C,QAAQ,CAACC,MAAM,CAACrD,aAAa,CAACyB,WAAW,GAAGzB,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHpB,GAAG,IAAIQ,oBAAoB,CACvBjB,aAAa,EACbgD,KAAK,CACR;QACL;QACA;MACJ;QACI,MAAM,IAAIlD,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOU,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/doc-cache.js b/dist/lib/doc-cache.js index 20a597b0f9d..8139b77af0a 100644 --- a/dist/lib/doc-cache.js +++ b/dist/lib/doc-cache.js @@ -7,6 +7,9 @@ exports.DocumentCache = void 0; var _utils = require("./plugins/utils"); var _overwritable = require("./overwritable"); var _rxChangeEvent = require("./rx-change-event"); +/** + * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + */ /** * The DocumentCache stores RxDocument objects * by their primary key and revision. diff --git a/dist/lib/doc-cache.js.map b/dist/lib/doc-cache.js.map index e38bd526aee..08cc3d5d9b3 100644 --- a/dist/lib/doc-cache.js.map +++ b/dist/lib/doc-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"doc-cache.js","names":["_utils","require","_overwritable","_rxChangeEvent","DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","documentByRevisionHeight","delete","revisionHeight","size","undefined","subscribe","changeEvent","documentId","documentData","getDocumentDataOfRxChangeEvent","latestDoc","_proto","prototype","getCachedRxDocument","docData","getHeightOfRevision","_rev","getFromMapOrCreate","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","overwritable","deepFreezeWhenDevMode","set","createWeakRefWithFallback","register","getLatestDocumentData","getFromMapOrThrow","getLatestDocumentDataIfExists","exports","HAS_WEAK_REF","WeakRef","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision\n} from './plugins/utils';\nimport {\n overwritable\n} from './overwritable';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\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 documentByRevisionHeight: 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 latestDoc: 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 private 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.documentByRevisionHeight.delete(docMeta.revisionHeight);\n if (cacheItem.documentByRevisionHeight.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 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.latestDoc = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n */\n public getCachedRxDocument(docData: RxDocumentData): RxDocument {\n const docId: string = (docData as any)[this.primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n this.cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const cachedRxDocumentWeakRef: WeakRef> | undefined = cacheItem.documentByRevisionHeight.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = overwritable.deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = this.documentCreator(docData) as RxDocument;\n cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n\n if (this.registry) {\n this.registry.register(cachedRxDocument, {\n docId,\n revisionHeight\n });\n }\n }\n return cachedRxDocument;\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.latestDoc;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.latestDoc;\n }\n }\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n documentByRevisionHeight: new Map(),\n latestDoc: docData\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';\nfunction createWeakRefWithFallback(obj: T): WeakRef {\n if (HAS_WEAK_REF) {\n return new WeakRef(obj) as any;\n } else {\n return {\n deref() {\n return obj;\n }\n } as any;\n }\n}\n"],"mappings":";;;;;;AAKA,IAAAA,MAAA,GAAAC,OAAA;AAKA,IAAAC,aAAA,GAAAD,OAAA;AAGA,IAAAE,cAAA,GAAAF,OAAA;AAqCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AATA,IAUaG,aAAa;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI,SAAAA,cACoBC,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA,KAhCKC,gBAAgB,GAAG,IAAIC,GAAG,EAA4C;IAAA,KAQrEC,QAAQ,GAAqD,OAAOC,oBAAoB,KAAK,UAAU,GAC3G,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,wBAAwB,CAACC,MAAM,CAACL,OAAO,CAACM,cAAc,CAAC;QACjE,IAAIJ,SAAS,CAACE,wBAAwB,CAACG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,CAAA,EAAG;QACJ,OAAOY,GAAG;MACd;IACJ,CAAC;EACL;AACJ"} \ No newline at end of file +{"version":3,"file":"doc-cache.js","names":["_utils","require","_overwritable","_rxChangeEvent","DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","documentByRevisionHeight","delete","revisionHeight","size","undefined","subscribe","changeEvent","documentId","documentData","getDocumentDataOfRxChangeEvent","latestDoc","_proto","prototype","getCachedRxDocument","docData","getHeightOfRevision","_rev","getFromMapOrCreate","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","overwritable","deepFreezeWhenDevMode","set","createWeakRefWithFallback","register","getLatestDocumentData","getFromMapOrThrow","getLatestDocumentDataIfExists","exports","HAS_WEAK_REF","WeakRef","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n getFromMapOrCreate,\n getFromMapOrThrow,\n getHeightOfRevision\n} from './plugins/utils';\nimport {\n overwritable\n} from './overwritable';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\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 documentByRevisionHeight: 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 latestDoc: 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 private 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.documentByRevisionHeight.delete(docMeta.revisionHeight);\n if (cacheItem.documentByRevisionHeight.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 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.latestDoc = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n */\n public getCachedRxDocument(docData: RxDocumentData): RxDocument {\n const docId: string = (docData as any)[this.primaryPath];\n const revisionHeight = getHeightOfRevision(docData._rev);\n const cacheItem = getFromMapOrCreate>(\n this.cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const cachedRxDocumentWeakRef: WeakRef> | undefined = cacheItem.documentByRevisionHeight.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = overwritable.deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = this.documentCreator(docData) as RxDocument;\n cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n\n if (this.registry) {\n this.registry.register(cachedRxDocument, {\n docId,\n revisionHeight\n });\n }\n }\n return cachedRxDocument;\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.latestDoc;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.latestDoc;\n }\n }\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n documentByRevisionHeight: new Map(),\n latestDoc: docData\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';\nfunction createWeakRefWithFallback(obj: T): WeakRef {\n if (HAS_WEAK_REF) {\n return new WeakRef(obj) as any;\n } else {\n return {\n deref() {\n return obj;\n }\n } as any;\n }\n}\n"],"mappings":";;;;;;AAKA,IAAAA,MAAA,GAAAC,OAAA;AAKA,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;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI,SAAAA,cACoBC,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA,KAhCKC,gBAAgB,GAAG,IAAIC,GAAG,EAA4C;IAAA,KAQrEC,QAAQ,GAAqD,OAAOC,oBAAoB,KAAK,UAAU,GAC3G,IAAIA,oBAAoB,CAA4BC,OAAO,IAAI;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S,EAAEI;EACf,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA;AACA,IAAMiB,YAAY,GAAG,OAAOC,OAAO,KAAK,UAAU;AAClD,SAASP,yBAAyBA,CAAmBQ,GAAM,EAAc;EACrE,IAAIF,YAAY,EAAE;IACd,OAAO,IAAIC,OAAO,CAACC,GAAG,CAAC;EAC3B,CAAC,MAAM;IACH,OAAO;MACHZ,KAAKA,CAAA,EAAG;QACJ,OAAOY,GAAG;MACd;IACJ,CAAC;EACL;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugin-helpers.js b/dist/lib/plugin-helpers.js index 856c79d6e16..db5b0e83ad9 100644 --- a/dist/lib/plugin-helpers.js +++ b/dist/lib/plugin-helpers.js @@ -9,6 +9,11 @@ var _operators = require("rxjs/operators"); var _rxSchemaHelper = require("./rx-schema-helper"); var _utils = require("./plugins/utils"); var _rxjs = require("rxjs"); +/** + * Returns the validation errors. + * If document is fully valid, returns an empty array. + */ + /** * cache the validators by the schema-hash * so we can reuse them when multiple collections have the same schema diff --git a/dist/lib/plugin-helpers.js.map b/dist/lib/plugin-helpers.js.map index bd4b7c9a27e..32877f1691e 100644 --- a/dist/lib/plugin-helpers.js.map +++ b/dist/lib/plugin-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin-helpers.js","names":["_operators","require","_rxSchemaHelper","_utils","_rxjs","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","getFromMapOrCreate","initValidator","schema","hash","defaultHashSha256","JSON","stringify","args","Object","assign","storage","createStorageInstance","params","instance","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","validatorCached","requestIdleCallbackIfAvailable","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","flatClone","documentInDb","previous","processingChangesCount$","BehaviorSubject","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","entries","k","v2","err","firstValueFrom","pipe","filter","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","data","findDocumentsById","ids","deleted","findResult","key","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","tap","next","getValue","mergeMap","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","id","conflictResultionTasks","task","assumedMasterState","input","newDocumentState","realMasterState","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport { WrappedRxStorageInstance } from './rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n defaultHashSha256,\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = defaultHashSha256(JSON.stringify(schema));\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n hash,\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ error: {}, success: {} });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error[validationError.documentId] = validationError;\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: instance.schema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: (limit, checkpoint) => {\n return instance.getChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n conflictResultionTasks: () => {\n return instance.conflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n },\n resolveConflictResultionTask: (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return instance.resolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return instance.resolveConflictResultionTask(useSolution);\n }\n };\n\n return wrappedInstance;\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,eAAA,GAAAD,OAAA;AAmBA,IAAAE,MAAA,GAAAF,OAAA;AAMA,IAAAG,KAAA,GAAAH,OAAA;AAeA;AACA;AACA;AACA;AACA,IAAMI,gCAA6E,GAAG,IAAIC,GAAG,EAAE;;AAE/F;AACA;AACA;AACA;AACO,SAASC,6BAA6BA;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ;AACA;AACIC,YAAoB,EACE;EACtB,IAAMC,eAAe,GAAG,IAAAC,yBAAkB,EACtCN,gCAAgC,EAChCI,YAAY,EACZ,MAAM,IAAIH,GAAG,EAAE,CAClB;EAED,SAASM,aAAaA,CAClBC,MAAyB,EACR;IACjB,IAAMC,IAAI,GAAG,IAAAC,wBAAiB,EAACC,IAAI,CAACC,SAAS,CAACJ,MAAM,CAAC,CAAC;IACtD,OAAO,IAAAF,yBAAkB,EACrBD,eAAe,EACfI,IAAI,EACJ,MAAMN,YAAY,CAACK,MA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YAAY,EAAEgB,YAAY,CAACC,MAAM,CAACjB;QACtC;MACJ,CAAC;MACD,OAAO/F,QAAQ,CAAC8G,4BAA4B,CAACI,WAAW,CAAC;IAC7D;EACJ,CAAC;EAED,OAAOpE,eAAe;AAC1B"} \ No newline at end of file +{"version":3,"file":"plugin-helpers.js","names":["_operators","require","_rxSchemaHelper","_utils","_rxjs","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","getFromMapOrCreate","initValidator","schema","hash","defaultHashSha256","JSON","stringify","args","Object","assign","storage","createStorageInstance","params","instance","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","validatorCached","requestIdleCallbackIfAvailable","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","flatClone","documentInDb","previous","processingChangesCount$","BehaviorSubject","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","entries","k","v2","err","firstValueFrom","pipe","filter","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","data","findDocumentsById","ids","deleted","findResult","key","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","tap","next","getValue","mergeMap","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","id","conflictResultionTasks","task","assumedMasterState","input","newDocumentState","realMasterState","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport { WrappedRxStorageInstance } from './rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n defaultHashSha256,\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = defaultHashSha256(JSON.stringify(schema));\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n hash,\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ error: {}, success: {} });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error[validationError.documentId] = validationError;\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: instance.schema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: (limit, checkpoint) => {\n return instance.getChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n conflictResultionTasks: () => {\n return instance.conflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n },\n resolveConflictResultionTask: (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return instance.resolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return instance.resolveConflictResultionTask(useSolution);\n }\n };\n\n return wrappedInstance;\n}\n"],"mappings":";;;;;;;AAA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AAkB,CAAC;QAC3E,IAAME,gBAAgB,GAAG,MAAMtE,WAAW,CAACmE,IAAI,CAACE,KAAK,CAACC,gBAAgB,CAAC;QACvE,IAAMC,eAAe,GAAG,MAAMvE,WAAW,CAACmE,IAAI,CAACE,KAAK,CAACE,eAAe,CAAC;QACrE,OAAO;UACHN,EAAE,EAAEE,IAAI,CAACF,EAAE;UACX7F,OAAO,EAAE+F,IAAI,CAAC/F,OAAO;UACrBiG,KAAK,EAAE;YACHD,kBAAkB;YAClBG,eAAe;YACfD;UACJ;QACJ,CAAC;MACL,CAAC,CAAC,CACL;IACL,CAAC;IACDE,4BAA4B,EAAGC,YAAY,IAAK;MAC5C,IAAIA,YAAY,CAACC,MAAM,CAACC,OAAO,EAAE;QAC7B,OAAOjH,QAAQ,CAAC8G,4BAA4B,CAACC,YAAY,CAAC;MAC9D;MACA,IAAMG,WAAW,GAAG;QAChBX,EAAE,EAAEQ,YAAY,CAACR,EAAE;QACnBS,MAAM,EAAE;UACJC,OAAO,EAAE,KAAK;UACdlB,YAAY,EAAEgB,YAAY,CAACC,MAAM,CAACjB;QACtC;MACJ,CAAC;MACD,OAAO/F,QAAQ,CAAC8G,4BAA4B,CAACI,WAAW,CAAC;IAC7D;EACJ,CAAC;EAED,OAAOpE,eAAe;AAC1B"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js index 30e5a5cadf9..a53592c7c5c 100644 --- a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js +++ b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js @@ -9,6 +9,12 @@ exports.graphQLSchemaFromRxSchema = graphQLSchemaFromRxSchema; var _getGraphqlFromJsonschema = require("get-graphql-from-jsonschema"); var _rxSchemaHelper = require("../../rx-schema-helper"); var _utils = require("../../plugins/utils"); +/** + * just type some common types + * to have better IDE autocomplete, + * all strings are allowed + */ + // we use two spaces because get-graphql-from-jsonschema does also var SPACING = ' '; diff --git a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map index 495758c6ef5..ec77e305b02 100644 --- a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map +++ b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["_getGraphqlFromJsonschema","require","_rxSchemaHelper","_utils","SPACING","exports","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ensureNotFalsy","ucCollectionName","ucfirst","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","getGraphqlSchemaFromJsonSchema","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","flatClone","fillWithDefaultSettings","keys","startsWith","deletedField","withRevisions","strip","cloned","clone","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,yBAAA,GAAAC,OAAA;AAEA,IAAAC,eAAA,GAAAD,OAAA;AAGA,IAAAE,MAAA,GAAAF,OAAA;AAsDA;AACO,IAAMG,OAAO,GAAG,IAAI;;AAE3B;AACA;AACA;AAFAC,OAAA,CAAAD,OAAA,GAAAA,OAAA;AAGO,SAASE,yBAAyBA,CACrCC,KAAqC,EACN;EAC/B,IAAMC,GAAoC,GAAG;IACzCC,QAAQ,EAAE,EAAE;IACZC,OAAO,EAAE,EAAE;IACXC,SAAS,EAAE,EAAE;IACbC,aAAa,EAAE,EAAE;IACjBC,MAAM,EAAE,EAAE;IACVC,KAAK,EAAE;EACX,CAAC;EAEDC,MAAM,CAACC,OAAO,CAACT,KAAK,CAAC,CAACU,OAAO,CAAC,CAAC,CAACC,cAAc,EAAEC,kBAAkB,CAAC,KAAK;IACpEA,kBAAkB,GAAGC,eAAe,CAACD,kBAAkB,CAAC;IAExD,IAAME,MAAM,GAAGF,kBAAkB,CAACE,MAAM;IACxC,IAAMC,QAAkB,GAAG,IAAAC,qBAAc,EAACJ,kBAAkB,CAACG,QAAQ,CAAC;IACtE,IAAME,gBAAgB,GAAG,IAAAC,cAAO,EAACP,cAAc,CAAC;IAChD,IAAMQ,mBAAmB,GAAG,IAAAD,cAAO,EAACP,cAAc,CAAC,GAAG,OAAO;;IAE7D;IACA,IAAMS,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C,OAAO,EAAE;IACnBpC,QAAQ,CAACoC,OAAO,GAAG,SAAS;EAChC;EACA,IAAI,CAACnD,KAAK,CAACgD,YAAY,EAAE;IACrBhD,KAAK,CAACgD,YAAY,GAAG,EAAE;EAC3B;EAGA,IAAI,CAAChD,KAAK,CAACoF,aAAa,EAAE;IACtBpF,KAAK,CAACoF,aAAa,GAAG,KAAK;EAC/B;EAEA,IAAI,CAACpF,KAAK,CAACsB,eAAe,EAAE;IACxBtB,KAAK,CAACsB,eAAe,GAAG,EAAE;EAC9B;EACA,IAAI,CAACtB,KAAK,CAACuD,gBAAgB,EAAE;IACzBvD,KAAK,CAACuD,gBAAgB,GAAG,EAAE;EAC/B;EAEA,OAAOvD,KAAK;AAChB;AAEA,SAASqB,mBAAmBA,CAAIP,MAAuB,EAAEuE,KAAe,EAA4B;EAChG,IAAMC,MAAW,GAAG,IAAAC,YAAK,EAACzE,MAAM,CAAC;EACjCuE,KAAK,CAAC3E,OAAO,CAAC2B,GAAG,IAAI;IACjB,OAAOiD,MAAM,CAACxD,UAAU,CAACO,GAAG,CAAC;EACjC,CAAC,CAAC;EACF,OAAOiD,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA,SAASxC,uBAAuBA,CAACD,GAAW,EAAE5B,gBAAwB,EAAU;EAC5E,OAAO4B,GAAG,CAAC2C,OAAO,CAAC,GAAG,GAAGvE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file +{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["_getGraphqlFromJsonschema","require","_rxSchemaHelper","_utils","SPACING","exports","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ensureNotFalsy","ucCollectionName","ucfirst","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","getGraphqlSchemaFromJsonSchema","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","flatClone","fillWithDefaultSettings","keys","startsWith","deletedField","withRevisions","strip","cloned","clone","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,yBAAA,GAAAC,OAAA;AAEA,IAAAC,eAAA,GAAAD,OAAA;AAGA,IAAAE,MAAA,GAAAF,OAAA;AAYA;AACA;AACA;AACA;AACA;;AAsCA;AACO,IAAMG,OAAO,GAAG,IAAI;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MC,MAAW,GAAG,IAAAC,YAAK,EAACzE,MAAM,CAAC;EACjCuE,KAAK,CAAC3E,OAAO,CAAC2B,GAAG,IAAI;IACjB,OAAOiD,MAAM,CAACxD,UAAU,CAACO,GAAG,CAAC;EACjC,CAAC,CAAC;EACF,OAAOiD,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA,SAASxC,uBAAuBA,CAACD,GAAW,EAAE5B,gBAAwB,EAAU;EAC5E,OAAO4B,GAAG,CAAC2C,OAAO,CAAC,GAAG,GAAGvE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-p2p/index.js b/dist/lib/plugins/replication-p2p/index.js index 2cc3443b6cc..bafa04d05ef 100644 --- a/dist/lib/plugins/replication-p2p/index.js +++ b/dist/lib/plugins/replication-p2p/index.js @@ -225,6 +225,7 @@ var RxP2PReplicationPool = /*#__PURE__*/function () { await this.connectionHandler.destroy(); }; return RxP2PReplicationPool; -}(); +}(); // export * from './connection-handler-webtorrent'; +// export * from './connection-handler-p2pcf'; exports.RxP2PReplicationPool = RxP2PReplicationPool; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-p2p/index.js.map b/dist/lib/plugins/replication-p2p/index.js.map index 3fc5d8a7bd4..863130576ef 100644 --- a/dist/lib/plugins/replication-p2p/index.js.map +++ b/dist/lib/plugins/replication-p2p/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_rxjs","require","_plugin","_replicationProtocol","_utils","_leaderElection","_replication","_p2pHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_p2pTypes","_connectionHandlerSimplePeer","replicateP2P","options","collection","addRxPlugin","RxDBLeaderElectionPlugin","pull","batchSize","push","database","multiInstance","waitForLeadership","requestCounter","requestFlag","randomCouchString","getRequestId","count","token","storageToken","pool","RxP2PReplicationPool","connectionHandlerCreator","subs","connectionHandler","error$","subscribe","err","next","disconnect$","peer","removePeer","message$","pipe","filter","data","message","method","send","id","result","connectSub","connect$","canceled","tokenResponse","sendMessageAndAwaitAnswer","params","peerToken","isMaster","isMasterInP2PReplication","hashFunction","replicationState","masterHandler","masterReplicationHandler","masterChangeStreamSub","masterChangeStream$","ev","streamResponse","p","unsubscribe","messageSub","msgPeer","bind","response","replicateRxCollection","replicationIdentifier","name","topic","join","autoStart","deletedField","live","retryTime","assign","handler","lastPulledCheckpoint","answer","ensureNotFalsy","stream$","response$","m","map","undefined","docs","addPeer","peerStates$","BehaviorSubject","Map","Subject","onDestroy","cancel","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","_proto","peerState","getValue","set","getFromMapOrThrow","delete","sub","awaitFirstPeer","firstValueFrom","peerStates","size","Array","from","destroy"],"sources":["../../../../src/plugins/replication-p2p/index.ts"],"sourcesContent":["import {\n BehaviorSubject,\n filter,\n firstValueFrom,\n map,\n Subject,\n Subscription\n} from 'rxjs';\nimport { addRxPlugin } from '../../plugin';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport type {\n RxCollection,\n RxError,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxTypeError\n} from '../../types';\nimport { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../plugins/utils';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport { replicateRxCollection } from '../replication';\nimport { isMasterInP2PReplication, sendMessageAndAwaitAnswer } from './p2p-helper';\nimport type {\n P2PConnectionHandler,\n P2PPeer,\n P2PPeerState,\n P2PReplicationCheckpoint,\n P2PResponse,\n RxP2PReplicationState,\n SyncOptionsP2P\n} from './p2p-types';\n\n\nexport async function replicateP2P(\n options: SyncOptionsP2P\n): Promise> {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n // fill defaults\n if (options.pull) {\n if (!options.pull.batchSize) {\n options.pull.batchSize = 20;\n }\n }\n if (options.push) {\n if (!options.push.batchSize) {\n options.push.batchSize = 20;\n }\n }\n\n if (collection.database.multiInstance) {\n await collection.database.waitForLeadership();\n }\n\n // used to easier debug stuff\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return collection.database.token + '|' + requestFlag + '|' + count;\n }\n\n const storageToken = await collection.database.storageToken;\n const pool = new RxP2PReplicationPool(\n collection,\n options,\n options.connectionHandlerCreator(options)\n );\n\n\n pool.subs.push(\n pool.connectionHandler.error$.subscribe(err => pool.error$.next(err)),\n pool.connectionHandler.disconnect$.subscribe(peer => pool.removePeer(peer))\n );\n\n /**\n * Answer if someone requests our storage token\n */\n pool.subs.push(\n pool.connectionHandler.message$.pipe(\n filter(data => data.message.method === 'token')\n ).subscribe(data => {\n pool.connectionHandler.send(data.peer, {\n id: data.message.id,\n result: storageToken\n });\n })\n );\n\n const connectSub = pool.connectionHandler.connect$\n .pipe(\n filter(() => !pool.canceled)\n )\n .subscribe(async (peer) => {\n /**\n * TODO ensure both know the correct secret\n */\n const tokenResponse = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n id: getRequestId(),\n method: 'token',\n params: []\n }\n );\n const peerToken: string = tokenResponse.result;\n const isMaster = isMasterInP2PReplication(collection.database.hashFunction, storageToken, peerToken);\n\n let replicationState: RxP2PReplicationState | undefined;\n if (isMaster) {\n const masterHandler = pool.masterReplicationHandler;\n const masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(ev => {\n const streamResponse: P2PResponse = {\n id: 'masterChangeStream$',\n result: ev\n };\n pool.connectionHandler.send(peer, streamResponse);\n });\n\n // clean up the subscription\n pool.subs.push(\n masterChangeStreamSub,\n pool.connectionHandler.disconnect$.pipe(\n filter(p => p.id === peer.id)\n ).subscribe(() => masterChangeStreamSub.unsubscribe())\n );\n\n const messageSub = pool.connectionHandler.message$\n .pipe(\n filter(data => data.peer.id === peer.id),\n filter(data => data.message.method !== 'token')\n )\n .subscribe(async (data) => {\n const { peer: msgPeer, message } = data;\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n const method = (masterHandler as any)[message.method].bind(masterHandler);\n const result = await (method as any)(...message.params);\n const response: P2PResponse = {\n id: message.id,\n result\n };\n pool.connectionHandler.send(msgPeer, response);\n });\n pool.subs.push(messageSub);\n } else {\n replicationState = replicateRxCollection({\n replicationIdentifier: [collection.name, options.topic, peerToken].join('||'),\n collection: collection,\n autoStart: true,\n deletedField: '_deleted',\n live: true,\n retryTime: options.retryTime,\n waitForLeadership: false,\n pull: options.pull ? Object.assign({}, options.pull, {\n async handler(lastPulledCheckpoint: P2PReplicationCheckpoint) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterChangesSince',\n params: [\n lastPulledCheckpoint,\n ensureNotFalsy(options.pull).batchSize\n ],\n id: getRequestId()\n }\n );\n return answer.result;\n },\n stream$: pool.connectionHandler.response$.pipe(\n filter(m => m.response.id === 'masterChangeStream$'),\n map(m => m.response.result)\n )\n\n }) : undefined,\n push: options.push ? Object.assign({}, options.push, {\n async handler(docs: RxReplicationWriteToMasterRow[]) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterWrite',\n params: [docs],\n id: getRequestId()\n }\n );\n return answer.result;\n }\n }) : undefined\n });\n }\n pool.addPeer(peer, replicationState);\n });\n pool.subs.push(connectSub);\n return pool;\n}\n\n\n/**\n * Because the P2P replication runs between many instances,\n * we use a Pool instead of returning a single replication state.\n */\nexport class RxP2PReplicationPool {\n\n peerStates$: BehaviorSubject>> = new BehaviorSubject(new Map());\n canceled: boolean = false;\n masterReplicationHandler: RxReplicationHandler;\n subs: Subscription[] = [];\n\n public error$ = new Subject();\n\n constructor(\n public readonly collection: RxCollection,\n public readonly options: SyncOptionsP2P,\n public readonly connectionHandler: P2PConnectionHandler\n ) {\n this.collection.onDestroy.push(() => this.cancel());\n this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n collection.database.token,\n );\n }\n\n addPeer(\n peer: P2PPeer,\n replicationState?: RxP2PReplicationState\n ) {\n const peerState: P2PPeerState = {\n peer,\n replicationState,\n subs: []\n };\n this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState));\n if (replicationState) {\n peerState.subs.push(\n replicationState.error$.subscribe(ev => this.error$.next(ev))\n );\n }\n }\n removePeer(peer: P2PPeer) {\n const peerState = getFromMapOrThrow(this.peerStates$.getValue(), peer);\n this.peerStates$.getValue().delete(peer);\n this.peerStates$.next(this.peerStates$.getValue());\n peerState.subs.forEach(sub => sub.unsubscribe());\n if (peerState.replicationState) {\n peerState.replicationState.cancel();\n }\n }\n\n // often used in unit tests\n awaitFirstPeer() {\n return firstValueFrom(\n this.peerStates$.pipe(\n filter(peerStates => peerStates.size > 0)\n )\n );\n }\n\n public async cancel() {\n if (this.canceled) {\n return;\n }\n this.canceled = true;\n this.subs.forEach(sub => sub.unsubscribe());\n Array.from(this.peerStates$.getValue().keys()).forEach(peer => {\n this.removePeer(peer);\n });\n await this.connectionHandler.destroy();\n }\n}\n\nexport * from './p2p-helper';\nexport * from './p2p-types';\n// export * from './connection-handler-webtorrent';\n// export * from './connection-handler-p2pcf';\nexport * from './connection-handler-simple-peer';\n"],"mappings":";;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAQA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,oBAAA,GAAAF,OAAA;AAQA,IAAAG,MAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,UAAA,GAAAN,OAAA;AAgQAO,MAAA,CAAAC,IAAA,CAAAF,UAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAA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IAAI,IAAI,CAAC/C,QAAQ,EAAE;MACf;IACJ;IACA,IAAI,CAACA,QAAQ,GAAG,IAAI;IACpB,IAAI,CAACpB,IAAI,CAACjC,OAAO,CAAC8G,GAAG,IAAIA,GAAG,CAACzC,WAAW,EAAE,CAAC;IAC3C8C,KAAK,CAACC,IAAI,CAAC,IAAI,CAACrB,WAAW,CAACW,QAAQ,EAAE,CAAC3G,IAAI,EAAE,CAAC,CAACC,OAAO,CAACwC,IAAI,IAAI;MAC3D,IAAI,CAACC,UAAU,CAACD,IAAI,CAAC;IACzB,CAAC,CAAC;IACF,MAAM,IAAI,CAACN,iBAAiB,CAACmF,OAAO,EAAE;EAC1C,CAAC;EAAA,OAAAtF,oBAAA;AAAA;AAAAzB,OAAA,CAAAyB,oBAAA,GAAAA,oBAAA"} \ No newline at end of file +{"version":3,"file":"index.js","names":["_rxjs","require","_plugin","_replicationProtocol","_utils","_leaderElection","_replication","_p2pHelper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_p2pTypes","_connectionHandlerSimplePeer","replicateP2P","options","collection","addRxPlugin","RxDBLeaderElectionPlugin","pull","batchSize","push","database","multiInstance","waitForLeadership","requestCounter","requestFlag","randomCouchString","getRequestId","count","token","storageToken","pool","RxP2PReplicationPool","connectionHandlerCreator","subs","connectionHandler","error$","subscribe","err","next","disconnect$","peer","removePeer","message$","pipe","filter","data","message","method","send","id","result","connectSub","connect$","canceled","tokenResponse","sendMessageAndAwaitAnswer","params","peerToken","isMaster","isMasterInP2PReplication","hashFunction","replicationState","masterHandler","masterReplicationHandler","masterChangeStreamSub","masterChangeStream$","ev","streamResponse","p","unsubscribe","messageSub","msgPeer","bind","response","replicateRxCollection","replicationIdentifier","name","topic","join","autoStart","deletedField","live","retryTime","assign","handler","lastPulledCheckpoint","answer","ensureNotFalsy","stream$","response$","m","map","undefined","docs","addPeer","peerStates$","BehaviorSubject","Map","Subject","onDestroy","cancel","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","_proto","peerState","getValue","set","getFromMapOrThrow","delete","sub","awaitFirstPeer","firstValueFrom","peerStates","size","Array","from","destroy"],"sources":["../../../../src/plugins/replication-p2p/index.ts"],"sourcesContent":["import {\n BehaviorSubject,\n filter,\n firstValueFrom,\n map,\n Subject,\n Subscription\n} from 'rxjs';\nimport { addRxPlugin } from '../../plugin';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport type {\n RxCollection,\n RxError,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxTypeError\n} from '../../types';\nimport { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../plugins/utils';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport { replicateRxCollection } from '../replication';\nimport { isMasterInP2PReplication, sendMessageAndAwaitAnswer } from './p2p-helper';\nimport type {\n P2PConnectionHandler,\n P2PPeer,\n P2PPeerState,\n P2PReplicationCheckpoint,\n P2PResponse,\n RxP2PReplicationState,\n SyncOptionsP2P\n} from './p2p-types';\n\n\nexport async function replicateP2P(\n options: SyncOptionsP2P\n): Promise> {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n // fill defaults\n if (options.pull) {\n if (!options.pull.batchSize) {\n options.pull.batchSize = 20;\n }\n }\n if (options.push) {\n if (!options.push.batchSize) {\n options.push.batchSize = 20;\n }\n }\n\n if (collection.database.multiInstance) {\n await collection.database.waitForLeadership();\n }\n\n // used to easier debug stuff\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return collection.database.token + '|' + requestFlag + '|' + count;\n }\n\n const storageToken = await collection.database.storageToken;\n const pool = new RxP2PReplicationPool(\n collection,\n options,\n options.connectionHandlerCreator(options)\n );\n\n\n pool.subs.push(\n pool.connectionHandler.error$.subscribe(err => pool.error$.next(err)),\n pool.connectionHandler.disconnect$.subscribe(peer => pool.removePeer(peer))\n );\n\n /**\n * Answer if someone requests our storage token\n */\n pool.subs.push(\n pool.connectionHandler.message$.pipe(\n filter(data => data.message.method === 'token')\n ).subscribe(data => {\n pool.connectionHandler.send(data.peer, {\n id: data.message.id,\n result: storageToken\n });\n })\n );\n\n const connectSub = pool.connectionHandler.connect$\n .pipe(\n filter(() => !pool.canceled)\n )\n .subscribe(async (peer) => {\n /**\n * TODO ensure both know the correct secret\n */\n const tokenResponse = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n id: getRequestId(),\n method: 'token',\n params: []\n }\n );\n const peerToken: string = tokenResponse.result;\n const isMaster = isMasterInP2PReplication(collection.database.hashFunction, storageToken, peerToken);\n\n let replicationState: RxP2PReplicationState | undefined;\n if (isMaster) {\n const masterHandler = pool.masterReplicationHandler;\n const masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(ev => {\n const streamResponse: P2PResponse = {\n id: 'masterChangeStream$',\n result: ev\n };\n pool.connectionHandler.send(peer, streamResponse);\n });\n\n // clean up the subscription\n pool.subs.push(\n masterChangeStreamSub,\n pool.connectionHandler.disconnect$.pipe(\n filter(p => p.id === peer.id)\n ).subscribe(() => masterChangeStreamSub.unsubscribe())\n );\n\n const messageSub = pool.connectionHandler.message$\n .pipe(\n filter(data => data.peer.id === peer.id),\n filter(data => data.message.method !== 'token')\n )\n .subscribe(async (data) => {\n const { peer: msgPeer, message } = data;\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n const method = (masterHandler as any)[message.method].bind(masterHandler);\n const result = await (method as any)(...message.params);\n const response: P2PResponse = {\n id: message.id,\n result\n };\n pool.connectionHandler.send(msgPeer, response);\n });\n pool.subs.push(messageSub);\n } else {\n replicationState = replicateRxCollection({\n replicationIdentifier: [collection.name, options.topic, peerToken].join('||'),\n collection: collection,\n autoStart: true,\n deletedField: '_deleted',\n live: true,\n retryTime: options.retryTime,\n waitForLeadership: false,\n pull: options.pull ? Object.assign({}, options.pull, {\n async handler(lastPulledCheckpoint: P2PReplicationCheckpoint) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterChangesSince',\n params: [\n lastPulledCheckpoint,\n ensureNotFalsy(options.pull).batchSize\n ],\n id: getRequestId()\n }\n );\n return answer.result;\n },\n stream$: pool.connectionHandler.response$.pipe(\n filter(m => m.response.id === 'masterChangeStream$'),\n map(m => m.response.result)\n )\n\n }) : undefined,\n push: options.push ? Object.assign({}, options.push, {\n async handler(docs: RxReplicationWriteToMasterRow[]) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterWrite',\n params: [docs],\n id: getRequestId()\n }\n );\n return answer.result;\n }\n }) : undefined\n });\n }\n pool.addPeer(peer, replicationState);\n });\n pool.subs.push(connectSub);\n return pool;\n}\n\n\n/**\n * Because the P2P replication runs between many instances,\n * we use a Pool instead of returning a single replication state.\n */\nexport class RxP2PReplicationPool {\n\n peerStates$: BehaviorSubject>> = new BehaviorSubject(new Map());\n canceled: boolean = false;\n masterReplicationHandler: RxReplicationHandler;\n subs: Subscription[] = [];\n\n public error$ = new Subject();\n\n constructor(\n public readonly collection: RxCollection,\n public readonly options: SyncOptionsP2P,\n public readonly connectionHandler: P2PConnectionHandler\n ) {\n this.collection.onDestroy.push(() => this.cancel());\n this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n collection.database.token,\n );\n }\n\n addPeer(\n peer: P2PPeer,\n replicationState?: RxP2PReplicationState\n ) {\n const peerState: P2PPeerState = {\n peer,\n replicationState,\n subs: []\n };\n this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState));\n if (replicationState) {\n peerState.subs.push(\n replicationState.error$.subscribe(ev => this.error$.next(ev))\n );\n }\n }\n removePeer(peer: P2PPeer) {\n const peerState = getFromMapOrThrow(this.peerStates$.getValue(), peer);\n this.peerStates$.getValue().delete(peer);\n this.peerStates$.next(this.peerStates$.getValue());\n peerState.subs.forEach(sub => sub.unsubscribe());\n if (peerState.replicationState) {\n peerState.replicationState.cancel();\n }\n }\n\n // often used in unit tests\n awaitFirstPeer() {\n return firstValueFrom(\n this.peerStates$.pipe(\n filter(peerStates => peerStates.size > 0)\n )\n );\n }\n\n public async cancel() {\n if (this.canceled) {\n return;\n }\n this.canceled = true;\n this.subs.forEach(sub => sub.unsubscribe());\n Array.from(this.peerStates$.getValue().keys()).forEach(peer => {\n this.removePeer(peer);\n });\n await this.connectionHandler.destroy();\n }\n}\n\nexport * from './p2p-helper';\nexport * from './p2p-types';\n// export * from './connection-handler-webtorrent';\n// export * from './connection-handler-p2pcf';\nexport * from './connection-handler-simple-peer';\n"],"mappings":";;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAQA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,oBAAA,GAAAF,OAAA;AAQA,IAAAG,MAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,UAAA,GAAAN,OAAA;AAgQAO,MAAA,CAAAC,IAAA,CAAAF,UAAA,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,UAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,UAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,SAAA,GAAAnB,OAAA;AAAAO,MAAA,CAAAC,IAAA,CAAAW,SAAA,EAAAV,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC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1C,CAAC;EAAA,OAAAtF,oBAAA;AAAA,KAKL;AACA;AAAAzB,OAAA,CAAAyB,oBAAA,GAAAA,oBAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-array.js b/dist/lib/plugins/utils/utils-array.js index c55bd61c101..76cacf7f43c 100644 --- a/dist/lib/plugins/utils/utils-array.js +++ b/dist/lib/plugins/utils/utils-array.js @@ -9,6 +9,7 @@ exports.batchArray = batchArray; exports.countUntilNotMatching = countUntilNotMatching; exports.isMaybeReadonlyArray = isMaybeReadonlyArray; exports.lastOfArray = lastOfArray; +exports.maxOfNumbers = maxOfNumbers; exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; exports.shuffleArray = shuffleArray; exports.sumNumberArray = sumNumberArray; @@ -111,4 +112,7 @@ function sumNumberArray(array) { } return count; } +function maxOfNumbers(arr) { + return Math.max(...arr); +} //# sourceMappingURL=utils-array.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-array.js.map b/dist/lib/plugins/utils/utils-array.js.map index f838cbfcb84..e514be542d0 100644 --- a/dist/lib/plugins/utils/utils-array.js.map +++ b/dist/lib/plugins/utils/utils-array.js.map @@ -1 +1 @@ -{"version":3,"file":"utils-array.js","names":["lastOfArray","ar","length","shuffleArray","arr","slice","sort","Math","random","toArray","input","Array","isArray","batchArray","array","batchSize","ret","batch","splice","push","removeOneFromArrayIfMatches","condition","i","done","isMaybeReadonlyArray","x","arrayFilterNotEmpty","value","undefined","countUntilNotMatching","matchingFn","count","idx","item","matching","asyncFilter","predicate","filters","Promise","all","map","filter","index","sumNumberArray"],"sources":["../../../../src/plugins/utils/utils-array.ts"],"sourcesContent":["import type {\n MaybePromise,\n MaybeReadonly\n} from '../../types';\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.slice(0).sort(() => (Math.random() - 0.5));\n}\n\nexport function toArray(input: T | T[] | Readonly | Readonly): T[] {\n return Array.isArray(input) ? (input as any[]).slice(0) : [input];\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n\nexport function countUntilNotMatching(\n ar: T[],\n matchingFn: (v: T, idx: number) => boolean\n): number {\n let count = 0;\n let idx = -1;\n for (const item of ar) {\n idx = idx + 1;\n const matching = matchingFn(item, idx);\n if (matching) {\n count = count + 1;\n } else {\n break;\n }\n }\n return count;\n}\n\nexport async function asyncFilter(array: T[], predicate: (item: T, index: number, a: T[]) => MaybePromise): Promise {\n const filters = await Promise.all(\n array.map(predicate)\n );\n\n return array.filter((...[, index]) => filters[index]);\n}\n\n/**\n * @link https://stackoverflow.com/a/3762735\n */\nexport function sumNumberArray(array: number[]): number {\n let count = 0;\n for (let i = array.length; i--;) {\n count += array[i];\n }\n return count;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKO,SAASA,WAAWA,CAAIC,EAAO,EAAiB;EACnD,OAAOA,EAAE,CAACA,EAAE,CAACC,MAAM,GAAG,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACO,SAASC,YAAYA,CAAIC,GAAQ,EAAO;EAC3C,OAAOA,GAAG,CAACC,KAAK,CAAC,CAAC,CAAC,CAACC,IAAI,CAAC,MAAOC,IAAI,CAACC,MAAM,EAAE,GAAG,GAAI,CAAC;AACzD;AAEO,SAASC,OAAOA,CAAIC,KAA4C,EAAO;EAC1E,OAAOC,KAAK,CAACC,OAAO,CAACF,KAAK,CAAC,GAAIA,KAAK,CAAWL,KAAK,CAAC,CAAC,CAAC,GAAG,CAACK,KAAK,CAAC;AACrE;;AAEA;AACA;AACA;AACA;AACO,SAASG,UAAUA,CAAIC,KAAU,EAAEC,SAAiB,EAAS;EAChED,KAAK,GAAGA,KAAK,CAACT,KAAK,CAAC,CAAC,CAAC;EACtB,IAAMW,GAAU,GAAG,EAAE;EACrB,OAAOF,KAAK,CAACZ,MAAM,EAAE;IACjB,IAAMe,KAAK,GAAGH,KAAK,CAACI,MAAM,CAAC,CAAC,EAAEH,SAAS,CAAC;IACxCC,GAAG,CAACG,IAAI,CAACF,KAAK,CAAC;EACnB;EACA,OAAOD,GAAG;AACd;;AAEA;AACA;AACA;AACO,SAASI,2BAA2BA,CAAInB,EAAO,EAAEoB,SAA4B,EAAO;EACvFpB,EAAE,GAAGA,EAAE,CAACI,KAAK,EAAE;EACf,IAAIiB,CAAC,GAAGrB,EAAE,CAACC,MAAM;EACjB,IAAIqB,IAAI,GAAG,KAAK;EAChB,OAAOD,CAAC,EAAE,IAAI,CAACC,IAAI,EAAE;IACjB,IAAIF,SAAS,CAACpB,EAAE,CAACqB,CAAC,CAAC,CAAC,EAAE;MAClBC,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,CAACZ,MAAM,EAAEoB,CAAC,EAAE,GAAG;IAC7BS,KAAK,IAAIjB,KAAK,CAACQ,CAAC,CAAC;EACrB;EACA,OAAOS,KAAK;AAChB"} \ No newline at end of file +{"version":3,"file":"utils-array.js","names":["lastOfArray","ar","length","shuffleArray","arr","slice","sort","Math","random","toArray","input","Array","isArray","batchArray","array","batchSize","ret","batch","splice","push","removeOneFromArrayIfMatches","condition","i","done","isMaybeReadonlyArray","x","arrayFilterNotEmpty","value","undefined","countUntilNotMatching","matchingFn","count","idx","item","matching","asyncFilter","predicate","filters","Promise","all","map","filter","index","sumNumberArray","maxOfNumbers","max"],"sources":["../../../../src/plugins/utils/utils-array.ts"],"sourcesContent":["import type {\n MaybePromise,\n MaybeReadonly\n} from '../../types';\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.slice(0).sort(() => (Math.random() - 0.5));\n}\n\nexport function toArray(input: T | T[] | Readonly | Readonly): T[] {\n return Array.isArray(input) ? (input as any[]).slice(0) : [input];\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n\nexport function countUntilNotMatching(\n ar: T[],\n matchingFn: (v: T, idx: number) => boolean\n): number {\n let count = 0;\n let idx = -1;\n for (const item of ar) {\n idx = idx + 1;\n const matching = matchingFn(item, idx);\n if (matching) {\n count = count + 1;\n } else {\n break;\n }\n }\n return count;\n}\n\nexport async function asyncFilter(array: T[], predicate: (item: T, index: number, a: T[]) => MaybePromise): Promise {\n const filters = await Promise.all(\n array.map(predicate)\n );\n\n return array.filter((...[, index]) => filters[index]);\n}\n\n/**\n * @link https://stackoverflow.com/a/3762735\n */\nexport function sumNumberArray(array: number[]): number {\n let count = 0;\n for (let i = array.length; i--;) {\n count += array[i];\n }\n return count;\n}\n\nexport function maxOfNumbers(arr: number[]): number {\n return Math.max(...arr);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAKO,SAASA,WAAWA,CAAIC,EAAO,EAAiB;EACnD,OAAOA,EAAE,CAACA,EAAE,CAACC,MAAM,GAAG,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACO,SAASC,YAAYA,CAAIC,GAAQ,EAAO;EAC3C,OAAOA,GAAG,CAACC,KAAK,CAAC,CAAC,CAAC,CAACC,IAAI,CAAC,MAAOC,IAAI,CAACC,MAAM,EAAE,GAAG,GAAI,CAAC;AACzD;AAEO,SAASC,OAAOA,CAAIC,KAA4C,EAAO;EAC1E,OAAOC,KAAK,CAACC,OAAO,CAACF,KAAK,CAAC,GAAIA,KAAK,CAAWL,KAAK,CAAC,CAAC,CAAC,GAA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AAG,CAAC,CAAC;EACZ,KAAK,IAAMC,KAAI,IAAIhC,EAAE,EAAE;IACnB+B,GAAG,GAAGA,GAAG,GAAG,CAAC;IACb,IAAME,QAAQ,GAAGJ,UAAU,CAACG,KAAI,EAAED,GAAG,CAAC;IACtC,IAAIE,QAAQ,EAAE;MACVH,KAAK,GAAGA,KAAK,GAAG,CAAC;IACrB,CAAC,MAAM;MACH;IACJ;EACJ;EACA,OAAOA,KAAK;AAChB;AAEO,eAAeI,WAAWA,CAAIrB,KAAU,EAAEsB,SAAoE,EAAgB;EACjI,IAAMC,OAAO,GAAG,MAAMC,OAAO,CAACC,GAAG,CAC7BzB,KAAK,CAAC0B,GAAG,CAACJ,SAAS,CAAC,CACvB;EAED,OAAOtB,KAAK,CAAC2B,MAAM,CAAC,CAAC,GAAG,GAAGC,KAAK,CAAC,KAAKL,OAAO,CAACK,KAAK,CAAC,CAAC;AACzD;;AAEA;AACA;AACA;AACO,SAASC,cAAcA,CAAC7B,KAAe,EAAU;EACpD,IAAIiB,KAAK,GAAG,CAAC;EACb,KAAK,IAAIT,CAAC,GAAGR,KAAK,CAACZ,MAAM,EAAEoB,CAAC,EAAE,GAAG;IAC7BS,KAAK,IAAIjB,KAAK,CAACQ,CAAC,CAAC;EACrB;EACA,OAAOS,KAAK;AAChB;AAEO,SAASa,YAAYA,CAACxC,GAAa,EAAU;EAChD,OAAOG,IAAI,CAACsC,GAAG,CAAC,GAAGzC,GAAG,CAAC;AAC3B"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-rxdb-version.js b/dist/lib/plugins/utils/utils-rxdb-version.js index e05cd3b4420..435126c7186 100644 --- a/dist/lib/plugins/utils/utils-rxdb-version.js +++ b/dist/lib/plugins/utils/utils-rxdb-version.js @@ -7,6 +7,6 @@ exports.RXDB_VERSION = void 0; /** * This file is replaced in the 'npm run build:version' script. */ -var RXDB_VERSION = '14.5.2'; +var RXDB_VERSION = '14.6.0'; exports.RXDB_VERSION = RXDB_VERSION; //# sourceMappingURL=utils-rxdb-version.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-rxdb-version.js.map b/dist/lib/plugins/utils/utils-rxdb-version.js.map index e39df14b27e..b72dec2c0a9 100644 --- a/dist/lib/plugins/utils/utils-rxdb-version.js.map +++ b/dist/lib/plugins/utils/utils-rxdb-version.js.map @@ -1 +1 @@ -{"version":3,"file":"utils-rxdb-version.js","names":["RXDB_VERSION","exports"],"sources":["../../../../src/plugins/utils/utils-rxdb-version.ts"],"sourcesContent":["/**\n * This file is replaced in the 'npm run build:version' script.\n */\nexport const RXDB_VERSION = '14.5.2';\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACO,IAAMA,YAAY,GAAG,QAAQ;AAACC,OAAA,CAAAD,YAAA,GAAAA,YAAA"} \ No newline at end of file +{"version":3,"file":"utils-rxdb-version.js","names":["RXDB_VERSION","exports"],"sources":["../../../../src/plugins/utils/utils-rxdb-version.ts"],"sourcesContent":["/**\n * This file is replaced in the 'npm run build:version' script.\n */\nexport const RXDB_VERSION = '14.6.0';\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACO,IAAMA,YAAY,GAAG,QAAQ;AAACC,OAAA,CAAAD,YAAA,GAAAA,YAAA"} \ No newline at end of file diff --git a/dist/lib/rx-collection.js b/dist/lib/rx-collection.js index 225885bcca5..7bd0735369f 100644 --- a/dist/lib/rx-collection.js +++ b/dist/lib/rx-collection.js @@ -521,6 +521,15 @@ var RxCollectionBase = /*#__PURE__*/function () { get: function () { return this.$.pipe((0, _operators.filter)(cE => cE.operation === 'DELETE')); } + + // defaults + + /** + * When the collection is destroyed, + * these functions will be called an awaited. + * Used to automatically clean up stuff that + * belongs to this collection. + */ }, { key: "asRxCollection", get: function () { diff --git a/dist/lib/rx-collection.js.map b/dist/lib/rx-collection.js.map index b946ea6c207..3226a0781ab 100644 --- a/dist/lib/rx-collection.js.map +++ b/dist/lib/rx-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection.js","names":["_operators","require","_utils","_rxCollectionHelper","_rxQuery","_rxError","_docCache","_queryCache","_changeEventBuffer","_hooks","_rxDocumentPrototypeMerge","_rxStorageHelper","_replicationProtocol","_incrementalWrite","_rxDocument","_overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","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","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","migrationNeeded","pluginMissing","getDataMigrator","migrate","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","useDocs","useDocData","fillObjectDataBeforeInsert","docs","hasHooks","Promise","all","doc","docsMap","insertRows","set","row","document","results","bulkWrite","rxDocuments","Object","values","writtenDocData","getCachedRxDocument","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","forEach","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","successIds","keys","getFromMapOrThrow","bulkUpsert","insertData","useJsonByDocId","useJson","newRxError","ret","slice","updatedDocs","status","collection","writeError","documentId","writeData","docDataInDb","documentInDb","newDoc","incrementalModify","concat","upsert","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","selector","limit","isArray","newRxTypeError","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","res","timeout","setTimeout","delete","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","hashFunction","_createClass2","default","operation","exports","colProto","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","devMode","overwritable","isDevMode","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","catch","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs/operators';\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';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocumentCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n MigrationState,\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} from './types';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\nimport { IncrementalWriteQueue } from './incremental-write';\nimport { beforeDocumentUpdateWrite } from './rx-document';\nimport { overwritable } from './overwritable';\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> {\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: KeyFunctionMap = {},\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 };\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 // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().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 docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[primaryPath] as any, 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 = Object.values(results.success)\n .map((writtenDocData) => this._docCache.getCachedRxDocument(writtenDocData));\n\n if (this.hasHooks('post', 'insert')) {\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: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\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 (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[] = Object.keys(results.success);\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: Object.values(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 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 let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('VD2', {\n collection: this.name,\n writeError: error\n });\n }\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n return newDoc;\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[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 > {\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 > {\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 // 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 as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\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 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.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,UAAA,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,gBA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,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAASE,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYhQ,gBAAgB;AAC1C"} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["_operators","require","_utils","_rxCollectionHelper","_rxQuery","_rxError","_docCache","_queryCache","_changeEventBuffer","_hooks","_rxDocumentPrototypeMerge","_rxStorageHelper","_replicationProtocol","_incrementalWrite","_rxDocument","_overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","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","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","migrationNeeded","pluginMissing","getDataMigrator","migrate","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","useDocs","useDocData","fillObjectDataBeforeInsert","docs","hasHooks","Promise","all","doc","docsMap","insertRows","set","row","document","results","bulkWrite","rxDocuments","Object","values","writtenDocData","getCachedRxDocument","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","forEach","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","successIds","keys","getFromMapOrThrow","bulkUpsert","insertData","useJsonByDocId","useJson","newRxError","ret","slice","updatedDocs","status","collection","writeError","documentId","writeData","docDataInDb","documentInDb","newDoc","incrementalModify","concat","upsert","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","selector","limit","isArray","newRxTypeError","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","res","timeout","setTimeout","delete","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","hashFunction","_createClass2","default","operation","exports","colProto","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","devMode","overwritable","isDevMode","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","catch","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs/operators';\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';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocumentCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n MigrationState,\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} from './types';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\nimport { IncrementalWriteQueue } from './incremental-write';\nimport { beforeDocumentUpdateWrite } from './rx-document';\nimport { overwritable } from './overwritable';\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> {\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: KeyFunctionMap = {},\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 };\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 // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().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 docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[primaryPath] as any, 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 = Object.values(results.success)\n .map((writtenDocData) => this._docCache.getCachedRxDocument(writtenDocData));\n\n if (this.hasHooks('post', 'insert')) {\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: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\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 (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[] = Object.keys(results.success);\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: Object.values(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 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 let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('VD2', {\n collection: this.name,\n writeError: error\n });\n }\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n return newDoc;\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[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 > {\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 > {\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 // 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 as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\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 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.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,UAAA,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,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AAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAICuG,KAAK,CAACC,GAAG,IAAI;MACV,OAAO9O,eAAe,CAACoM,KAAK,EAAE,CACzBtI,IAAI,CAAC,MAAM2B,OAAO,CAACsJ,MAAM,CAACD,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAASE,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYhQ,gBAAgB;AAC1C"} \ No newline at end of file diff --git a/dist/lib/rx-database.js b/dist/lib/rx-database.js index aa0321ef8b1..8612dedd639 100644 --- a/dist/lib/rx-database.js +++ b/dist/lib/rx-database.js @@ -339,6 +339,43 @@ var RxDatabaseBase = /*#__PURE__*/function () { get: function () { return this.observable$; } + + /** + * Because having unhandled exceptions would fail, + * we have to store the async errors of the constructor here + * so we can throw them later. + */ + + /** + * When the database is destroyed, + * these functions will be called an awaited. + * Used to automatically clean up stuff that + * belongs to this collection. + */ + + /** + * Unique token that is stored with the data. + * Used to detect if the dataset has been deleted + * and if two RxDatabase instances work on the same dataset or not. + * + * Because reading and writing the storageToken runs in the hot path + * of database creation, we do not await the storageWrites but instead + * work with the promise when we need the value. + */ + + /** + * Stores the whole state of the internal storage token document. + * We need this in some plugins. + */ + + /** + * Contains the ids of all event bulks that have been emitted + * by the database. + * Used to detect duplicates that come in again via BroadcastChannel + * or other streams. + * TODO instead of having this here, we should add a test to ensure each RxStorage + * behaves equal and does never emit duplicate eventBulks. + */ }, { key: "asRxDatabase", get: function () { diff --git a/dist/lib/rx-database.js.map b/dist/lib/rx-database.js.map index 1aa28dc3617..c5543e8f3af 100644 --- a/dist/lib/rx-database.js.map +++ b/dist/lib/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["_customIdleQueue","require","_utils","_rxError","_rxSchema","_hooks","_rxjs","_operators","_rxCollection","_rxStorageHelper","_obliviousSet","_rxDatabaseInternalStore","_rxCollectionHelper","_overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","IdleQueue","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","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","$emit","has","id","add","next","removeCollectionDoc","schema","getSingleDocument","getPrimaryKeyOfInternalDocument","_collectionNamePrimary","INTERNAL_CONTEXT_COLLECTION","newRxError","writeDoc","flatCloneDocWithMeta","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","forEach","args","collectionName","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","database","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","ensureNoStartupErrors","error","_id","status","writeError","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","Promise","all","keys","map","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","runAsyncPluginHooks","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass2","default","exports","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","INTERNAL_STORAGE_NAME","devMode","overwritable","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashSha256","randomCouchString","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","getAllCollectionDocuments","statics","collectionNames","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 AllMigrationStates,\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} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\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';\nimport { removeCollectionStorages } from './rx-collection-helper';\nimport { overwritable } from './overwritable';\n\n/**\n * stores the used database 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> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\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 ) {\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 _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 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 Object.entries(collectionCreators).forEach(([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: 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 const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, 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 !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\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 /**\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');\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.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));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/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>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256\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);\n }\n USED_DATABASE_NAMES.add(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(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 ) 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): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\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 ))\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;AAUA,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,IAAAW,mBAAA,GAAAX,OAAA;AACA,IAAAY,aAAA,GAAAZ,OAAA;AAEA;AACA;AACA;AACA;AACA,IAAMa,mBAAgC,GAAG,IAAIC,GAAG,EAAE;AAElD,IAAIC,QAAQ,GAAG,CAAC;AAAC,IAEJC,cAAc;EAQvB;AACJ;AACA;AACA;AACA;;EAGI,SAAAA,eACoBC,IAAY;EAC5B;AACR;AACA;AACA;EACwBC,KAAa,EACbC,OAAsD,EACtDC,uBAAgD,EAChDC,QAAa,EACbC,aAAsB,EACtBC,WAAoB,GAAG,KAAK,EACrCC,OAAY,GAAG,CAAC,CAAC;EACxB;AACR;AACA;EACwBC,aAA0F,EAC1FC,YAA0B,EAC1BC,aAAwC,EACxCC,cAAwB,EAC1C;IAAA,KA7BcC,SAAS,GAAc,IAAIC,0BAAS,EAAE;IAAA,KAOtCC,gBAAgB,GAAG,IAAIjB,GAAG,EAAqE;I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J;EACJ,CAAC,CAAC;EAEF,MAAMgK,0BAA0B,CAACvB,MAAM,EAAE;EACzC,OAAO4B,sBAAsB;AACjC;AAEO,SAASI,YAAYA,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAY7K,cAAc;AACxC;AAEO,SAAS8K,OAAOA,CAAA,EAAW;EAC9B,OAAO/K,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAegL,iCAAiCA,CACnDnF,QAAoB,EACJ;EAChB,IAAMoF,QAAQ,GAAG,MAAMpF,QAAQ,CAAC9D,oBAAoB;EACpD,OAAOkJ,QAAQ,CAACtI,IAAI,CAACuI,aAAa,KAAKrF,QAAQ,CAAC1F,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,eAAegG,qBAAqBA,CACvC+D,UAAyC,EAC3C;EACE,MAAMA,UAAU,CAACrI,YAAY;EAC7B,IAAIqI,UAAU,CAAChJ,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMgJ,UAAU,CAAChJ,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ"} \ No newline at end of file +{"version":3,"file":"rx-database.js","names":["_customIdleQueue","require","_utils","_rxError","_rxSchema","_hooks","_rxjs","_operators","_rxCollection","_rxStorageHelper","_obliviousSet","_rxDatabaseInternalStore","_rxCollectionHelper","_overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","IdleQueue","storageInstances","_subs","startupErrors","onDestroy","destroyed","collections","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","$emit","has","id","add","next","removeCollectionDoc","schema","getSingleDocument","getPrimaryKeyOfInternalDocument","_collectionNamePrimary","INTERNAL_CONTEXT_COLLECTION","newRxError","writeDoc","flatCloneDocWithMeta","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","forEach","args","collectionName","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","database","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","ensureNoStartupErrors","error","_id","status","writeError","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","Promise","all","keys","map","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","runAsyncPluginHooks","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass2","default","exports","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","INTERNAL_STORAGE_NAME","devMode","overwritable","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashSha256","randomCouchString","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","getAllCollectionDocuments","statics","collectionNames","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 AllMigrationStates,\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} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\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';\nimport { removeCollectionStorages } from './rx-collection-helper';\nimport { overwritable } from './overwritable';\n\n/**\n * stores the used database 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> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\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 ) {\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 _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 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 Object.entries(collectionCreators).forEach(([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: 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 const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, 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 !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\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 /**\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');\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.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));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/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>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashSha256\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);\n }\n USED_DATABASE_NAMES.add(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(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 ) 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): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\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 ))\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;AAUA,IAAAE,QAAA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AAO/K,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAegL,iCAAiCA,CACnDnF,QAAoB,EACJ;EAChB,IAAMoF,QAAQ,GAAG,MAAMpF,QAAQ,CAAC9D,oBAAoB;EACpD,OAAOkJ,QAAQ,CAACtI,IAAI,CAACuI,aAAa,KAAKrF,QAAQ,CAAC1F,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,eAAegG,qBAAqBA,CACvC+D,UAAyC,EAC3C;EACE,MAAMA,UAAU,CAACrI,YAAY;EAC7B,IAAIqI,UAAU,CAAChJ,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMgJ,UAAU,CAAChJ,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ"} \ No newline at end of file diff --git a/dist/lib/rx-query.js b/dist/lib/rx-query.js index 9e69c775ce8..c19c3d1a787 100644 --- a/dist/lib/rx-query.js +++ b/dist/lib/rx-query.js @@ -62,6 +62,13 @@ var RxQueryBase = /*#__PURE__*/function () { this.isFindOneByIdQuery = isFindOneByIdQuery(this.collection.schema.primaryPath, mangoQuery); } var _proto = RxQueryBase.prototype; + /** + * Returns an observable that emits the results + * This should behave like an rxjs-BehaviorSubject which means: + * - Emit the current result-set on subscribe + * - Emit the new result-set when an RxChangeEvent comes in + * - Do not emit anything before the first result-set was created (no null) + */ /** * set the new result-data as result-docs of the query * @param newResultData json-docs that were received from the storage @@ -336,6 +343,13 @@ var RxQueryBase = /*#__PURE__*/function () { } // stores the changeEvent-number of the last handled change-event + + // time stamps on when the last full exec over the database has run + // used to properly handle events that happen while the find-query is running + /** + * ensures that the exec-runs + * are not run in parallel + */ }, { key: "queryMatcher", get: function () { diff --git a/dist/lib/rx-query.js.map b/dist/lib/rx-query.js.map index 08c8998795d..6e40b4cec22 100644 --- a/dist/lib/rx-query.js.map +++ b/dist/lib/rx-query.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.js","names":["_rxjs","require","_operators","_utils","_rxError","_hooks","_eventReduce","_queryCache","_rxQueryHelper","_queryCount","newQueryID","RxQueryBase","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","docsData","docsMap","Map","docsDataMap","count","docs","time","Array","from","values","map","docData","_docCache","getCachedRxDocument","doc","set","primary","_data","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","mode","database","allowSlowCount","newRxError","queryObj","ids","ensureNotFalsy","selector","$in","ret","mustBeQueried","forEach","getLatestDocumentDataIfExists","_deleted","push","findDocumentsById","Object","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","firstValueFrom","$","toString","stringObj","sortObject","value","JSON","stringify","stringifyFilter","hookInput","rxQuery","normalizeMangoQuery","jsonSchema","runPluginHooks","storage","statics","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","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","useResult","slice","merge","normalizedQuery","overwriteGetterForCaching","getQueryMatcher","exports","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","latestAfter","areRxDocumentArraysEqual","resolve","docIds","docId","queryResult","documents","keys","$eq","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 stringifyFilter,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\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} from './types';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\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: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docsMap: Map>;\n docs: RxDocument[];\n count: number;\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 time: number;\n } | 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.docs.length === 0 ? null : useResult.docs[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.docs.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\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\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsMap: new Map(),\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const docsDataMap = new Map();\n const docsMap = new Map();\n const docs = newResultData.map(docData => this.collection._docCache.getCachedRxDocument(docData));\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 */\n const docsData = docs.map(doc => {\n docsDataMap.set(doc.primary, doc._data);\n docsMap.set(doc.primary, doc);\n return doc._data;\n });\n\n this._result = {\n docsData,\n docsMap,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\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 Object.values(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)\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, stringifyFilter);\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 runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\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\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\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 * 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 docs.push(docData);\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n const docsMap = await collection.storageInstance.findDocumentsById(docIds, false);\n Object.values(docsMap).forEach(docData => {\n docs.push(docData);\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 docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n docData = docsMap[docId];\n }\n if (docData) {\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;AAiBA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AACA,IAAAO,cAAA,GAAAP,OAAA;AAEA,IAAIQ,WAAW,GAAG,CAAC;AACnB,IAAMC,UAAU,GAAG,SAAAA,CAAA,EAAoB;EACnC,OAAO,EAAED,WAAW;AACxB,CAAC;AAAC,IAEWE,WAAW;EAQpB;AACJ;AACA;;EAII;;EAKA;;EAMA;AACJ;AACA;AACA;;EAiBI,SAAAA,YACWC,EAAa,EACbC,UAA2C,EAC3CC,UAAmC;EAC1C;EACOC,KAAU,GAAG,CAAC,CAAC,EACxB;IAAA,KA7CKC,EAAE,GAAWN,UAAU,EAAE;IAAA,KAKzBO,sBAAsB,GAAW,CAAC;IAAA,KAClCC,aAAa,GAAG,IAAAC,UAAG,GAAE;IAAA,KAGrBC,gBAAgB,GAAG,CAAC;IAAA,KAEpBC,QAAQ,GAAG,KAAK;IAAA,KAGhBC,SAAS,GAAG,IAAIC,qBAAe,CAAC,IAAI,CAAC;IAAA,KASrCC,OAAO,GAaH,IAAI;IAAA,KAqFRC,kBAAkB,GAAgB,CAAC,CAAC;IAAA,KAIpCC,cAAc,GAA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AgB,EAAE;IAChD,IAAMsH,WAAW,GAAG,MAAMnK,UAAU,CAAC+C,eAAe,CAACwB,KAAK,CAAC3B,aAAa,CAAC;IACzEf,IAAI,GAAGsI,WAAW,CAACC,SAAS;EAChC;EACA,OAAOvI,IAAI;AAEf;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASZ,kBAAkBA,CAC9BE,WAAmB,EACnBoD,KAAsB,EACG;EACzB;EACA,IACI,CAACA,KAAK,CAACgC,IAAI,IACXhC,KAAK,CAAChB,QAAQ,IACdS,MAAM,CAACqG,IAAI,CAAC9F,KAAK,CAAChB,QAAQ,CAAC,CAACb,MAAM,KAAK,CAAC,IACxC6B,KAAK,CAAChB,QAAQ,CAACpC,WAAW,CAAC,EAC7B;IACE,IAAM2D,KAAU,GAAGP,KAAK,CAAChB,QAAQ,CAACpC,WAAW,CAAC;IAC9C,IAAI,OAAO2D,KAAK,KAAK,QAAQ,EAAE;MAC3B,OAAOA,KAAK;IAChB,CAAC,MAAM,IACHd,MAAM,CAACqG,IAAI,CAACvF,KAAK,CAAC,CAACpC,MAAM,KAAK,CAAC,IAC/B,OAAOoC,KAAK,CAACwF,GAAG,KAAK,QAAQ,EAC/B;MACE,OAAOxF,KAAK,CAACwF,GAAG;IACpB;;IAEA;IACA,IACItG,MAAM,CAACqG,IAAI,CAACvF,KAAK,CAAC,CAACpC,MAAM,KAAK,CAAC,IAC/BX,KAAK,CAAC8D,OAAO,CAACf,KAAK,CAACwF,GAAG,CAAC;IACxB;IACA,CAAExF,KAAK,CAACwF,GAAG,CAAWC,IAAI,CAACC,CAAC,IAAI,OAAOA,CAAC,KAAK,QAAQ,CAAC,EACxD;MACE,OAAO1F,KAAK,CAACwF,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIO,SAASG,SAASA,CAACC,GAAQ,EAAW;EACzC,OAAOA,GAAG,YAAY7K,WAAW;AACrC"} \ No newline at end of file +{"version":3,"file":"rx-query.js","names":["_rxjs","require","_operators","_utils","_rxError","_hooks","_eventReduce","_queryCache","_rxQueryHelper","_queryCount","newQueryID","RxQueryBase","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","docsData","docsMap","Map","docsDataMap","count","docs","time","Array","from","values","map","docData","_docCache","getCachedRxDocument","doc","set","primary","_data","length","_execOverDatabase","preparedQuery","getPreparedQuery","result","storageInstance","mode","database","allowSlowCount","newRxError","queryObj","ids","ensureNotFalsy","selector","$in","ret","mustBeQueried","forEach","getLatestDocumentDataIfExists","_deleted","push","findDocumentsById","Object","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","firstValueFrom","$","toString","stringObj","sortObject","value","JSON","stringify","stringifyFilter","hookInput","rxQuery","normalizeMangoQuery","jsonSchema","runPluginHooks","storage","statics","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","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","useResult","slice","merge","normalizedQuery","overwriteGetterForCaching","getQueryMatcher","exports","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","latestAfter","areRxDocumentArraysEqual","resolve","docIds","docId","queryResult","documents","keys","$eq","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 stringifyFilter,\n pluginMissing,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\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} from './types';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport { getQueryMatcher, normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\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: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docsMap: Map>;\n docs: RxDocument[];\n count: number;\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 time: number;\n } | 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.docs.length === 0 ? null : useResult.docs[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.docs.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\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\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsMap: new Map(),\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const docsDataMap = new Map();\n const docsMap = new Map();\n const docs = newResultData.map(docData => this.collection._docCache.getCachedRxDocument(docData));\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 */\n const docsData = docs.map(doc => {\n docsDataMap.set(doc.primary, doc._data);\n docsMap.set(doc.primary, doc);\n return doc._data;\n });\n\n this._result = {\n docsData,\n docsMap,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\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 Object.values(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)\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, stringifyFilter);\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 runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\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\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\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 * 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 docs.push(docData);\n return false;\n } else {\n return true;\n }\n });\n // otherwise get from storage\n const docsMap = await collection.storageInstance.findDocumentsById(docIds, false);\n Object.values(docsMap).forEach(docData => {\n docs.push(docData);\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 docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n docData = docsMap[docId];\n }\n if (docData) {\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;AAiBA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AACA,IAAAO,cAAA,GAAAP,OAAA;AAEA,IAAIQ,WAAW,GAAG,CAAC;AACnB,IAAMC,UAAU,GAAG,SAAAA,CAAA,EAAoB;EACnC,OAAO,EAAED,WAAW;AACxB,CAAC;AAAC,IAEWE,WAAW;EAQpB;AACJ;AACA;;EAII;;EAKA;;EAMA;AACJ;AACA;AACA;;EAiBI,SAAAA,YACWC,EAAa,EACbC,UAA2C,EAC3CC,UAAmC;EAC1C;EACOC,KAAU,GAAG,CAAC,CAAC,EACxB;IAAA,KA7CKC,EAAE,GAAWN,UAAU,EAAE;IAAA,KAKzBO,sBAAsB,GAAW,CAAC;IAAA,KAClCC,aAAa,GAAG,IAAAC,UAAG,GAAE;IAAA,KAGrBC,gBAAgB,GAAG,CAAC;IAAA,KAEpBC,QAAQ,GAAG,KAAK;IAAA,KAGhBC,SAAS,GAAG,IAAIC,qBAAe,CAAC,IAAI,CAAC;IAAA,KASrCC,OAAO,GAaH,IAAI;IAAA,KAqFRC,kBAAkB,GAAgB,CAAC,CAAC;IAAA,KAIpCC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,OAAOA,GAAG,YAAY7K,WAAW;AACrC"} \ No newline at end of file diff --git a/dist/rxdb.browserify.js b/dist/rxdb.browserify.js index 6cba42b12d5..96375a35c89 100644 --- a/dist/rxdb.browserify.js +++ b/dist/rxdb.browserify.js @@ -206,9 +206,6 @@ function getIndexableStringMonad(schema, index) { } else { // is number var parsedLengths = props.parsedLengths; - if (!fieldValue) { - fieldValue = 0; - } str += getNumberIndexString(parsedLengths, fieldValue); } } @@ -228,6 +225,8 @@ function getStringLengthOfIndexNumber(schemaPart) { decimals = multipleOfParts[1].length; } return { + minimum, + maximum, nonDecimals, decimals, roundedMinimum: minimum @@ -256,12 +255,32 @@ function getPrimaryKeyFromIndexableString(indexableString, primaryKeyLength) { return primaryKey; } function getNumberIndexString(parsedLengths, fieldValue) { + /** + * Ensure that the given value is in the boundaries + * of the schema, otherwise it would create a broken index string. + * This can happen for example if you have a minimum of 0 + * and run a query like + * selector { + * numField: { $gt: -1000 } + * } + */ + if (typeof fieldValue === 'undefined') { + fieldValue = 0; + } + if (fieldValue < parsedLengths.minimum) { + fieldValue = parsedLengths.minimum; + } + if (fieldValue > parsedLengths.maximum) { + fieldValue = parsedLengths.maximum; + } var str = ''; var nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString(); str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0'); var splitByDecimalPoint = fieldValue.toString().split('.'); var decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0'; - str += decimalValueAsString.padEnd(parsedLengths.decimals, '0'); + if (parsedLengths.decimals > 0) { + str += decimalValueAsString.padEnd(parsedLengths.decimals, '0'); + } return str; } function getStartIndexStringFromLowerBound(schema, index, lowerBound, inclusiveStart) { @@ -354,6 +373,9 @@ exports.DocumentCache = void 0; var _utils = require("./plugins/utils"); var _overwritable = require("./overwritable"); var _rxChangeEvent = require("./rx-change-event"); +/** + * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + */ /** * The DocumentCache stores RxDocument objects * by their primary key and revision. @@ -1209,6 +1231,11 @@ var _operators = require("rxjs/operators"); var _rxSchemaHelper = require("./rx-schema-helper"); var _utils = require("./plugins/utils"); var _rxjs = require("rxjs"); +/** + * Returns the validation errors. + * If document is fully valid, returns an empty array. + */ + /** * cache the validators by the schema-hash * so we can reuse them when multiple collections have the same schema @@ -1748,6 +1775,7 @@ exports.batchArray = batchArray; exports.countUntilNotMatching = countUntilNotMatching; exports.isMaybeReadonlyArray = isMaybeReadonlyArray; exports.lastOfArray = lastOfArray; +exports.maxOfNumbers = maxOfNumbers; exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; exports.shuffleArray = shuffleArray; exports.sumNumberArray = sumNumberArray; @@ -1850,6 +1878,9 @@ function sumNumberArray(array) { } return count; } +function maxOfNumbers(arr) { + return Math.max(...arr); +} },{}],14:[function(require,module,exports){ "use strict"; @@ -2860,7 +2891,7 @@ exports.RXDB_VERSION = void 0; /** * This file is replaced in the 'npm run build:version' script. */ -var RXDB_VERSION = '14.5.2'; +var RXDB_VERSION = '14.6.0'; exports.RXDB_VERSION = RXDB_VERSION; },{}],28:[function(require,module,exports){ @@ -5253,6 +5284,15 @@ var RxCollectionBase = /*#__PURE__*/function () { get: function () { return this.$.pipe((0, _operators.filter)(cE => cE.operation === 'DELETE')); } + + // defaults + + /** + * When the collection is destroyed, + * these functions will be called an awaited. + * Used to automatically clean up stuff that + * belongs to this collection. + */ }, { key: "asRxCollection", get: function () { @@ -5942,6 +5982,43 @@ var RxDatabaseBase = /*#__PURE__*/function () { get: function () { return this.observable$; } + + /** + * Because having unhandled exceptions would fail, + * we have to store the async errors of the constructor here + * so we can throw them later. + */ + + /** + * When the database is destroyed, + * these functions will be called an awaited. + * Used to automatically clean up stuff that + * belongs to this collection. + */ + + /** + * Unique token that is stored with the data. + * Used to detect if the dataset has been deleted + * and if two RxDatabase instances work on the same dataset or not. + * + * Because reading and writing the storageToken runs in the hot path + * of database creation, we do not await the storageWrites but instead + * work with the promise when we need the value. + */ + + /** + * Stores the whole state of the internal storage token document. + * We need this in some plugins. + */ + + /** + * Contains the ids of all event bulks that have been emitted + * by the database. + * Used to detect duplicates that come in again via BroadcastChannel + * or other streams. + * TODO instead of having this here, we should add a test to ensure each RxStorage + * behaves equal and does never emit duplicate eventBulks. + */ }, { key: "asRxDatabase", get: function () { @@ -7096,6 +7173,13 @@ var RxQueryBase = /*#__PURE__*/function () { this.isFindOneByIdQuery = isFindOneByIdQuery(this.collection.schema.primaryPath, mangoQuery); } var _proto = RxQueryBase.prototype; + /** + * Returns an observable that emits the results + * This should behave like an rxjs-BehaviorSubject which means: + * - Emit the current result-set on subscribe + * - Emit the new result-set when an RxChangeEvent comes in + * - Do not emit anything before the first result-set was created (no null) + */ /** * set the new result-data as result-docs of the query * @param newResultData json-docs that were received from the storage @@ -7370,6 +7454,13 @@ var RxQueryBase = /*#__PURE__*/function () { } // stores the changeEvent-number of the last handled change-event + + // time stamps on when the last full exec over the database has run + // used to properly handle events that happen while the find-query is running + /** + * ensures that the exec-runs + * are not run in parallel + */ }, { key: "queryMatcher", get: function () { diff --git a/dist/rxdb.browserify.min.js b/dist/rxdb.browserify.min.js index 5e01741c559..602bcc336d0 100644 --- a/dist/rxdb.browserify.min.js +++ b/dist/rxdb.browserify.min.js @@ -1,4 +1,4 @@ -!function e(t,r,n){function o(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[a]={exports:{}};t[a][0].call(l.exports,(function(e){return o(t[a][1][e]||e)}),l,l.exports,e,t,r,n)}return r[a].exports}for(var i="function"==typeof require&&require,a=0;a!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}();r.ChangeEventBuffer=o},{"rxjs/operators":675}],3:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getIndexMeta=a,r.getIndexStringLength=function(e,t){var r=a(e,t),n=0;return r.forEach((e=>{var t=e.schemaPart,r=t.type;if("string"===r)n+=t.maxLength;else if("boolean"===r)n+=1;else{var o=e.parsedLengths;n=n+o.nonDecimals+o.decimals}})),n},r.getIndexableStringMonad=function(e,t){var r=a(e,t);return function(e){for(var t="",n=0;n{var f=(0,n.getSchemaByObjectPath)(e,t),p=r[l],d=f.type;switch(d){case"string":var h=(0,o.ensureNotFalsy)(f.maxLength);c+="string"==typeof p?p.padEnd(h," "):"".padEnd(h," ");break;case"boolean":if(null===p)c+=a?"0":i.INDEX_MAX;else c+=p?"1":"0";break;case"number":case"integer":var b=s(f);if(null===p||p===i.INDEX_MIN){var v=a?"0":i.INDEX_MAX;c+=v.repeat(b.nonDecimals+b.decimals)}else c+=u(b,p);break;default:throw new Error("unknown index type "+d)}})),c},r.getStartIndexStringFromUpperBound=function(e,t,r,a){var c="";return t.forEach(((t,l)=>{var f=(0,n.getSchemaByObjectPath)(e,t),p=r[l],d=f.type;switch(d){case"string":var h=(0,o.ensureNotFalsy)(f.maxLength);c+="string"==typeof p?p.padEnd(h,a?i.INDEX_MAX:" "):"".padEnd(h,a?i.INDEX_MAX:" ");break;case"boolean":if(null===p)c+=a?"0":"1";else c+=p?"1":"0";break;case"number":case"integer":var b=s(f);if(null===p||p===i.INDEX_MAX)c+=(a?"9":"0").repeat(b.nonDecimals+b.decimals);else c+=u(b,p);break;default:throw new Error("unknown index type "+d)}})),c},r.getStringLengthOfIndexNumber=s;var n=e("./rx-schema-helper"),o=e("./plugins/utils"),i=e("./query-planner");function a(e,t){return t.map((t=>{var r=(0,n.getSchemaByObjectPath)(e,t);if(!r)throw new Error("not in schema: "+t);var i,a=r.type;return"number"!==a&&"integer"!==a||(i=s(r)),{fieldName:t,schemaPart:r,parsedLengths:i,hasComplexPath:t.includes("."),getValueFn:(0,o.objectPathMonad)(t)}}))}function s(e){var t=Math.floor(e.minimum),r=Math.ceil(e.maximum),n=e.multipleOf,o=(r-t).toString().length,i=n.toString().split("."),a=0;return i.length>1&&(a=i[1].length),{nonDecimals:o,decimals:a,roundedMinimum:t}}function u(e,t){var r="";r+=(Math.floor(t)-e.roundedMinimum).toString().padStart(e.nonDecimals,"0");var n=t.toString().split(".");return r+=(n.length>1?n[1]:"0").padEnd(e.decimals,"0")}},{"./plugins/utils":12,"./query-planner":31,"./rx-schema-helper":50}],4:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.DocumentCache=void 0;var n=e("./plugins/utils"),o=e("./overwritable"),i=e("./rx-change-event"),a=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.documentByRevisionHeight.delete(e.revisionHeight),0===r.documentByRevisionHeight.size&&this.cacheItemByDocId.delete(t))})):void 0,this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var n=(0,i.getDocumentDataOfRxChangeEvent)(e);r.latestDoc=n}}))}var t=e.prototype;return t.getCachedRxDocument=function(e){var t,r=e[this.primaryPath],i=(0,n.getHeightOfRevision)(e._rev),a=(0,n.getFromMapOrCreate)(this.cacheItemByDocId,r,(()=>function(e){return{documentByRevisionHeight:new Map,latestDoc:e}}(e))),u=a.documentByRevisionHeight.get(i),c=u?u.deref():void 0;return c||(e=o.overwritable.deepFreezeWhenDevMode(e),c=this.documentCreator(e),a.documentByRevisionHeight.set(i,(t=c,s?new WeakRef(t):{deref:()=>t})),this.registry&&this.registry.register(c,{docId:r,revisionHeight:i})),c},t.getLatestDocumentData=function(e){return(0,n.getFromMapOrThrow)(this.cacheItemByDocId,e).latestDoc},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.latestDoc},e}();r.DocumentCache=a;var s="function"==typeof WeakRef},{"./overwritable":9,"./plugins/utils":12,"./rx-change-event":39}],5:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RXQUERY_QUERY_PARAMS_CACHE=void 0,r.calculateNewResults=function(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=c(e),a=(0,i.ensureNotFalsy)(e._result).docsData.slice(0),s=(0,i.ensureNotFalsy)(e._result).docsDataMap,u=!1;return t.map((e=>(0,o.rxChangeEventToEventReduceChangeEvent)(e))).filter(i.arrayFilterNotEmpty).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:s},o=(0,n.calculateActionName)(t);return"runFullQueryAgain"===o||("doNothing"!==o?(u=!0,(0,n.runAction)(o,r,e,a,s),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:u,newResults:a}},r.getQueryParams=c,r.getSortFieldsOfQuery=s;var n=e("event-reduce-js"),o=e("./rx-change-event"),i=e("./plugins/utils"),a=e("./rx-query-helper");function s(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var u=new WeakMap;function c(e){return(0,i.getFromMapOrCreate)(u,e,(()=>{var t=e.collection,r=(0,a.normalizeMangoQuery)(t.storageInstance.schema,(0,i.clone)(e.mangoQuery)),n=t.schema.primaryPath,o=(0,a.getSortComparator)(t.schema.jsonSchema,r),u=(0,a.getQueryMatcher)(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:s(n,r),sortComparator:(t,r)=>{var n={docA:t,docB:r,rxQuery:e};return o(n.docA,n.docB)},queryMatcher:t=>u({doc:t,rxQuery:e}.doc)}}))}r.RXQUERY_QUERY_PARAMS_CACHE=u},{"./plugins/utils":12,"./rx-change-event":39,"./rx-query-helper":47,"event-reduce-js":413}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.HOOKS=void 0,r._clearHook=function(e,t){n[e]=n[e].filter((e=>e!==t))},r.runAsyncPluginHooks=function(e,t){return Promise.all(n[e].map((e=>e(t))))},r.runPluginHooks=function(e,t){n[e]&&n[e].forEach((e=>e(t)))};var n={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[]};r.HOOKS=n},{}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.IncrementalWriteQueue=void 0,r.findNewestOfDocumentStates=a,r.modifierFromPublicToInternal=function(e){return async t=>{var r=(0,o.stripMetaDataFromDocument)(t);r._deleted=t._deleted;var n=await e(r),i=Object.assign({},n,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==n._deleted?n._deleted:t._deleted});return void 0===i._deleted&&(i._deleted=!1),i}};var n=e("./rx-error"),o=e("./plugins/utils"),i=function(){function e(e,t,r,n){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=n}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],n=(0,o.getFromMapOrCreate)(this.queueByDocId,r,(()=>[]));return new Promise(((r,i)=>{var a={lastKnownDocumentState:e,modifier:t,resolve:r,reject:i};(0,o.ensureNotFalsy)(n).push(a),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,r])=>{var n=a(r.map((e=>e.lastKnownDocumentState))),i=n;for(var s of r)try{i=await s.modifier((0,o.clone)(i))}catch(e){s.reject(e),s.reject=()=>{},s.resolve=()=>{}}try{await this.preWrite(i,n)}catch(e){return void r.forEach((t=>t.reject(e)))}e.push({previous:n,document:i})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:{},success:{}};return await Promise.all(Array.from(Object.entries(r.success)).map((([e,r])=>{this.postWrite(r),(0,o.getFromMapOrThrow)(t,e).forEach((e=>e.resolve(r)))}))),Array.from(Object.entries(r.error)).forEach((([e,r])=>{var i=(0,o.getFromMapOrThrow)(t,e),a=(0,n.isBulkWriteConflictError)(r);if(a){var s=(0,o.getFromMapOrCreate)(this.queueByDocId,e,(()=>[]));i.reverse().forEach((e=>{e.lastKnownDocumentState=(0,o.ensureNotFalsy)(a.documentInDb),(0,o.ensureNotFalsy)(s).unshift(e)}))}else{var u=(0,n.rxStorageWriteErrorToRxError)(r);i.forEach((e=>e.reject(u)))}})),this.isRunning=!1,this.triggerRun()}},e}();function a(e){var t=e[0],r=(0,o.parseRevision)(t._rev).height;return e.forEach((e=>{var n=(0,o.parseRevision)(e._rev).height;n>r&&(t=e,r=n)})),t}r.IncrementalWriteQueue=i},{"./plugins/utils":12,"./rx-error":46}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={addRxPlugin:!0};Object.defineProperty(r,"addRxPlugin",{enumerable:!0,get:function(){return o.addRxPlugin}});var o=e("./plugin"),i=e("./rx-database");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===i[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return i[e]}}))}));var a=e("./rx-error");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===a[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return a[e]}}))}));var s=e("./rx-database-internal-store");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===s[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return s[e]}}))}));var u=e("./overwritable");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===u[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return u[e]}}))}));var c=e("./rx-collection");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===c[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=e("./rx-collection-helper");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===l[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return l[e]}}))}));var f=e("./rx-document");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===f[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./rx-change-event");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===p[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return p[e]}}))}));var d=e("./rx-document-prototype-merge");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===d[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return d[e]}}))}));var h=e("./rx-query");Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===h[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return h[e]}}))}));var b=e("./rx-query-helper");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===b[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return b[e]}}))}));var v=e("./rx-schema");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===v[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./rx-schema-helper");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===m[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=e("./rx-storage-helper");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===y[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return y[e]}}))}));var g=e("./rx-storage-statics");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===g[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return g[e]}}))}));var _=e("./replication-protocol/index");Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===_[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return _[e]}}))}));var O=e("./rx-storage-multiinstance");Object.keys(O).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===O[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return O[e]}}))}));var w=e("./custom-index");Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===w[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return w[e]}}))}));var j=e("./query-planner");Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===j[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return j[e]}}))}));var x=e("./plugin-helpers");Object.keys(x).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===x[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return x[e]}}))}));var S=e("./plugins/utils");Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===S[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return S[e]}}))}));var E=e("./hooks");Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===E[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return E[e]}}))}));var P=e("./query-cache");Object.keys(P).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===P[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return P[e]}}))}))},{"./custom-index":3,"./hooks":6,"./overwritable":9,"./plugin":11,"./plugin-helpers":10,"./plugins/utils":12,"./query-cache":30,"./query-planner":31,"./replication-protocol/index":36,"./rx-change-event":39,"./rx-collection":41,"./rx-collection-helper":40,"./rx-database":43,"./rx-database-internal-store":42,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-error":46,"./rx-query":49,"./rx-query-helper":47,"./rx-schema":51,"./rx-schema-helper":50,"./rx-storage-helper":52,"./rx-storage-multiinstance":53,"./rx-storage-statics":54}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.overwritable=void 0;var n={isDevMode:()=>!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 "};r.overwritable=n},{}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.wrapRxStorageInstance=function(e,t,r,o=(e=>e)){async function s(e){return e?await t(e):e}async function u(e){return e?await r(e):e}var c=new a.BehaviorSubject(0);return{databaseName:e.databaseName,internals:e.internals,cleanup:e.cleanup.bind(e),options:e.options,close:e.close.bind(e),schema:e.schema,collectionName:e.collectionName,count:e.count.bind(e),remove:e.remove.bind(e),originalStorageInstance:e,bulkWrite:async(t,r)=>{var o=[];await Promise.all(t.map((async e=>{var[t,r]=await Promise.all([e.previous?s(e.previous):void 0,s(e.document)]);o.push({previous:t,document:r})})));var l=await e.bulkWrite(o,r),f={success:{},error:{}},p=[];return Object.entries(l.success).forEach((([e,t])=>{p.push(u(t).then((t=>f.success[e]=t)))})),Object.entries(l.error).forEach((([e,t])=>{p.push(async function(e){var t=(0,i.flatClone)(e);return t.writeRow=(0,i.flatClone)(t.writeRow),t.documentInDb&&(t.documentInDb=await u(t.documentInDb)),t.writeRow.previous&&(t.writeRow.previous=await u(t.writeRow.previous)),t.writeRow.document=await u(t.writeRow.document),t}(t).then((t=>f.error[e]=t)))})),await Promise.all(p),await(0,a.firstValueFrom)(c.pipe((0,n.filter)((e=>0===e)))),f},query:t=>e.query(t).then((e=>Promise.all(e.documents.map((e=>u(e)))))).then((e=>({documents:e}))),getAttachmentData:async(t,r)=>{var n=await e.getAttachmentData(t,r);return n=await o(n)},findDocumentsById:(t,r)=>e.findDocumentsById(t,r).then((async e=>{var t={};return await Promise.all(Object.entries(e).map((async([e,r])=>{t[e]=await u(r)}))),t})),getChangedDocumentsSince:(t,r)=>e.getChangedDocumentsSince(t,r).then((async e=>({checkpoint:e.checkpoint,documents:await Promise.all(e.documents.map((e=>u(e))))}))),changeStream:()=>e.changeStream().pipe((0,n.tap)((()=>c.next(c.getValue()+1))),(0,n.mergeMap)((async e=>{var t=await Promise.all(e.events.map((async e=>{var[t,r]=await Promise.all([u(e.documentData),u(e.previousDocumentData)]);return{operation:e.operation,eventId:e.eventId,documentId:e.documentId,endTime:e.endTime,startTime:e.startTime,documentData:t,previousDocumentData:r,isLocal:!1}})));return{id:e.id,events:t,checkpoint:e.checkpoint,context:e.context}})),(0,n.tap)((()=>c.next(c.getValue()-1)))),conflictResultionTasks:()=>e.conflictResultionTasks().pipe((0,n.mergeMap)((async e=>{var t=await u(e.input.assumedMasterState),r=await u(e.input.newDocumentState),n=await u(e.input.realMasterState);return{id:e.id,context:e.context,input:{assumedMasterState:t,realMasterState:n,newDocumentState:r}}}))),resolveConflictResultionTask:t=>{if(t.output.isEqual)return e.resolveConflictResultionTask(t);var r={id:t.id,output:{isEqual:!1,documentData:t.output.documentData}};return e.resolveConflictResultionTask(r)}}},r.wrappedValidateStorageFactory=function(e,t){var r=(0,i.getFromMapOrCreate)(s,t,(()=>new Map));function n(t){var n=(0,i.defaultHashSha256)(JSON.stringify(t));return(0,i.getFromMapOrCreate)(r,n,(()=>e(t)))}return e=>Object.assign({},e.storage,{async createStorageInstance(t){var r,a=await e.storage.createStorageInstance(t),s=(0,o.getPrimaryFieldOfPrimaryKey)(t.schema.primaryKey);(0,i.requestIdleCallbackIfAvailable)((()=>r=n(t.schema)));var u=a.bulkWrite.bind(a);return a.bulkWrite=(e,o)=>{r||(r=n(t.schema));var i=[],a=[];return e.forEach((e=>{var t=e.document[s],n=r(e.document);n.length>0?i.push({status:422,isError:!0,documentId:t,writeRow:e,validationErrors:n}):a.push(e)})),(a.length>0?u(a,o):Promise.resolve({error:{},success:{}})).then((e=>(i.forEach((t=>{e.error[t.documentId]=t})),e)))},a}})};var n=e("rxjs/operators"),o=e("./rx-schema-helper"),i=e("./plugins/utils"),a=e("rxjs"),s=new Map},{"./plugins/utils":12,"./rx-schema-helper":50,rxjs:450,"rxjs/operators":675}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.addRxPlugin=function(e){if((0,c.runPluginHooks)("preAddRxPlugin",{plugin:e,plugins:p}),p.has(e))return;if(d.has(e.name))throw(0,l.newRxError)("PL3",{name:e.name,plugin:e});p.add(e),d.add(e.name);if(!e.rxdb)throw(0,l.newRxTypeError)("PL1",{plugin:e});e.init&&e.init();e.prototypes&&Object.entries(e.prototypes).forEach((([e,t])=>t(f[e])));e.overwritable&&Object.assign(u.overwritable,e.overwritable);e.hooks&&Object.entries(e.hooks).forEach((([e,t])=>{t.after&&c.HOOKS[e].push(t.after),t.before&&c.HOOKS[e].unshift(t.before)}))};var n=e("./rx-schema"),o=e("./rx-document"),i=e("./rx-query"),a=e("./rx-collection"),s=e("./rx-database"),u=e("./overwritable"),c=e("./hooks"),l=e("./rx-error"),f={RxSchema:n.RxSchema.prototype,RxDocument:o.basePrototype,RxQuery:i.RxQueryBase.prototype,RxCollection:a.RxCollectionBase.prototype,RxDatabase:s.RxDatabaseBase.prototype},p=new Set,d=new Set},{"./hooks":6,"./overwritable":9,"./rx-collection":41,"./rx-database":43,"./rx-document":45,"./rx-error":46,"./rx-query":49,"./rx-schema":51}],12:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./utils-array");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===n[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return n[e]}}))}));var o=e("./utils-blob");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===o[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return o[e]}}))}));var i=e("./utils-base64");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===i[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return i[e]}}))}));var a=e("./utils-revision");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===a[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return a[e]}}))}));var s=e("./utils-document");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===s[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return s[e]}}))}));var u=e("./utils-hash");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===u[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return u[e]}}))}));var c=e("./utils-promise");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===c[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=e("./utils-string");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===l[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return l[e]}}))}));var f=e("./utils-object-deep-equal");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===f[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./utils-object-dot-prop");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===p[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return p[e]}}))}));var d=e("./utils-object");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===d[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return d[e]}}))}));var h=e("./utils-map");Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===h[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return h[e]}}))}));var b=e("./utils-error");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===b[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return b[e]}}))}));var v=e("./utils-time");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===v[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./utils-regex");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===m[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=e("./utils-other");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===y[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return y[e]}}))}));var g=e("./utils-rxdb-version");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===g[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return g[e]}}))}))},{"./utils-array":13,"./utils-base64":14,"./utils-blob":15,"./utils-document":16,"./utils-error":17,"./utils-hash":18,"./utils-map":19,"./utils-object":22,"./utils-object-deep-equal":20,"./utils-object-dot-prop":21,"./utils-other":23,"./utils-promise":24,"./utils-regex":25,"./utils-revision":26,"./utils-rxdb-version":27,"./utils-string":28,"./utils-time":29}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.arrayFilterNotEmpty=function(e){if(null==e)return!1;return!0},r.asyncFilter=async function(e,t){var r=await Promise.all(e.map(t));return e.filter(((...[,e])=>r[e]))},r.batchArray=function(e,t){e=e.slice(0);var r=[];for(;e.length;){var n=e.splice(0,t);r.push(n)}return r},r.countUntilNotMatching=function(e,t){var r=0,n=-1;for(var o of e){if(!t(o,n+=1))break;r+=1}return r},r.isMaybeReadonlyArray=function(e){return Array.isArray(e)},r.lastOfArray=function(e){return e[e.length-1]},r.removeOneFromArrayIfMatches=function(e,t){var r=(e=e.slice()).length,n=!1;for(;r--&&!n;)t(e[r])&&(n=!0,e.splice(r,1));return e},r.shuffleArray=function(e){return e.slice(0).sort((()=>Math.random()-.5))},r.sumNumberArray=function(e){for(var t=0,r=e.length;r--;)t+=e[r];return t},r.toArray=function(e){return Array.isArray(e)?e.slice(0):[e]}},{}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.arrayBufferToBase64=function(e){for(var t="",r=new Uint8Array(e),n=r.byteLength,o=0;oe.arrayBuffer()));return(0,n.arrayBufferToBase64)(t)},r.blobToString=function(e){"[object Uint8Array]"===Object.prototype.toString.call(e)&&(e=new Blob([e]));if("string"==typeof e)return Promise.resolve(e);return e.text()},r.createBlob=function(e,t){return new Blob([e],{type:t})},r.createBlobFromBase64=async function(e,t){var r=await fetch("data:"+t+";base64,"+e);return await r.blob()},r.getBlobSize=function(e){return e.size},r.isBlob=function(e){return!!(e instanceof Blob||void 0!==t&&t.isBuffer(e))};var n=e("./utils-base64")}).call(this)}).call(this,e("buffer").Buffer)},{"./utils-base64":14,buffer:103}],16:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RX_META_LWT_MINIMUM=void 0,r.areRxDocumentArraysEqual=function(e,t,r){if(t.length!==r.length)return!1;var n=0,o=t.length;for(;nt._meta.lwt===r._meta.lwt?r[e]{r+=(0,n.ucfirst)(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 ")};var n=e("./utils-string")},{"./utils-string":28}],18:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defaultHashSha256=function(e){return(0,n.sha256)(e)};var n=e("ohash")},{ohash:447}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getFromMapOrCreate=function(e,t,r,n){var o=e.get(t);void 0===o?(o=r(),e.set(t,o)):n&&n(o);return o}},{}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.deepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,o;if(Array.isArray(t)){if((n=t.length)!==r.length)return!1;for(o=n;0!=o--;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();var i=Object.keys(t);if((n=i.length)!==Object.keys(r).length)return!1;for(o=n;0!=o--;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;0!=o--;){var a=i[o];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r}},{}],21:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.deepKeys=function(e){return[...f(e)]},r.deleteProperty=function(e,t){if(!n(e)||"string"!=typeof t)return!1;for(var r=a(t),o=0;o{var t=typeof e;return null!==e&&("object"===t||"function"===t)},o=new Set(["__proto__","prototype","constructor"]),i=new Set("0123456789");function a(e){var t=[],r="",n="start",a=!1;for(var s of e)switch(s){case"\\":if("index"===n)throw new Error("Invalid character in an index");if("indexEnd"===n)throw new Error("Invalid character after an index");a&&(r+=s),n="property",a=!a;break;case".":if("index"===n)throw new Error("Invalid character in an index");if("indexEnd"===n){n="property";break}if(a){a=!1,r+=s;break}if(o.has(r))return[];t.push(r),r="",n="property";break;case"[":if("index"===n)throw new Error("Invalid character in an index");if("indexEnd"===n){n="index";break}if(a){a=!1,r+=s;break}if("property"===n){if(o.has(r))return[];t.push(r),r=""}n="index";break;case"]":if("index"===n){t.push(Number.parseInt(r,10)),r="",n="indexEnd";break}if("indexEnd"===n)throw new Error("Invalid character after an index");default:if("index"===n&&!i.has(s))throw new Error("Invalid character in an index");if("indexEnd"===n)throw new Error("Invalid character after an index");"start"===n&&(n="property"),a&&(a=!1,r+="\\"),r+=s}switch(a&&(r+="\\"),n){case"property":if(o.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function s(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 u(e,t){if(s(e,t))throw new Error("Cannot use string index")}function c(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[\\.[]/g,"\\$&")}function l(e){return Array.isArray(e)?e.map(((e,t)=>[t,e])):Object.entries(e)}function*f(e,t=[]){if(n(e))for(var[r,o]of l(e))yield*f(o,[...t,r]);else t.length>0&&(yield function(e){var t="";for(var[r,n]of l(e))"number"==typeof n?t+="["+n+"]":(n=c(n),t+=0===r?n:"."+n);return t}(t))}},{}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.clone=void 0,r.deepFreeze=function e(t){return Object.freeze(t),Object.getOwnPropertyNames(t).forEach((function(r){!t.hasOwnProperty(r)||null===t[r]||"object"!=typeof t[r]&&"function"!=typeof t[r]||Object.isFrozen(t[r])||e(t[r])})),t},r.firstPropertyNameOfObject=function(e){return Object.keys(e)[0]},r.firstPropertyValueOfObject=function(e){var t=Object.keys(e)[0];return e[t]},r.flatClone=function(e){return Object.assign({},e)},r.flattenObject=function e(t){var r={};for(var n in t)if(t.hasOwnProperty(n))if("object"==typeof t[n]){var o=e(t[n]);for(var i in o)o.hasOwnProperty(i)&&(r[n+"."+i]=o[i])}else r[n]=t[n];return r},r.getFromObjectOrThrow=function(e,t){var r=e[t];if(!r)throw new Error("missing value from object "+t);return r},r.objectPathMonad=function(e){var t=e.split(".");if(1===t.length)return t=>t[e];return e=>{for(var r=e,n=0;n"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((t=>e(t,r)));if("object"==typeof t&&!Array.isArray(t)){if(t instanceof RegExp)return t;var n={};return Object.keys(t).sort(((e,t)=>e.localeCompare(t))).forEach((o=>{n[o]=e(t[o],r)})),n}return t},r.stringifyFilter=function(e,t){if(t instanceof RegExp)return t.toString();return t};var n=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),n=r.length;n--;)r[n]=e(t[n]);return r}var o={};for(var i in t)o[i]=e(t[i]);return o};r.clone=n},{}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RXJS_SHARE_REPLAY_DEFAULTS=void 0,r.ensureInteger=function(e){if(!Number.isInteger(e))throw new Error("ensureInteger() is falsy");return e},r.ensureNotFalsy=function(e){if(!e)throw new Error("ensureNotFalsy() is falsy");return e},r.getFromMapOrThrow=function(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r},r.runXTimes=function(e,t){new Array(e).fill(0).forEach(((e,r)=>t(r)))};r.RXJS_SHARE_REPLAY_DEFAULTS={bufferSize:1,refCount:!0}},{}],24:[function(e,t,r){"use strict";function n(e=0){return new Promise((t=>setTimeout(t,e)))}Object.defineProperty(r,"__esModule",{value:!0}),r.PROMISE_RESOLVE_VOID=r.PROMISE_RESOLVE_TRUE=r.PROMISE_RESOLVE_NULL=r.PROMISE_RESOLVE_FALSE=void 0,r.nextTick=function(){return new Promise((e=>setTimeout(e,0)))},r.promiseSeries=function(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))},r.promiseWait=n,r.requestIdleCallbackIfAvailable=function(e){"object"==typeof window&&window.requestIdleCallback&&window.requestIdleCallback(e)},r.requestIdlePromise=function(e=null){return"object"==typeof window&&window.requestIdleCallback?new Promise((t=>window.requestIdleCallback(t,{timeout:e}))):n(0)},r.toPromise=function(e){return e&&"function"==typeof e.then?e:Promise.resolve(e)};var o=Promise.resolve(!0);r.PROMISE_RESOLVE_TRUE=o;var i=Promise.resolve(!1);r.PROMISE_RESOLVE_FALSE=i;var a=Promise.resolve(null);r.PROMISE_RESOLVE_NULL=a;var s=Promise.resolve();r.PROMISE_RESOLVE_VOID=s},{}],25:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.REGEX_PARSE_REGEX_EXPRESSION=r.REGEX_ALL_PIPES=r.REGEX_ALL_DOTS=void 0,r.parseRegex=function(e){var t=(0,n.ensureNotFalsy)(e.toString().match(o));return{pattern:t[2],flags:t[3]}};var n=e("./utils-other");r.REGEX_ALL_DOTS=/\./g;r.REGEX_ALL_PIPES=/\|/g;var o=/(\/?)(.+)\1([a-z]*)/i;r.REGEX_PARSE_REGEX_EXPRESSION=o},{"./utils-other":23}],26:[function(e,t,r){"use strict";function n(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}Object.defineProperty(r,"__esModule",{value:!0}),r.createRevision=function(e,t){var r=t?t._rev:null;return(r?n(r).height:0)+1+"-"+e},r.getHeightOfRevision=function(e){return parseInt(e.split("-")[0],10)},r.parseRevision=n},{}],27:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RXDB_VERSION=void 0;r.RXDB_VERSION="14.5.2"},{}],28:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RANDOM_STRING=void 0,r.arrayBufferToString=function(e){return String.fromCharCode.apply(null,new Uint16Array(e))},r.isFolderPath=function(e){return!(!e.includes("/")&&!e.includes("\\"))},r.randomCouchString=function(e=10){for(var t="",r="abcdefghijklmnopqrstuvwxyz",n=0;n(0,n.requestIdlePromise)(200))).then((()=>{e.destroyed||e.cacheReplacementPolicy(e,e._queryCache),c.delete(e)}))},r.uncacheRxQuery=i;var n=e("./plugins/utils"),o=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return(0,n.getFromMapOrCreate)(this._map,t,(()=>e))},e}();function i(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function a(e){return e.refCount$.observers.length}r.QueryCache=o;r.DEFAULT_TRY_TO_KEEP_MAX=100;r.DEFAULT_UNEXECUTED_LIFETIME=3e4;var s=(e,t)=>(r,o)=>{if(!(o._map.size0||(0===l._lastEnsureEqual&&l._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,f).forEach((e=>i(o,e)))}};r.defaultCacheReplacementPolicyMonad=s;var u=s(100,3e4);r.defaultCacheReplacementPolicy=u;var c=new WeakSet;r.COLLECTIONS_WITH_RUNNING_CLEANUP=c},{"./plugins/utils":12}],31:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UPPER_BOUND_LOGICAL_OPERATORS=r.LOWER_BOUND_LOGICAL_OPERATORS=r.LOGICAL_OPERATORS=r.INDEX_MIN=r.INDEX_MAX=void 0,r.getMatcherQueryOpts=f,r.getQueryPlan=function(e,t){var r=(0,o.getPrimaryFieldOfPrimaryKey)(e.primaryKey),n=t.selector,u=e.indexes?e.indexes.slice(0):[];t.index?u=[t.index]:u.push([r]);var c,d=t.sort.map((e=>Object.keys(e)[0])).join(","),h=!!t.sort.find((e=>"desc"===Object.values(e)[0])),b=-1;u.forEach((r=>{var o=!0,u=!0,v=r.map((e=>{var t=n[e],r=t?Object.keys(t):[],c={};t&&r.length?r.forEach((e=>{if(s.has(e)){var r=f(e,t[e]);c=Object.assign(c,r)}})):c={startKey:u?a:i,endKey:o?i:a,inclusiveStart:!0,inclusiveEnd:!0};return void 0===c.startKey&&(c.startKey=a),void 0===c.endKey&&(c.endKey=i),void 0===c.inclusiveStart&&(c.inclusiveStart=!0),void 0===c.inclusiveEnd&&(c.inclusiveEnd=!0),u&&!c.inclusiveStart&&(u=!1),o&&!c.inclusiveEnd&&(o=!1),c})),m={index:r,startKeys:v.map((e=>e.startKey)),endKeys:v.map((e=>e.endKey)),inclusiveEnd:o,inclusiveStart:u,sortFieldsSameAsIndexFields:!h&&d===r.join(","),selectorSatisfiedByIndex:l(r,t.selector)},y=p(e,t,m);(y>0&&y>b||t.index)&&(b=y,c=m)})),c||(c={index:[r],startKeys:[a],endKeys:[i],inclusiveEnd:!0,inclusiveStart:!0,sortFieldsSameAsIndexFields:!h&&d===r,selectorSatisfiedByIndex:l([r],t.selector)});return c},r.isSelectorSatisfiedByIndex=l,r.rateQueryPlan=p;var n=e("./plugins/utils"),o=e("./rx-schema-helper"),i=String.fromCharCode(65535);r.INDEX_MAX=i;var a=Number.MIN_VALUE;r.INDEX_MIN=a;var s=new Set(["$eq","$gt","$gte","$lt","$lte"]);r.LOGICAL_OPERATORS=s;var u=new Set(["$eq","$gt","$gte"]);r.LOWER_BOUND_LOGICAL_OPERATORS=u;var c=new Set(["$eq","$lt","$lte"]);function l(e,t){var r,n;return!Object.entries(t).find((([t,r])=>!e.includes(t)||Object.entries(r).find((([e,t])=>!s.has(e)))))&&(!e.find((e=>{var n=t[e];if(!n)return!1;var o=Object.keys(n).find((e=>u.has(e)));return!(!r||!o)||("$eq"!==o&&(r=o),!1)}))&&!e.find((e=>{var r=t[e];if(!r)return!1;var o=Object.keys(r).find((e=>c.has(e)));return!(!n||!o)||("$eq"!==o&&(n=o),!1)})))}function f(e,t){switch(e){case"$eq":return{startKey:t,endKey:t};case"$lte":return{endKey:t};case"$gte":return{startKey:t};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}function p(e,t,r){var o=0,s=e=>{e>0&&(o+=e)};return s(10*(0,n.countUntilNotMatching)(r.startKeys,(e=>e!==a&&e!==i))),s(10*(0,n.countUntilNotMatching)(r.startKeys,(e=>e!==i&&e!==a))),s(10*(0,n.countUntilNotMatching)(r.startKeys,((e,t)=>e===r.endKeys[t]))*1.5),s(r.sortFieldsSameAsIndexFields?5:0),o}r.UPPER_BOUND_LOGICAL_OPERATORS=c},{"./plugins/utils":12,"./rx-schema-helper":50}],32:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getCheckpointKey=function(e){return"rx-storage-replication-"+e.hashFunction([e.identifier,e.forkInstance.databaseName,e.forkInstance.collectionName].join("||"))},r.getLastCheckpointDoc=async function(e,t){var r=(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,{isCheckpoint:"1",itemId:t}),o=(await e.input.metaInstance.findDocumentsById([r],!1))[r];return e.lastCheckpointDoc[t]=o,o?o.data:void 0},r.setCheckpoint=async function(e,t,r){var a=e.lastCheckpointDoc[t];if(r&&!e.events.canceled.getValue()&&(!a||JSON.stringify(a.data)!==JSON.stringify(r))){var s={id:"",isCheckpoint:"1",itemId:t,_deleted:!1,_attachments:{},data:r,_meta:(0,i.getDefaultRxDocumentMeta)(),_rev:(0,i.getDefaultRevision)()};for(s.id=(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,s);;){a&&(s.data=(0,o.stackCheckpoints)([a.data,s.data])),s._meta.lwt=(0,i.now)(),s._rev=(0,i.createRevision)(e.input.identifier,a);var u=await e.input.metaInstance.bulkWrite([{previous:a,document:s}],"replication-set-checkpoint");if(u.success[s.id])return void(e.lastCheckpointDoc[t]=(0,i.getFromObjectOrThrow)(u.success,s.id));var c=(0,i.getFromObjectOrThrow)(u.error,s.id);if(409!==c.status)throw c;a=(0,i.ensureNotFalsy)(c.documentInDb),s._rev=(0,i.createRevision)(e.input.identifier,a)}}};var n=e("../rx-schema-helper"),o=e("../rx-storage-helper"),i=e("../plugins/utils")},{"../plugins/utils":12,"../rx-schema-helper":50,"../rx-storage-helper":52}],33:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defaultConflictHandler=void 0,r.resolveConflictError=async function(e,t,r){var o=e.input.conflictHandler,i=await o(t,"replication-resolve-conflict");if(i.isEqual)return;var a=Object.assign({},i.documentData,{_meta:(0,n.flatClone)(r._meta),_rev:(0,n.getDefaultRevision)(),_attachments:(0,n.flatClone)(r._attachments)});return a._meta.lwt=(0,n.now)(),a._rev=(0,n.createRevision)(e.input.identifier,r),{resolvedDoc:a,output:i}};var n=e("../plugins/utils");r.defaultConflictHandler=function(e,t){return(0,n.deepEqual)(e.newDocumentState,e.realMasterState)?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})}},{"../plugins/utils":12}],34:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.startReplicationDownstream=async function(e){if(e.input.initialCheckpoint&&e.input.initialCheckpoint.downstream){await(0,s.getLastCheckpointDoc)(e,"down")||await(0,s.setCheckpoint)(e,"down",e.input.initialCheckpoint.downstream)}var t=e.input.hashFunction(e.input.identifier),r=e.input.replicationHandler,l=0,f=[];function p(t){e.stats.down.addNewTask=e.stats.down.addNewTask+1;var n={time:l++,task:t};f.push(n),e.streamQueue.down=e.streamQueue.down.then((()=>{for(var t=[];f.length>0;){e.events.active.down.next(!0);var n=(0,a.ensureNotFalsy)(f.shift());if(!(n.time(0,s.getLastCheckpointDoc)(e,"down")));var t=await e.checkpointQueue,n=[];for(;!e.events.canceled.getValue();){h=l++;var o=await r.masterChangesSince(t,e.input.pullBatchSize);if(0===o.documents.length)break;if(t=(0,i.stackCheckpoints)([t,o.checkpoint]),n.push(m(o.documents,t)),o.documents.length{if("RESYNC"===e)throw new Error("SNH");r=r.concat(e.documents),n=(0,i.stackCheckpoints)([n,e.checkpoint])})),m(r,(0,a.ensureNotFalsy)(n))}(t)})).then((()=>{e.events.active.down.next(!1),e.firstSyncDone.down.getValue()||e.events.canceled.getValue()||e.firstSyncDone.down.next(!0)}))}p("RESYNC");var d=r.masterChangeStream$.subscribe((t=>{e.stats.down.masterChangeStreamEmit=e.stats.down.masterChangeStreamEmit+1,p(t)}));(0,n.firstValueFrom)(e.events.canceled.pipe((0,n.filter)((e=>!!e)))).then((()=>d.unsubscribe()));var h=-1;var b=a.PROMISE_RESOLVE_VOID,v={docs:{}};function m(r,n){return e.stats.down.persistFromMaster=e.stats.down.persistFromMaster+1,r.forEach((t=>{var r=t[e.primaryPath];v.docs[r]=t})),v.checkpoint=n,b=b.then((()=>{var r=v.docs;v.docs={};var n=v.checkpoint,i=Object.keys(r);if(e.events.canceled.getValue()||0===i.length)return a.PROMISE_RESOLVE_VOID;var l=[],f={},p={},d=[];return Promise.all([e.input.forkInstance.findDocumentsById(i,!0),(0,c.getAssumedMasterState)(e,i)]).then((([n,o])=>Promise.all(i.map((async i=>{var s=n[i],h=s?(0,u.writeDocToDocState)(s):void 0,b=r[i],v=o[i];if(v&&v.metaDocument.isResolvedConflict===s._rev)return a.PROMISE_RESOLVE_VOID;var m=v&&h?e.input.conflictHandler({realMasterState:v.docData,newDocumentState:h},"downstream-check-if-equal-0").then((e=>e.isEqual)):a.PROMISE_RESOLVE_FALSE,y=await m;if(!y&&v&&v.docData._rev&&s._meta[e.input.identifier]&&(0,a.parseRevision)(s._rev).height===s._meta[e.input.identifier]&&(y=!0),s&&v&&!1===y||s&&!v)return a.PROMISE_RESOLVE_VOID;var g=h?e.input.conflictHandler({realMasterState:b,newDocumentState:h},"downstream-check-if-equal-1").then((e=>e.isEqual)):a.PROMISE_RESOLVE_FALSE,_=await g;if(h&&_)return v&&!1!==y||d.push((0,c.getMetaWriteRow)(e,h,v?v.metaDocument:void 0)),a.PROMISE_RESOLVE_VOID;var O=Object.assign({},b,s?{_meta:(0,a.flatClone)(s._meta),_attachments:{},_rev:(0,a.getDefaultRevision)()}:{_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}});if(b._rev){var w=s?(0,a.parseRevision)(s._rev).height+1:1;O._meta[e.input.identifier]=w}var j={previous:s,document:O};j.document._rev=(0,a.createRevision)(t,j.previous),l.push(j),f[i]=j,p[i]=(0,c.getMetaWriteRow)(e,b,v?v.metaDocument:void 0)}))))).then((()=>{if(l.length>0)return e.input.forkInstance.bulkWrite(l,e.downstreamBulkWriteFlag).then((t=>{Object.keys(t.success).forEach((t=>{e.events.processed.down.next(f[t]),d.push(p[t])})),Object.values(t.error).forEach((t=>{409!==t.status&&e.events.error.next((0,o.newRxError)("RC_PULL",{writeError:t}))}))}))})).then((()=>{if(d.length>0)return e.input.metaInstance.bulkWrite(d,"replication-down-write-meta").then((t=>{Object.entries(t.error).forEach((([t,r])=>{e.events.error.next((0,o.newRxError)("RC_PULL",{id:t,writeError:r}))}))}))})).then((()=>{e.checkpointQueue=e.checkpointQueue.then((()=>(0,s.setCheckpoint)(e,"down",n)))}))})).catch((t=>e.events.error.next(t)))}};var n=e("rxjs"),o=e("../rx-error"),i=e("../rx-storage-helper"),a=e("../plugins/utils"),s=e("./checkpoint"),u=e("./helper"),c=e("./meta-instance")},{"../plugins/utils":12,"../rx-error":46,"../rx-storage-helper":52,"./checkpoint":32,"./helper":35,"./meta-instance":37,rxjs:450}],35:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.docStateToWriteDoc=function(e,t,r){var o=Object.assign({},t,{_attachments:{},_meta:{lwt:(0,n.now)()},_rev:(0,n.getDefaultRevision)()});return o._rev=(0,n.createRevision)(e,r),o},r.writeDocToDocState=function(e){var t=(0,n.flatClone)(e);return delete t._attachments,delete t._meta,delete t._rev,t};var n=e("../plugins/utils")},{"../plugins/utils":12}],36:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={replicateRxStorageInstance:!0,awaitRxStorageReplicationFirstInSync:!0,awaitRxStorageReplicationInSync:!0,awaitRxStorageReplicationIdle:!0,rxStorageInstanceToReplicationHandler:!0,cancelRxStorageReplication:!0};r.awaitRxStorageReplicationFirstInSync=d,r.awaitRxStorageReplicationIdle=async function(e){await d(e);for(;;){var{down:t,up:r}=e.streamQueue;if(await Promise.all([r,t]),t===e.streamQueue.down&&r===e.streamQueue.up)return}},r.awaitRxStorageReplicationInSync=function(e){return Promise.all([e.streamQueue.up,e.streamQueue.down,e.checkpointQueue])},r.cancelRxStorageReplication=function(e){e.events.canceled.next(!0),e.events.active.up.complete(),e.events.active.down.complete(),e.events.processed.up.complete(),e.events.processed.down.complete(),e.events.resolvedConflicts.complete(),e.events.canceled.complete()},r.replicateRxStorageInstance=function(e){var t=(0,s.getCheckpointKey)(e),r={primaryPath:(0,i.getPrimaryFieldOfPrimaryKey)(e.forkInstance.schema.primaryKey),input:e,checkpointKey:t,downstreamBulkWriteFlag:"replication-downstream-"+t,events:{canceled:new o.BehaviorSubject(!1),active:{down:new o.BehaviorSubject(!0),up:new o.BehaviorSubject(!0)},processed:{down:new o.Subject,up:new o.Subject},resolvedConflicts:new o.Subject,error:new o.Subject},stats:{down:{addNewTask:0,downstreamProcessChanges:0,downstreamResyncOnce:0,masterChangeStreamEmit:0,persistFromMaster:0},up:{forkChangeStreamEmit:0,persistToMaster:0,persistToMasterConflictWrites:0,persistToMasterHadConflicts:0,processTasks:0,upstreamInitialSync:0}},firstSyncDone:{down:new o.BehaviorSubject(!1),up:new o.BehaviorSubject(!1)},streamQueue:{down:a.PROMISE_RESOLVE_VOID,up:a.PROMISE_RESOLVE_VOID},checkpointQueue:a.PROMISE_RESOLVE_VOID,lastCheckpointDoc:{}};return(0,u.startReplicationDownstream)(r),(0,l.startReplicationUpstream)(r),r},r.rxStorageInstanceToReplicationHandler=function(e,t,r){var n=(0,i.getPrimaryFieldOfPrimaryKey)(e.schema.primaryKey);return{masterChangeStream$:e.changeStream().pipe((0,o.map)((e=>({checkpoint:e.checkpoint,documents:e.events.map((e=>(0,c.writeDocToDocState)((0,a.ensureNotFalsy)(e.documentData))))})))),masterChangesSince:(t,r)=>e.getChangedDocumentsSince(r,t).then((e=>({checkpoint:e.documents.length>0?e.checkpoint:t,documents:e.documents.map((e=>(0,c.writeDocToDocState)(e)))}))),async masterWrite(o){var i={};o.forEach((e=>{var t=e.newDocumentState[n];i[t]=e}));var s=Object.keys(i),u=await e.findDocumentsById(s,!0),l=[],f=[];if(await Promise.all(Object.entries(i).map((async([e,n])=>{var o=u[e];o?o&&!n.assumedMasterState?l.push((0,c.writeDocToDocState)(o)):!0===(await t({realMasterState:(0,c.writeDocToDocState)(o),newDocumentState:(0,a.ensureNotFalsy)(n.assumedMasterState)},"rxStorageInstanceToReplicationHandler-masterWrite")).isEqual?f.push({previous:o,document:(0,c.docStateToWriteDoc)(r,n.newDocumentState,o)}):l.push((0,c.writeDocToDocState)(o)):f.push({document:(0,c.docStateToWriteDoc)(r,n.newDocumentState)})}))),f.length>0){var p=await e.bulkWrite(f,"replication-master-write");Object.values(p.error).forEach((e=>{if(409!==e.status)throw new Error("non conflict error");l.push((0,c.writeDocToDocState)((0,a.ensureNotFalsy)(e.documentInDb)))}))}return l}}};var o=e("rxjs"),i=e("../rx-schema-helper"),a=e("../plugins/utils"),s=e("./checkpoint");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===s[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return s[e]}}))}));var u=e("./downstream");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===u[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return u[e]}}))}));var c=e("./helper");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===c[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=e("./upstream");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===l[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return l[e]}}))}));var f=e("./meta-instance");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===f[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./conflicts");function d(e){return(0,o.firstValueFrom)((0,o.combineLatest)([e.firstSyncDone.down.pipe((0,o.filter)((e=>!!e))),e.firstSyncDone.up.pipe((0,o.filter)((e=>!!e)))])).then((()=>{}))}Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===p[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return p[e]}}))}))},{"../plugins/utils":12,"../rx-schema-helper":50,"./checkpoint":32,"./conflicts":33,"./downstream":34,"./helper":35,"./meta-instance":37,"./upstream":38,rxjs:450}],37:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getAssumedMasterState=function(e,t){return e.input.metaInstance.findDocumentsById(t.map((t=>(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,{itemId:t,isCheckpoint:"0"}))),!0).then((e=>{var t={};return Object.values(e).forEach((e=>{t[e.itemId]={docData:e.data,metaDocument:e}})),t}))},r.getMetaWriteRow=function(e,t,r,a){var s=t[e.primaryPath],u=r?(0,o.flatCloneDocWithMeta)(r):{id:"",isCheckpoint:"0",itemId:s,data:t,_attachments:{},_deleted:!1,_rev:(0,i.getDefaultRevision)(),_meta:{lwt:0}};return u.data=t,u.isResolvedConflict=a,u._meta.lwt=(0,i.now)(),u.id=(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,u),u._rev=(0,i.createRevision)(e.input.identifier,r),{previous:r,document:u}},r.getRxReplicationMetaInstanceSchema=function(e,t){var r=(0,n.getLengthOfPrimaryKey)(e),o={primaryKey:{key:"id",fields:["itemId","isCheckpoint"],separator:"|"},type:"object",version:0,additionalProperties:!1,properties:{id:{type:"string",minLength:1,maxLength:r+2},isCheckpoint:{type:"string",enum:["0","1"],minLength:1,maxLength:1},itemId:{type:"string",maxLength:r},data:{type:"object",additionalProperties:!0},isResolvedConflict:{type:"string"}},required:["id","isCheckpoint","itemId","data"]};t&&(o.encrypted=["data"]);return(0,n.fillWithDefaultSettings)(o)};var n=e("../rx-schema-helper"),o=e("../rx-storage-helper"),i=e("../plugins/utils")},{"../plugins/utils":12,"../rx-schema-helper":50,"../rx-storage-helper":52}],38:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.startReplicationUpstream=async function(e){if(e.input.initialCheckpoint&&e.input.initialCheckpoint.upstream){await(0,a.getLastCheckpointDoc)(e,"up")||await(0,a.setCheckpoint)(e,"up",e.input.initialCheckpoint.upstream)}var t=e.input.replicationHandler;e.streamQueue.up=e.streamQueue.up.then((()=>d().then((()=>{h()}))));var r=0,l=-1,f=[],p=e.input.forkInstance.changeStream().pipe((0,n.filter)((t=>t.context!==e.downstreamBulkWriteFlag))).subscribe((t=>(e.stats.up.forkChangeStreamEmit=e.stats.up.forkChangeStreamEmit+1,f.push({task:t,time:r++}),e.input.waitBeforePersist?e.input.waitBeforePersist().then((()=>h())):h())));async function d(){if(e.stats.up.upstreamInitialSync=e.stats.up.upstreamInitialSync+1,!e.events.canceled.getValue()){e.checkpointQueue=e.checkpointQueue.then((()=>(0,a.getLastCheckpointDoc)(e,"up")));for(var t=await e.checkpointQueue,n=[];!e.events.canceled.getValue();){l=r++;var s=await e.input.forkInstance.getChangedDocumentsSince(e.input.pushBatchSize,t);if(0===s.documents.length)break;t=(0,o.stackCheckpoints)([t,s.checkpoint]),n.push(m(s.documents,(0,i.ensureNotFalsy)(t)))}(await Promise.all(n)).find((e=>!!e))?await d():e.firstSyncDone.up.getValue()||e.events.canceled.getValue()||e.firstSyncDone.up.next(!0)}}function h(){e.events.canceled.getValue()||0===f.length?e.events.active.up.next(!1):(e.stats.up.processTasks=e.stats.up.processTasks+1,e.events.active.up.next(!0),e.streamQueue.up=e.streamQueue.up.then((()=>{for(var t=[],r={};f.length>0;){var n=(0,i.ensureNotFalsy)(f.shift());n.timee.documentData))),r=(0,o.stackCheckpoints)([r,n.task.checkpoint]))}return(0===t.length?i.PROMISE_RESOLVE_FALSE:m(t,r)).then((()=>{0===f.length?e.events.active.up.next(!1):h()}))})))}(0,n.firstValueFrom)(e.events.canceled.pipe((0,n.filter)((e=>!!e)))).then((()=>p.unsubscribe()));var b=i.PROMISE_RESOLVE_FALSE,v={docs:{}};function m(r,n){return e.stats.up.persistToMaster=e.stats.up.persistToMaster+1,r.forEach((t=>{var r=t[e.primaryPath];v.docs[r]=t})),v.checkpoint=n,b=b.then((async()=>{if(e.events.canceled.getValue())return!1;var r=v.docs;v.docs={};var n=v.checkpoint,o=Object.keys(r);if(0===o.length)return!1;var l=await(0,c.getAssumedMasterState)(e,o),f={},p=[],d={},h={};if(await Promise.all(o.map((async t=>{var n=r[t];h[t]=n;var o=(0,u.writeDocToDocState)(n),a=l[t];a&&a.metaDocument.isResolvedConflict!==n._rev&&(await e.input.conflictHandler({realMasterState:a.docData,newDocumentState:o},"upstream-check-if-equal")).isEqual||a&&a.docData._rev&&(0,i.parseRevision)(n._rev).height===n._meta[e.input.identifier]||(p.push(t),f[t]={assumedMasterState:a?a.docData:void 0,newDocumentState:o},d[t]=(0,c.getMetaWriteRow)(e,o,a?a.metaDocument:void 0))}))),0===p.length)return!1;var b=Object.values(f),m=new Set,y={},g=(0,i.batchArray)(b,e.input.pushBatchSize);await Promise.all(g.map((async r=>{(await t.masterWrite(r)).forEach((t=>{var r=t[e.primaryPath];m.add(r),y[r]=t}))})));var _=[];p.forEach((t=>{m.has(t)||(e.events.processed.up.next(f[t]),_.push(d[t]))})),_.length>0&&await e.input.metaInstance.bulkWrite(_,"replication-up-write-meta");var O=!1;if(m.size>0){e.stats.up.persistToMasterHadConflicts=e.stats.up.persistToMasterHadConflicts+1;var w=[],j={};if(await Promise.all(Object.entries(y).map((([t,r])=>{var n=f[t],o={newDocumentState:n.newDocumentState,assumedMasterState:n.assumedMasterState,realMasterState:r};return(0,s.resolveConflictError)(e,o,h[t]).then((n=>{if(n){e.events.resolvedConflicts.next({input:o,output:n.output}),w.push({previous:h[t],document:n.resolvedDoc});var a=l[t];j[t]=(0,c.getMetaWriteRow)(e,(0,i.ensureNotFalsy)(r),a?a.metaDocument:void 0,n.resolvedDoc._rev)}}))}))),w.length>0){O=!0,e.stats.up.persistToMasterConflictWrites=e.stats.up.persistToMasterConflictWrites+1;var x=await e.input.forkInstance.bulkWrite(w,"replication-up-write-conflict"),S=[];Object.keys(x.success).forEach((e=>{S.push(j[e])})),S.length>0&&await e.input.metaInstance.bulkWrite(S,"replication-up-write-conflict-meta")}}return e.checkpointQueue=e.checkpointQueue.then((()=>(0,a.setCheckpoint)(e,"up",n))),O})).catch((t=>(e.events.error.next(t),!1)))}};var n=e("rxjs"),o=e("../rx-storage-helper"),i=e("../plugins/utils"),a=e("./checkpoint"),s=e("./conflicts"),u=e("./helper"),c=e("./meta-instance")},{"../plugins/utils":12,"../rx-storage-helper":52,"./checkpoint":32,"./conflicts":33,"./helper":35,"./meta-instance":37,rxjs:450}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.flattenEvents=function e(t){var r=[];Array.isArray(t)?t.forEach((t=>{var n=e(t);r=r.concat(n)})):t.id&&t.events?t.events.forEach((e=>r.push(e))):r.push(t);var n=new Set,o=[];return r.forEach((e=>{n.has(e.eventId)||(n.add(e.eventId),o.push(e))})),o},r.getDocumentDataOfRxChangeEvent=function(e){return e.documentData?e.documentData:e.previousDocumentData},r.rxChangeEventToEventReduceChangeEvent=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:n.overwritable.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}};var n=e("./overwritable")},{"./overwritable":9}],40:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createRxCollectionStorageInstance=async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)},r.fillObjectDataBeforeInsert=function(e,t){t=(0,n.flatClone)(t),t=(0,o.fillObjectWithDefaults)(e,t),(t=(0,o.fillPrimaryKey)(e.primaryPath,e.jsonSchema,t))._meta=(0,n.getDefaultRxDocumentMeta)(),t.hasOwnProperty("_deleted")||(t._deleted=!1);t.hasOwnProperty("_attachments")||(t._attachments={});t.hasOwnProperty("_rev")||(t._rev=(0,n.getDefaultRevision)());return t},r.removeCollectionStorages=async function(e,t,r,o,c,l){var f=(await(0,a.getAllCollectionDocuments)(e.statics,t)).filter((e=>e.data.name===c)),p=[];f.forEach((e=>{p.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>p.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var d=new Set;if(p=p.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!d.has(t)&&(d.add(t),!0)})),await Promise.all(p.map((async t=>{var n=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:o,multiInstance:!1,options:{},schema:t.schema,devMode:u.overwritable.isDevMode()});await n.remove(),t.isCollection&&await(0,i.runAsyncPluginHooks)("postRemoveRxCollection",{storage:e,databaseName:o,collectionName:c})}))),l){var h=f.map((e=>{var t=(0,s.flatCloneDocWithMeta)(e);return t._deleted=!0,t._meta.lwt=(0,n.now)(),t._rev=(0,n.createRevision)(r,e),{previous:e,document:t}}));await t.bulkWrite(h,"rx-database-remove-collection-all")}};var n=e("./plugins/utils"),o=e("./rx-schema-helper"),i=e("./hooks"),a=e("./rx-database-internal-store"),s=e("./rx-storage-helper"),u=e("./overwritable")},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-database-internal-store":42,"./rx-schema-helper":50,"./rx-storage-helper":52}],41:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxCollectionBase=void 0,r.createRxCollection=function({database:e,name:t,schema:r,instanceCreationOptions:n={},migrationStrategies:o={},autoMigrate:i=!0,statics:u={},methods:c={},attachments:l={},options:p={},localDocuments:h=!1,cacheReplacementPolicy:b=f.defaultCacheReplacementPolicy,conflictHandler:m=v.defaultConflictHandler}){var y={databaseInstanceToken:e.token,databaseName:e.name,collectionName:t,schema:r.jsonSchema,options:n,multiInstance:e.multiInstance,password:e.password,devMode:g.overwritable.isDevMode()};return(0,d.runPluginHooks)("preCreateRxStorageInstance",y),(0,s.createRxCollectionStorageInstance)(e,y).then((s=>{var f=new j(e,t,r,s,n,o,c,l,p,b,u,m);return f.prepare().then((()=>{Object.entries(u).forEach((([e,t])=>{Object.defineProperty(f,e,{get:()=>t.bind(f)})}));var e=a.PROMISE_RESOLVE_VOID;return i&&0!==f.schema.version&&(e=f.migratePromise()),e})).then((()=>((0,d.runPluginHooks)("createRxCollection",{collection:f,creator:{name:t,schema:r,storageInstance:s,instanceCreationOptions:n,migrationStrategies:o,methods:c,attachments:l,options:p,cacheReplacementPolicy:b,localDocuments:h,statics:u}}),f))).catch((e=>s.close().then((()=>Promise.reject(e)))))}))},r.isRxCollection=function(e){return e instanceof j};var o=n(e("@babel/runtime/helpers/createClass")),i=e("rxjs/operators"),a=e("./plugins/utils"),s=e("./rx-collection-helper"),u=e("./rx-query"),c=e("./rx-error"),l=e("./doc-cache"),f=e("./query-cache"),p=e("./change-event-buffer"),d=e("./hooks"),h=e("./rx-document-prototype-merge"),b=e("./rx-storage-helper"),v=e("./replication-protocol"),m=e("./incremental-write"),y=e("./rx-document"),g=e("./overwritable"),_=["pre","post"],O=["insert","save","remove","create"],w=!1,j=function(){function e(e,t,r,n,o={},i={},s={},u={},c={},l=f.defaultCacheReplacementPolicy,p={},d=v.defaultConflictHandler){this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=(0,f.createQueryCache)(),this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=n,this.instanceCreationOptions=o,this.migrationStrategies=i,this.methods=s,this.attachments=u,this.options=c,this.cacheReplacementPolicy=l,this.statics=p,this.conflictHandler=d,function(e){if(w)return;w=!0;var t=Object.getPrototypeOf(e);O.forEach((e=>{_.map((r=>{var n=r+(0,a.ucfirst)(e);t[n]=function(t,n){return this.addHook(r,e,t,n)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=(0,b.getWrappedStorageInstance)(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new m.IncrementalWriteQueue(this.storageInstance,this.schema.primaryPath,((e,t)=>(0,y.beforeDocumentUpdateWrite)(this,e,t)),(e=>this._runHooks("post","save",e)));var e=this.database.eventBulks$.pipe((0,i.filter)((e=>e.collectionName===this.name)));this.$=e.pipe((0,i.mergeMap)((e=>e.events))),this.checkpoint$=e.pipe((0,i.map)((e=>e.checkpoint))),this._changeEventBuffer=(0,p.createChangeEventBuffer)(this.asRxCollection),this._docCache=new l.DocumentCache(this.schema.primaryPath,this.$.pipe((0,i.filter)((e=>!e.isLocal))),(e=>(0,h.createNewRxDocument)(this.asRxCollection,e)));var t=await this.database.storageToken,r=this.storageInstance.changeStream().subscribe((e=>{var r={id:e.id,internal:!1,collectionName:this.name,storageToken:t,events:e.events.map((e=>(0,b.storageChangeEventToRxChangeEvent)(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context};this.database.$emit(r)}));return this._subs.push(r),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),a.PROMISE_RESOLVE_VOID},t.migrationNeeded=function(){throw(0,a.pluginMissing)("migration")},t.getDataMigrator=function(){throw(0,a.pluginMissing)("migration")},t.migrate=function(e=10){return this.getDataMigrator().migrate(e)},t.migratePromise=function(e=10){return this.getDataMigrator().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return(0,b.throwIfIsStorageWriteError)(this,e[this.schema.primaryPath],e,r),(0,a.ensureNotFalsy)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>(0,s.fillObjectDataBeforeInsert)(this.schema,e))),n=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,o=new Map,i=n.map((e=>(o.set(e[t],e),{document:e}))),a=await this.storageInstance.bulkWrite(i,"rx-collection-bulk-insert"),u=Object.values(a.success).map((e=>this._docCache.getCachedRxDocument(e)));return this.hasHooks("post","insert")&&await Promise.all(u.map((e=>this._runHooks("post","insert",o.get(e.primary),e)))),{success:u,error:Object.values(a.error)}},t.bulkRemove=async function(e){if(0===e.length)return{success:[],error:[]};var t=await this.findByIds(e).exec(),r=[],n=new Map;Array.from(t.values()).forEach((e=>{var t=e.toMutableJSON(!0);r.push(t),n.set(e.primary,t)})),await Promise.all(r.map((e=>{var r=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,t.get(r))})));var o=r.map((e=>{var t=(0,a.flatClone)(e);return t._deleted=!0,{previous:e,document:t}})),i=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),s=Object.keys(i.success);return await Promise.all(s.map((e=>this._runHooks("post","remove",n.get(e),t.get(e))))),{success:s.map((e=>(0,a.getFromMapOrThrow)(t,e))),error:Object.values(i.error)}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var n=(0,s.fillObjectDataBeforeInsert)(this.schema,e),o=n[this.schema.primaryPath];if(!o)throw(0,c.newRxError)("COL3",{primaryPath:this.schema.primaryPath,data:n,schema:this.schema.jsonSchema});r.set(o,n),t.push(n)}));var n=await this.bulkInsert(t),o=n.success.slice(0),i=await Promise.all(n.error.map((async e=>{if(409!==e.status)throw(0,c.newRxError)("VD2",{collection:this.name,writeError:e});var t=e.documentId,n=(0,a.getFromMapOrThrow)(r,t),o=(0,a.ensureNotFalsy)(e.documentInDb),i=this._docCache.getCachedRxDocument(o);return await i.incrementalModify((()=>n))})));return o=o.concat(i)},t.upsert=function(e){return this.bulkUpsert([e]).then((e=>e[0]))},t.incrementalUpsert=function(e){var t=(0,s.fillObjectDataBeforeInsert)(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw(0,c.newRxError)("COL4",{data:e});var n=this._incrementalUpsertQueues.get(r);return n||(n=a.PROMISE_RESOLVE_VOID),n=n.then((()=>function(e,t,r){var n=e._docCache.getLatestDocumentDataIfExists(t);if(n)return Promise.resolve({doc:e._docCache.getCachedRxDocument(n),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,n),n},t.find=function(e){if("string"==typeof e)throw(0,c.newRxError)("COL5",{queryObj:e});return e||(e=(0,u._getDefaultQuery)()),(0,u.createRxQuery)("find",e,this)},t.findOne=function(e){var t;if("string"==typeof e)t=(0,u.createRxQuery)("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e=(0,u._getDefaultQuery)()),e.limit)throw(0,c.newRxError)("QU6");e.limit=1,t=(0,u.createRxQuery)("findOne",e,this)}if("number"==typeof e||Array.isArray(e))throw(0,c.newRxTypeError)("COL6",{queryObj:e});return t},t.count=function(e){return e||(e=(0,u._getDefaultQuery)()),(0,u.createRxQuery)("count",e,this)},t.findByIds=function(e){var t={selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}};return(0,u.createRxQuery)("findByIds",t,this)},t.exportJSON=function(){throw(0,a.pluginMissing)("json-dump")},t.importJSON=function(e){throw(0,a.pluginMissing)("json-dump")},t.insertCRDT=function(e){throw(0,a.pluginMissing)("crdt")},t.addHook=function(e,t,r,n=!1){if("function"!=typeof r)throw(0,c.newRxTypeError)("COL7",{key:t,when:e});if(!_.includes(e))throw(0,c.newRxTypeError)("COL8",{key:t,when:e});if(!O.includes(t))throw(0,c.newRxError)("COL9",{key:t});if("post"===e&&"create"===t&&!0===n)throw(0,c.newRxError)("COL10",{when:e,key:t,parallel:n});var o=r.bind(this),i=n?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(o)},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,n){var o=this.getHooks(e,t);if(!o)return a.PROMISE_RESOLVE_VOID;var i=o.series.map((e=>()=>e(r,n)));return(0,a.promiseSeries)(i).then((()=>Promise.all(o.parallel.map((e=>e(r,n))))))},t._runHooksSync=function(e,t,r,n){var o=this.getHooks(e,t);o&&o.series.forEach((e=>e(r,n)))},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?a.PROMISE_RESOLVE_FALSE:(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],(0,d.runAsyncPluginHooks)("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await(0,s.removeCollectionStorages)(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.hashFunction)},(0,o.default)(e,[{key:"insert$",get:function(){return this.$.pipe((0,i.filter)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,i.filter)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,i.filter)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();r.RxCollectionBase=j},{"./change-event-buffer":2,"./doc-cache":4,"./hooks":6,"./incremental-write":7,"./overwritable":9,"./plugins/utils":12,"./query-cache":30,"./replication-protocol":36,"./rx-collection-helper":40,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-error":46,"./rx-query":49,"./rx-storage-helper":52,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61,"rxjs/operators":675}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.STORAGE_TOKEN_DOCUMENT_KEY=r.STORAGE_TOKEN_DOCUMENT_ID=r.INTERNAL_STORE_SCHEMA_TITLE=r.INTERNAL_STORE_SCHEMA=r.INTERNAL_CONTEXT_STORAGE_TOKEN=r.INTERNAL_CONTEXT_COLLECTION=void 0,r._collectionNamePrimary=h,r.addConnectedStorageToCollection=async function(e,t,r){var o=f(h(e.name,e.schema.jsonSchema),s);for(;;){var u=await(0,i.getSingleDocument)(e.database.internalStore,o),c=(0,a.clone)((0,a.ensureNotFalsy)(u));if(c.data.connectedStorages||(c.data.connectedStorages=[]),c.data.connectedStorages.find((e=>e.collectionName===t&&e.schema.version===r.version)))return;c.data.connectedStorages.push({collectionName:t,schema:r});try{await(0,i.writeSingle)(e.database.internalStore,{previous:(0,a.ensureNotFalsy)(u),document:c},"add-connected-storage-to-collection")}catch(e){if(!(0,n.isBulkWriteConflictError)(e))throw e}}},r.ensureStorageTokenDocumentExists=async function(e){var t=(0,a.randomCouchString)(10),r=e.password?e.hashFunction(JSON.stringify(e.password)):void 0,o={id:d,context:u,key:p,data:{token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}},i=await e.internalStore.bulkWrite([{document:o}],"internal-add-storage-token");if(i.success[d])return i.success[d];var s=(0,a.ensureNotFalsy)(i.error[d]);if(s.isError&&409===s.status){var c=s;if(r&&r!==c.documentInDb.data.passwordHash)throw(0,n.newRxError)("DB1",{passwordHash:r,existingPasswordHash:c.documentInDb.data.passwordHash});var l=c.documentInDb;return(0,a.ensureNotFalsy)(l)}throw s},r.getAllCollectionDocuments=async function(e,t){var r=e.prepareQuery(t.schema,{selector:{context:s},sort:[{id:"asc"}],skip:0});return(await t.query(r)).documents},r.getPrimaryKeyOfInternalDocument=f;var n=e("./rx-error"),o=e("./rx-schema-helper"),i=e("./rx-storage-helper"),a=e("./plugins/utils"),s="collection";r.INTERNAL_CONTEXT_COLLECTION=s;var u="storage-token";r.INTERNAL_CONTEXT_STORAGE_TOKEN=u;var c="RxInternalDocument";r.INTERNAL_STORE_SCHEMA_TITLE=c;var l=(0,o.fillWithDefaultSettings)({version:0,title:c,primaryKey:{key:"id",fields:["context","key"],separator:"|"},type:"object",properties:{id:{type:"string",maxLength:200},key:{type:"string"},context:{type:"string",enum:[s,u,"OTHER"]},data:{type:"object",additionalProperties:!0}},indexes:[],required:["key","context","data"],additionalProperties:!1,sharding:{shards:1,mode:"collection"}});function f(e,t){return(0,o.getComposedPrimaryKeyOfDocumentData)(l,{key:e,context:t})}r.INTERNAL_STORE_SCHEMA=l;var p="storageToken";r.STORAGE_TOKEN_DOCUMENT_KEY=p;var d=f(p,u);function h(e,t){return e+"-"+t.version}r.STORAGE_TOKEN_DOCUMENT_ID=d},{"./plugins/utils":12,"./rx-error":46,"./rx-schema-helper":50,"./rx-storage-helper":52}],43:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxDatabaseBase=void 0,r.createRxDatabase=function({storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:o=!0,eventReduce:i=!1,ignoreDuplicate:u=!1,options:l={},cleanupPolicy:f,allowSlowCount:p=!1,localDocuments:d=!1,hashFunction:h=a.defaultHashSha256}){(0,c.runPluginHooks)("preCreateRxDatabase",{storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:o,eventReduce:i,ignoreDuplicate:u,options:l,localDocuments:d}),u||function(e){if(y.has(e))throw(0,s.newRxError)("DB8",{name:e,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(r);y.add(r);var b=(0,a.randomCouchString)(10);return O(b,e,r,t,o,n).catch((e=>{throw y.delete(r),e})).then((a=>{var s=new _(r,b,e,t,n,o,i,l,a,h,f,p);return(0,c.runAsyncPluginHooks)("createRxDatabase",{database:s,creator:{storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:o,eventReduce:i,ignoreDuplicate:u,options:l,localDocuments:d}}).then((()=>s))}))},r.createRxDatabaseStorageInstance=O,r.dbCount=function(){return g},r.ensureNoStartupErrors=j,r.isRxDatabase=function(e){return e instanceof _},r.isRxDatabaseFirstTimeInstantiated=async function(e){return(await e.storageTokenDocument).data.instanceToken===e.token},r.removeRxDatabase=w;var o=n(e("@babel/runtime/helpers/createClass")),i=e("custom-idle-queue"),a=e("./plugins/utils"),s=e("./rx-error"),u=e("./rx-schema"),c=e("./hooks"),l=e("rxjs"),f=e("rxjs/operators"),p=e("./rx-collection"),d=e("./rx-storage-helper"),h=e("oblivious-set"),b=e("./rx-database-internal-store"),v=e("./rx-collection-helper"),m=e("./overwritable"),y=new Set,g=0,_=function(){function e(e,t,r,n,o,s,u=!1,c={},p,v,m,y){this.idleQueue=new i.IdleQueue,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.eventBulks$=new l.Subject,this.observable$=this.eventBulks$.pipe((0,f.mergeMap)((e=>e.events))),this.storageToken=a.PROMISE_RESOLVE_FALSE,this.storageTokenDocument=a.PROMISE_RESOLVE_FALSE,this.emittedEventBulkIds=new h.ObliviousSet(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=n,this.password=o,this.multiInstance=s,this.eventReduce=u,this.options=c,this.internalStore=p,this.hashFunction=v,this.cleanupPolicy=m,this.allowSlowCount=y,g++,"pseudoInstance"!==this.name&&(this.internalStore=(0,d.getWrappedStorageInstance)(this.asRxDatabase,p,b.INTERNAL_STORE_SCHEMA),this.storageTokenDocument=(0,b.ensureStorageTokenDocumentExists)(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.$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(0,d.getSingleDocument)(this.internalStore,(0,b.getPrimaryKeyOfInternalDocument)((0,b._collectionNamePrimary)(e,t),b.INTERNAL_CONTEXT_COLLECTION));if(!r)throw(0,s.newRxError)("SNH",{name:e,schema:t});var n=(0,d.flatCloneDocWithMeta)(r);n._deleted=!0,await this.internalStore.bulkWrite([{document:n,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},n=[],o={};Object.entries(e).forEach((([e,i])=>{var l=e,f=i.schema;t[l]=f;var p=(0,u.createRxSchema)(f,this.hashFunction);if(r[l]=p,this.collections[e])throw(0,s.newRxError)("DB3",{name:e});var d=(0,b._collectionNamePrimary)(e,f),h={id:(0,b.getPrimaryKeyOfInternalDocument)(d,b.INTERNAL_CONTEXT_COLLECTION),key:d,context:b.INTERNAL_CONTEXT_COLLECTION,data:{name:l,schemaHash:p.hash,schema:p.jsonSchema,version:p.version,connectedStorages:[]},_deleted:!1,_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}};n.push({document:h});var v=Object.assign({},i,{name:l,schema:p,database:this}),m=(0,a.flatClone)(i);m.database=this,m.name=e,(0,c.runPluginHooks)("preCreateRxCollection",m),v.conflictHandler=m.conflictHandler,o[l]=v}));var i=await this.internalStore.bulkWrite(n,"rx-database-add-collection");await j(this),Object.entries(i.error).forEach((([e,n])=>{if(409!==n.status)throw(0,s.newRxError)("DB12",{database:this.name,writeError:n});var o=(0,a.ensureNotFalsy)(n.documentInDb),i=o.data.name,u=r[i];if(o.data.schemaHash!==u.hash)throw(0,s.newRxError)("DB6",{database:this.name,collection:i,previousSchemaHash:o.data.schemaHash,schemaHash:u.hash,previousSchema:o.data.schema,schema:(0,a.ensureNotFalsy)(t[i])})}));var l={};return await Promise.all(Object.keys(e).map((async e=>{var t=o[e],r=await(0,p.createRxCollection)(t);l[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),l},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw(0,a.pluginMissing)("json-dump")},t.importJSON=function(e){throw(0,a.pluginMissing)("json-dump")},t.backup=function(e){throw(0,a.pluginMissing)("backup")},t.leaderElector=function(){throw(0,a.pluginMissing)("leader-election")},t.isLeader=function(){throw(0,a.pluginMissing)("leader-election")},t.waitForLeadership=function(){throw(0,a.pluginMissing)("leader-election")},t.migrationStates=function(){throw(0,a.pluginMissing)("migration")},t.destroy=async function(){return this.destroyed?a.PROMISE_RESOLVE_FALSE:(this.destroyed=!0,await(0,c.runAsyncPluginHooks)("preDestroyRxDatabase",this),this.eventBulks$.complete(),g--,this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?a.PROMISE_RESOLVE_FALSE: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((()=>y.delete(this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>w(this.name,this.storage)))},(0,o.default)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function O(e,t,r,n,o,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:d.INTERNAL_STORAGE_NAME,schema:b.INTERNAL_STORE_SCHEMA,options:n,multiInstance:o,password:i,devMode:m.overwritable.isDevMode()})}async function w(e,t){var r=(0,a.randomCouchString)(10),n=await O(r,t,e,{},!1),o=await(0,b.getAllCollectionDocuments)(t.statics,n),i=new Set;o.forEach((e=>i.add(e.data.name)));var s=Array.from(i);return await Promise.all(s.map((o=>(0,v.removeCollectionStorages)(t,n,r,e,o)))),await(0,c.runAsyncPluginHooks)("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),s}async function j(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}r.RxDatabaseBase=_},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-collection":41,"./rx-collection-helper":40,"./rx-database-internal-store":42,"./rx-error":46,"./rx-schema":51,"./rx-storage-helper":52,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61,"custom-idle-queue":408,"oblivious-set":446,rxjs:450,"rxjs/operators":675}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createNewRxDocument=function(e,t){var r=(0,n.createWithConstructor)(c(e),e,i.overwritable.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),(0,o.runPluginHooks)("postCreateRxDocument",r),r},r.getDocumentOrmPrototype=l,r.getDocumentPrototype=u,r.getRxDocumentConstructor=c;var n=e("./rx-document"),o=e("./hooks"),i=e("./overwritable"),a=e("./plugins/utils"),s=new WeakMap;function u(e){var t=e.schema.getDocumentPrototype(),r=l(e),o=n.basePrototype,i={};return[t,r,o].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(i,t,{get(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(i,t,r))}))})),i}function c(e){return(0,a.getFromMapOrCreate)(s,e,(()=>(0,n.createRxDocumentConstructor)(u(e))))}function l(e){var t={};return Object.entries(e.methods).forEach((([e,r])=>{t[e]=r})),t}},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-document":45}],45:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.basePrototype=void 0,r.beforeDocumentUpdateWrite=h,r.createRxDocumentConstructor=function(e=p){var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t},r.createWithConstructor=function(e,t,r){var n=new e(t,r);return(0,a.runPluginHooks)("createRxDocument",n),n},r.defineGetterSetter=d,r.isRxDocument=function(e){return"object"==typeof e&&null!==e&&"isInstanceOfRxDocument"in e};var n=e("rxjs/operators"),o=e("./plugins/utils"),i=e("./rx-error"),a=e("./hooks"),s=e("./rx-change-event"),u=e("./overwritable"),c=e("./rx-schema-helper"),l=e("./rx-storage-helper"),f=e("./incremental-write"),p={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,n.map)((e=>e._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,n.filter)((e=>!e.isLocal)),(0,n.filter)((e=>e.documentId===this.primary)),(0,n.map)((e=>(0,s.getDocumentDataOfRxChangeEvent)(e))),(0,n.startWith)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,n.distinctUntilChanged)(((e,t)=>e._rev===t._rev)),(0,n.map)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,n.shareReplay)(o.RXJS_SHARE_REPLAY_DEFAULTS))},get$(e){if(u.overwritable.isDevMode()){if(e.includes(".item."))throw(0,i.newRxError)("DOC1",{path:e});if(e===this.primaryPath)throw(0,i.newRxError)("DOC2");if(this.collection.schema.finalFields.includes(e))throw(0,i.newRxError)("DOC3",{path:e});if(!(0,c.getSchemaByObjectPath)(this.collection.schema.jsonSchema,e))throw(0,i.newRxError)("DOC4",{path:e})}return this.$.pipe((0,n.map)((t=>(0,o.getProperty)(t,e))),(0,n.distinctUntilChanged)())},populate(e){var t=(0,c.getSchemaByObjectPath)(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return o.PROMISE_RESOLVE_NULL;if(!t)throw(0,i.newRxError)("DOC5",{path:e});if(!t.ref)throw(0,i.newRxError)("DOC6",{path:e,schemaObj:t});var n=this.collection.database.collections[t.ref];if(!n)throw(0,i.newRxError)("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?n.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):n.findOne(r).exec()},get(e){if(this._data){var t=this._propertyCache.get(e);if(t)return t;var r=(0,o.getProperty)(this._data,e);return"object"!=typeof r||Array.isArray(r)?u.overwritable.deepFreezeWhenDevMode(r):(r=(0,o.clone)(r),d(this.collection.schema,r,e,this),this._propertyCache.set(e,r),r)}},toJSON(e=!1){if(e)return u.overwritable.deepFreezeWhenDevMode(this._data);var t=(0,o.flatClone)(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,u.overwritable.deepFreezeWhenDevMode(t)},toMutableJSON(e=!1){return(0,o.clone)(this.toJSON(e))},update(e){throw(0,o.pluginMissing)("update")},incrementalUpdate(e){throw(0,o.pluginMissing)("update")},updateCRDT(e){throw(0,o.pluginMissing)("crdt")},putAttachment(){throw(0,o.pluginMissing)("attachments")},getAttachment(){throw(0,o.pluginMissing)("attachments")},allAttachments(){throw(0,o.pluginMissing)("attachments")},get allAttachments$(){throw(0,o.pluginMissing)("attachments")},async modify(e,t){var r=this._data,n=await(0,f.modifierFromPublicToInternal)(e)(r);return this._saveData(n,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,(0,f.modifierFromPublicToInternal)(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=(0,o.clone)(t);return Object.entries(e).forEach((([e,t])=>{r[e]=t})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((([e,r])=>{t[e]=r})),t)))},async _saveData(e,t){if(e=(0,o.flatClone)(e),this._data._deleted)throw(0,i.newRxError)("DOC11",{id:this.primary,document:this});await h(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),n=r.error[this.primary];return(0,l.throwIfIsStorageWriteError)(this.collection,this.primary,e,n),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument((0,o.getFromObjectOrThrow)(r.success,this.primary))},remove(){var e=this.collection;if(this.deleted)return Promise.reject((0,i.newRxError)("DOC13",{document:this,id:this.primary}));var t,r=(0,o.flatClone)(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"),n=t.error[this.primary];return(0,l.throwIfIsStorageWriteError)(e,this.primary,r,n),(0,o.getFromObjectOrThrow)(t.success,this.primary)})).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(0,i.newRxError)("DOC14")}};function d(e,t,r="",n=!1){if(null!==t){var i=(0,c.getSchemaByObjectPath)(e.jsonSchema,r);void 0!==i&&(i.properties&&(i=i.properties),Object.keys(i).forEach((e=>{var i=(0,o.trimDots)(r+"."+e);t.__defineGetter__(e,(function(){var e=n||this;if(e.get&&"function"==typeof e.get)return e.get(i)})),Object.defineProperty(t,e+"$",{get:function(){return(n||this).get$(i)},enumerable:!1,configurable:!1}),Object.defineProperty(t,e+"_",{get:function(){return(n||this).populate(i)},enumerable:!1,configurable:!1}),t.__defineSetter__(e,(function(e){return(n||this).set(i,e)}))})))}}function h(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),u.overwritable.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}r.basePrototype=p},{"./hooks":6,"./incremental-write":7,"./overwritable":9,"./plugins/utils":12,"./rx-change-event":39,"./rx-error":46,"./rx-schema-helper":50,"./rx-storage-helper":52,"rxjs/operators":675}],46:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxTypeError=r.RxError=void 0,r.isBulkWriteConflictError=function(e){return!(!e||409!==e.status)&&e},r.newRxError=f,r.newRxTypeError=function(e,t){return new l(e,s.overwritable.tunnelErrorMessage(e),t)},r.rxStorageWriteErrorToRxError=function(e){return f("COL20",{name:p[e.status],document:e.documentId,writeError:e})};var o=n(e("@babel/runtime/helpers/createClass")),i=n(e("@babel/runtime/helpers/inheritsLoose")),a=n(e("@babel/runtime/helpers/wrapNativeSuper")),s=e("./overwritable");function u(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((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(e){}return t+":"+r})).join("\n"),t+="}")}(r)}var c=function(e){function t(t,r,n={}){var o,i=u(r,t,n);return(o=e.call(this,i)||this).code=t,o.message=i,o.parameters=n,o.rxdb=!0,o}return(0,i.default)(t,e),t.prototype.toString=function(){return this.message},(0,o.default)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,a.default)(Error));r.RxError=c;var l=function(e){function t(t,r,n={}){var o,i=u(r,t,n);return(o=e.call(this,i)||this).code=t,o.message=i,o.parameters=n,o.rxdb=!0,o}return(0,i.default)(t,e),t.prototype.toString=function(){return this.message},(0,o.default)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,a.default)(TypeError));function f(e,t){return new c(e,s.overwritable.tunnelErrorMessage(e),t)}r.RxTypeError=l;var p={409:"document write conflict",422:"schema validation error",510:"attachment data missing"}},{"./overwritable":9,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/inheritsLoose":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/wrapNativeSuper":68}],47:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getQueryMatcher=function(e,t){if(!t.sort)throw(0,s.newRxError)("SNH",{query:t});var r=(0,u.getMingoQuery)(t.selector);return e=>!e._deleted&&!!r.find([e]).next()},r.getSortComparator=function(e,t){if(!t.sort)throw(0,s.newRxError)("SNH",{query:t});var r=[];return t.sort.forEach((e=>{var t=Object.keys(e)[0],n=Object.values(e)[0];r.push({key:t,direction:n,getValueFn:(0,i.objectPathMonad)(t)})})),(e,t)=>{for(var n=0;n{"object"==typeof t&&null!==t||(a.selector[e]={$eq:t})}))):a.selector={};if(a.index){var s=(0,i.toArray)(a.index);s.includes(r)||s.push(r),a.index=s}if(a.sort){a.sort.find((e=>(0,i.firstPropertyNameOfObject)(e)===r))||(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 u=new Set;Object.entries(a.selector).forEach((([e,t])=>{("object"!=typeof t||null===t||!!Object.keys(t).find((e=>n.LOGICAL_OPERATORS.has(e))))&&u.add(e)}));var l,f=-1;e.indexes.forEach((e=>{var t=(0,i.isMaybeReadonlyArray)(e)?e:[e],r=t.findIndex((e=>!u.has(e)));r>0&&r>f&&(f=r,l=t)})),l&&(a.sort=l.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a},r.normalizeQueryRegex=c;var n=e("./query-planner"),o=e("./rx-schema-helper"),i=e("./plugins/utils"),a=e("mingo/util"),s=e("./rx-error"),u=e("./rx-query-mingo");function c(e){if("object"!=typeof e||null===e)return e;var t=Object.keys(e),r={};return t.forEach((t=>{var n=e[t];if("$regex"===t&&n instanceof RegExp){var o=(0,i.parseRegex)(n);r.$regex=o.pattern,r.$options=o.flags}else Array.isArray(n)?r[t]=n.map((e=>c(e))):r[t]=c(n)})),r}},{"./plugins/utils":12,"./query-planner":31,"./rx-error":46,"./rx-query-mingo":48,"./rx-schema-helper":50,"mingo/util":445}],48:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getMingoQuery=function(e){S||((0,n.useOperators)(n.OperatorType.PIPELINE,{$sort:a.$sort,$project:i.$project}),(0,n.useOperators)(n.OperatorType.QUERY,{$and:s.$and,$eq:f.$eq,$elemMatch:g.$elemMatch,$exists:_.$exists,$gt:d.$gt,$gte:h.$gte,$in:w.$in,$lt:b.$lt,$lte:v.$lte,$ne:p.$ne,$nin:O.$nin,$mod:y.$mod,$nor:l.$nor,$not:u.$not,$or:c.$or,$regex:m.$regex,$size:j.$size,$type:x.$type}),S=!0);return new o.Query(e)};var n=e("mingo/core"),o=e("mingo/query"),i=e("mingo/operators/pipeline/project"),a=e("mingo/operators/pipeline/sort"),s=e("mingo/operators/query/logical/and"),u=e("mingo/operators/query/logical/not"),c=e("mingo/operators/query/logical/or"),l=e("mingo/operators/query/logical/nor"),f=e("mingo/operators/query/comparison/eq"),p=e("mingo/operators/query/comparison/ne"),d=e("mingo/operators/query/comparison/gt"),h=e("mingo/operators/query/comparison/gte"),b=e("mingo/operators/query/comparison/lt"),v=e("mingo/operators/query/comparison/lte"),m=e("mingo/operators/query/evaluation/regex"),y=e("mingo/operators/query/evaluation/mod"),g=e("mingo/operators/query/array/elemMatch"),_=e("mingo/operators/query/element/exists"),O=e("mingo/operators/query/comparison/nin"),w=e("mingo/operators/query/comparison/in"),j=e("mingo/operators/query/array/size"),x=e("mingo/operators/query/element/type"),S=!1},{"mingo/core":420,"mingo/operators/pipeline/project":424,"mingo/operators/pipeline/sort":425,"mingo/operators/query/array/elemMatch":426,"mingo/operators/query/array/size":427,"mingo/operators/query/comparison/eq":428,"mingo/operators/query/comparison/gt":429,"mingo/operators/query/comparison/gte":430,"mingo/operators/query/comparison/in":431,"mingo/operators/query/comparison/lt":432,"mingo/operators/query/comparison/lte":433,"mingo/operators/query/comparison/ne":434,"mingo/operators/query/comparison/nin":435,"mingo/operators/query/element/exists":436,"mingo/operators/query/element/type":437,"mingo/operators/query/evaluation/mod":438,"mingo/operators/query/evaluation/regex":439,"mingo/operators/query/logical/and":440,"mingo/operators/query/logical/nor":441,"mingo/operators/query/logical/not":442,"mingo/operators/query/logical/or":443,"mingo/query":444}],49:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxQueryBase=void 0,r._getDefaultQuery=b,r.createRxQuery=function(e,t,r,n){(0,c.runPluginHooks)("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:n});var o=new h(e,t,r,n);return o=v(o),(0,f.triggerCacheReplacement)(r),o},r.isFindOneByIdQuery=_,r.isRxQuery=function(e){return e instanceof h},r.queryCollection=g,r.tunnelQueryCache=v;var o=n(e("@babel/runtime/helpers/createClass")),i=e("rxjs"),a=e("rxjs/operators"),s=e("./plugins/utils"),u=e("./rx-error"),c=e("./hooks"),l=e("./event-reduce"),f=e("./query-cache"),p=e("./rx-query-helper"),d=0,h=function(){function e(e,t,r,n={}){this.id=++d,this._execOverDatabaseCount=0,this._creationTime=(0,s.now)(),this._lastEnsureEqual=0,this.uncached=!1,this.refCount$=new i.BehaviorSubject(null),this._result=null,this._latestChangeEvent=-1,this._lastExecStart=0,this._lastExecEnd=0,this._ensureEqualQueue=s.PROMISE_RESOLVE_FALSE,this.op=e,this.mangoQuery=t,this.collection=r,this.other=n,t||(this.mangoQuery={selector:{}}),this.isFindOneByIdQuery=_(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 Map,r=new Map,n=e.map((e=>this.collection._docCache.getCachedRxDocument(e))),o=n.map((e=>(t.set(e.primary,e._data),r.set(e.primary,e),e._data)));this._result={docsData:o,docsMap:r,docsDataMap:t,count:o.length,docs:n,time:(0,s.now)()}}else this._result={docsData:[],docsMap:new Map,docsDataMap:new Map,count:e,docs:[],time:(0,s.now)()}},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,s.now)(),"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(0,u.newRxError)("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,s.ensureNotFalsy)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,n=new Map,o=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);n.set(e,r)}}else o.push(e)})),o.length>0){var i=await this.collection.storageInstance.findDocumentsById(o,!1);Object.values(i).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);n.set(t.primary,t)}))}return n}return g(this).then((e=>(this._lastExecEnd=(0,s.now)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw(0,u.newRxError)("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return y(this).then((()=>(0,i.firstValueFrom)(this.$))).then((t=>{if(!t&&e)throw(0,u.newRxError)("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=(0,s.sortObject)({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e,s.stringifyFilter);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:(0,p.normalizeMangoQuery)(this.collection.schema.jsonSchema,this.mangoQuery)};(0,c.runPluginHooks)("prePrepareQuery",e);var t=this.collection.database.storage.statics.prepareQuery(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(0,s.pluginMissing)("update")},t.where=function(e){throw(0,s.pluginMissing)("query-builder")},t.sort=function(e){throw(0,s.pluginMissing)("query-builder")},t.skip=function(e){throw(0,s.pluginMissing)("query-builder")},t.limit=function(e){throw(0,s.pluginMissing)("query-builder")},(0,o.default)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,a.filter)((e=>!e.isLocal)),(0,a.startWith)(null),(0,a.mergeMap)((()=>y(this))),(0,a.map)((()=>this._result)),(0,a.shareReplay)(s.RXJS_SHARE_REPLAY_DEFAULTS),(0,a.distinctUntilChanged)(((e,t)=>!(!e||e.time!==(0,s.ensureNotFalsy)(t).time))),(0,a.filter)((e=>!!e)),(0,a.map)((e=>{var t=(0,s.ensureNotFalsy)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.docs.length?null:t.docs[0]:"findByIds"===this.op?t.docsMap:t.docs.slice(0)})));this._$=(0,i.merge)(e,this.refCount$.pipe((0,a.filter)((()=>!1))))}return this._$}},{key:"queryMatcher",get:function(){var e=this.collection.schema.jsonSchema,t=(0,p.normalizeMangoQuery)(this.collection.schema.jsonSchema,this.mangoQuery);return(0,s.overwriteGetterForCaching)(this,"queryMatcher",(0,p.getQueryMatcher)(e,t))}},{key:"asRxQuery",get:function(){return this}}]),e}();function b(){return{selector:{}}}function v(e){return e.collection._queryCache.getByQuery(e)}function m(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function y(e){return e.collection.database.destroyed||m(e)?s.PROMISE_RESOLVE_FALSE:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,s.now)(),e.collection.database.destroyed||m(e))return s.PROMISE_RESOLVE_FALSE;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var n=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===n)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var o=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(n);if("count"===e.op){var i=(0,s.ensureNotFalsy)(e._result).count,a=i;o.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),n=e.doesDocumentDataMatch(t.documentData);!r&&n&&a++,r&&!n&&a--})),a!==i&&(t=!0,e._setResultData(a))}else{var u=(0,l.calculateNewResults)(e,o);u.runFullQueryAgain?r=!0:u.changed&&(t=!0,e._setResultData(u.newResults))}}}if(r){var c=e.collection._changeEventBuffer.counter;return e._execOverDatabase().then((r=>(e._latestChangeEvent=c,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&(0,s.areRxDocumentArraysEqual)(e.collection.schema.primaryPath,r,e._result.docsData)||(t=!0,e._setResultData(r)),t))))}return Promise.resolve(t)}(e))),e._ensureEqualQueue)}async function g(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var n=e.isFindOneByIdQuery;n=n.filter((r=>{var n=e.collection._docCache.getLatestDocumentDataIfExists(r);return!n||(t.push(n),!1)}));var o=await r.storageInstance.findDocumentsById(n,!1);Object.values(o).forEach((e=>{t.push(e)}))}else{var i=e.isFindOneByIdQuery,a=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!a)a=(await r.storageInstance.findDocumentsById([i],!1))[i];a&&t.push(a)}else{var s=e.getPreparedQuery(),u=await r.storageInstance.query(s);t=u.documents}return t}function _(e,t){if(!t.skip&&t.selector&&1===Object.keys(t.selector).length&&t.selector[e]){var r=t.selector[e];if("string"==typeof r)return r;if(1===Object.keys(r).length&&"string"==typeof r.$eq)return r.$eq;if(1===Object.keys(r).length&&Array.isArray(r.$eq)&&!r.$eq.find((e=>"string"!=typeof e)))return r.$eq}return!1}r.RxQueryBase=h},{"./event-reduce":5,"./hooks":6,"./plugins/utils":12,"./query-cache":30,"./rx-error":46,"./rx-query-helper":47,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61,rxjs:450,"rxjs/operators":675}],50:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RX_META_SCHEMA=r.DEFAULT_CHECKPOINT_SCHEMA=void 0,r.fillObjectWithDefaults=function(e,t){for(var r=Object.keys(e.defaultValues),n=0;n{var r=(0,o.getProperty)(t,e);if(void 0===r)throw(0,n.newRxError)("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function u(e){var t=a((e=(0,o.flatClone)(e)).primaryKey);e.properties=(0,o.flatClone)(e.properties),e.additionalProperties=!1,e.hasOwnProperty("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=c,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=l(e);return e.required=e.required.concat(r).filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0,e.indexes&&(e.indexes=e.indexes.map((e=>{var r=(0,o.isMaybeReadonlyArray)(e)?e.slice(0):[e];if(!r.includes(t)){var n=r.slice(0);return n.push(t),n}return r}))),e}var c={type:"object",properties:{lwt:{type:"number",minimum:o.RX_META_LWT_MINIMUM,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function l(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=a(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}r.RX_META_SCHEMA=c;r.DEFAULT_CHECKPOINT_SCHEMA={type:"object",properties:{id:{type:"string"},lwt:{type:"number"}},required:["id","lwt"],additionalProperties:!1}},{"./plugins/utils":12,"./rx-error":46}],51:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxSchema=void 0,r.createRxSchema=function(e,t,r=!0){r&&(0,s.runPluginHooks)("preCreateRxSchema",e);var n=(0,c.fillWithDefaultSettings)(e);n=(0,c.normalizeRxJsonSchema)(n),l.overwritable.deepFreezeWhenDevMode(n);var o=new f(n,t);return(0,s.runPluginHooks)("createRxSchema",o),o},r.getIndexes=p,r.getPreviousVersions=function(e){var t=e.version?e.version:0,r=0;return new Array(t).fill(0).map((()=>r++))},r.isRxSchema=function(e){return e instanceof f},r.toTypedRxJsonSchema=function(e){return e};var o=n(e("@babel/runtime/helpers/createClass")),i=e("./plugins/utils"),a=e("./rx-error"),s=e("./hooks"),u=e("./rx-document"),c=e("./rx-schema-helper"),l=e("./overwritable"),f=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=p(this.jsonSchema),this.primaryPath=(0,c.getPrimaryFieldOfPrimaryKey)(this.jsonSchema.primaryKey),this.finalFields=(0,c.getFinalFields)(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!(0,i.deepEqual)(e[r],t[r]))throw(0,a.newRxError)("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={};return(0,u.defineGetterSetter)(this,e,""),(0,i.overwriteGetterForCaching)(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return(0,c.getComposedPrimaryKeyOfDocumentData)(this.jsonSchema,e)},(0,o.default)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((([,e])=>e.hasOwnProperty("default"))).forEach((([t,r])=>e[t]=r.default)),(0,i.overwriteGetterForCaching)(this,"defaultValues",e)}},{key:"hash",get:function(){return(0,i.overwriteGetterForCaching)(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function p(e){return(e.indexes||[]).map((e=>(0,i.isMaybeReadonlyArray)(e)?e:[e]))}r.RxSchema=f},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-document":45,"./rx-error":46,"./rx-schema-helper":50,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61}],52:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME=r.INTERNAL_STORAGE_NAME=void 0,r.attachmentWriteDataToNormalData=c,r.categorizeBulkWriteRows=function(e,t,r,n,i){var u,c=!!e.schema.attachments,p=[],d=[],h={},b=[],v={id:(0,a.randomCouchString)(10),events:[],checkpoint:null,context:i},m=[],y=[],g=[],_=(0,a.now)(),O="function"==typeof r.get;return n.forEach((n=>{var i,w=n.document[t],j=O?r.get(w):r[w];if(j){var x=j._rev;if(!n.previous||n.previous&&x!==n.previous._rev){var S={isError:!0,status:409,documentId:w,writeRow:n,documentInDb:j};return void(h[w]=S)}var E=c?s(n):n;c&&(n.document._deleted?n.previous&&Object.keys(n.previous._attachments).forEach((e=>{y.push({documentId:w,attachmentId:e})})):(Object.entries(n.document._attachments).find((([e,t])=>((n.previous?n.previous._attachments[e]:void 0)||t.data||(i={documentId:w,documentInDb:j,isError:!0,status:510,writeRow:n,attachmentId:e}),!0))),i||Object.entries(n.document._attachments).forEach((([e,t])=>{var r=n.previous?n.previous._attachments[e]:void 0;if(r){var o=E.document._attachments[e].digest;t.data&&r.digest!==o&&g.push({documentId:w,attachmentId:e,attachmentData:t})}else m.push({documentId:w,attachmentId:e,attachmentData:t})})))),i?h[w]=i:(d.push(E),(!u||u.document._meta.lwt{t.data?m.push({documentId:w,attachmentId:e,attachmentData:t}):(i={documentId:w,isError:!0,status:510,writeRow:n,attachmentId:e},h[w]=i)})),i||(c?p.push(s(n)):p.push(n),(!u||u.document._meta.lwt{return u=t,(c=(0,a.flatClone)(u.document))._meta=(0,a.flatClone)(c._meta),n.overwritable.isDevMode()&&(c=(0,i.fillPrimaryKey)(s,r,c),u.previous,u.previous&&Object.keys(u.previous._meta).forEach((e=>{if(!u.document._meta.hasOwnProperty(e))throw(0,o.newRxError)("SNH",{dataBefore:u.previous,dataAfter:u.document})}))),c._meta.lwt=(0,a.now)(),c._rev=(0,a.createRevision)(e.token,u.previous),{document:c,previous:u.previous};var u,c}));return e.lockedRun((()=>t.bulkWrite(l,c))).then((r=>{var n=Object.values(r.error).filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,a.ensureNotFalsy)(e.documentInDb)._deleted)));if(n.length>0){var o={error:(0,a.flatClone)(r.error),success:(0,a.flatClone)(r.success)},i=n.map((t=>(delete o.error[t.documentId],{previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:(0,a.createRevision)(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(i,c))).then((e=>(o.error=Object.assign(o.error,e.error),o.success=Object.assign(o.success,e.success),o)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,n)=>e.lockedRun((()=>t.findDocumentsById(r,n))),getAttachmentData:(r,n)=>e.lockedRun((()=>t.getAttachmentData(r,n))),getChangedDocumentsSince:(r,n)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,a.ensureNotFalsy)(r),n))),cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(u),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(u),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=Object.assign({},e.output.documentData,{_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}}),n=(0,a.flatClone)(r);return delete n._meta,delete n._rev,delete n._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:n}})}};return e.storageInstances.add(u),u},r.hasEncryption=p,r.stackCheckpoints=function(e){return Object.assign({},...e)},r.storageChangeEventToRxChangeEvent=function(e,t,r){var o=t.documentData,i=t.previousDocumentData;return{eventId:t.eventId,documentId:t.documentId,collectionName:r?r.name:void 0,startTime:t.startTime,endTime:t.endTime,isLocal:e,operation:t.operation,documentData:n.overwritable.deepFreezeWhenDevMode(o),previousDocumentData:n.overwritable.deepFreezeWhenDevMode(i)}},r.stripAttachmentsDataFromDocument=l,r.stripAttachmentsDataFromRow=s,r.throwIfIsStorageWriteError=function(e,t,r,n){if(n)throw 409===n.status?(0,o.newRxError)("CONFLICT",{collection:e.name,id:t,writeError:n,data:r}):422===n.status?(0,o.newRxError)("VD2",{collection:e.name,id:t,writeError:n,data:r}):n},r.writeSingle=async function(e,t,r){var n=await e.bulkWrite([t],r);if(Object.keys(n.error).length>0)throw(0,a.firstPropertyValueOfObject)(n.error);return(0,a.firstPropertyValueOfObject)(n.success)};var n=e("./overwritable"),o=e("./rx-error"),i=e("./rx-schema-helper"),a=e("./plugins/utils");r.INTERNAL_STORAGE_NAME="_rxdb_internal";function s(e){return{previous:e.previous,document:l(e.document)}}function u(e){return atob(e).length}function c(e){var t=e.data;return t?{digest:(0,a.defaultHashSha256)(t),length:u(t),type:e.type}:e}function l(e){var t=(0,a.flatClone)(e);return t._attachments={},Object.entries(e._attachments).forEach((([e,r])=>{t._attachments[e]=c(r)})),t}function f(e,t,r){var n=r.document[t],o=[!!r.previous,r.previous&&r.previous._deleted,!!r.document._deleted].map((e=>e?"1":"0")).join("");return e.databaseName+"|"+e.collectionName+"|"+n+"||"+o+"|"+r.document._rev}function p(e){return!!(e.encrypted&&e.encrypted.length>0||e.attachments&&e.attachments.encrypted)}r.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME="rxdatabase_storage_local"},{"./overwritable":9,"./plugins/utils":12,"./rx-error":46,"./rx-schema-helper":50}],53:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.BROADCAST_CHANNEL_BY_TOKEN=void 0,r.addRxStorageMultiInstanceSupport=function(e,t,r,i){if(!t.multiInstance)return;var a=i||s(t.databaseInstanceToken,r.databaseName,r),c=new n.Subject,l=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&c.next(r.eventBulk)};a.addEventListener("message",l);var f=r.changeStream(),p=!1,d=f.subscribe((r=>{p||a.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return c.asObservable().pipe((0,o.mergeWith)(f))};var h=r.close.bind(r);r.close=async function(){return p=!0,d.unsubscribe(),a.removeEventListener("message",l),i||await u(t.databaseInstanceToken,r),h()};var b=r.remove.bind(r);r.remove=async function(){return p=!0,d.unsubscribe(),a.removeEventListener("message",l),i||await u(t.databaseInstanceToken,r),b()}},r.getBroadcastChannelReference=s,r.removeBroadcastChannelReference=u;var n=e("rxjs"),o=e("rxjs/operators"),i=e("broadcast-channel"),a=new Map;function s(e,t,r){var n=a.get(e);return n||(n={bc:new i.BroadcastChannel("RxDB:"+t),refs:new Set},a.set(e,n)),n.refs.add(r),n.bc}function u(e,t){var r=a.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(a.delete(e),r.bc.close()):void 0}r.BROADCAST_CHANNEL_BY_TOKEN=a},{"broadcast-channel":91,rxjs:450,"rxjs/operators":675}],54:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RxStorageDefaultStatics=void 0;var n=e("./rx-error"),o=e("./query-planner"),i={prepareQuery(e,t){if(!t.sort)throw(0,n.newRxError)("SNH",{query:t});return{query:t,queryPlan:(0,o.getQueryPlan)(e,t)}},checkpointSchema:e("./rx-schema-helper").DEFAULT_CHECKPOINT_SCHEMA};r.RxStorageDefaultStatics=i},{"./query-planner":31,"./rx-error":46,"./rx-schema-helper":50}],55:[function(e,t,r){"use strict";e("./noConflict");var n,o=(n=e("core-js/library/fn/global"))&&n.__esModule?n:{default:n};o.default._babelPolyfill&&"undefined"!=typeof console&&console.warn&&console.warn("@babel/polyfill is loaded more than once on this page. This is probably not desirable/intended and may have consequences if different versions of the polyfills are applied sequentially. If you do need to load the polyfill more than once, use @babel/polyfill/noConflict instead to bypass the warning."),o.default._babelPolyfill=!0},{"./noConflict":56,"core-js/library/fn/global":116}],56:[function(e,t,r){"use strict";e("core-js/es6"),e("core-js/fn/array/includes"),e("core-js/fn/array/flat-map"),e("core-js/fn/string/pad-start"),e("core-js/fn/string/pad-end"),e("core-js/fn/string/trim-start"),e("core-js/fn/string/trim-end"),e("core-js/fn/symbol/async-iterator"),e("core-js/fn/object/get-own-property-descriptors"),e("core-js/fn/object/values"),e("core-js/fn/object/entries"),e("core-js/fn/promise/finally"),e("core-js/web"),e("regenerator-runtime/runtime")},{"core-js/es6":104,"core-js/fn/array/flat-map":105,"core-js/fn/array/includes":106,"core-js/fn/object/entries":107,"core-js/fn/object/get-own-property-descriptors":108,"core-js/fn/object/values":109,"core-js/fn/promise/finally":110,"core-js/fn/string/pad-end":111,"core-js/fn/string/pad-start":112,"core-js/fn/string/trim-end":113,"core-js/fn/string/trim-start":114,"core-js/fn/symbol/async-iterator":115,"core-js/web":407,"regenerator-runtime/runtime":449}],57:[function(e,t,r){var n=e("./setPrototypeOf.js"),o=e("./isNativeReflectConstruct.js");function i(e,r,a){return o()?(t.exports=i=Reflect.construct.bind(),t.exports.__esModule=!0,t.exports.default=t.exports):(t.exports=i=function(e,t,r){var o=[null];o.push.apply(o,t);var i=new(Function.bind.apply(e,o));return r&&n(i,r.prototype),i},t.exports.__esModule=!0,t.exports.default=t.exports),i.apply(null,arguments)}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},{"./isNativeReflectConstruct.js":63,"./setPrototypeOf.js":64}],58:[function(e,t,r){var n=e("./toPropertyKey.js");function o(e,t){for(var r=0;r>1)],t)<=0?s=u+1:a=u-1;r(o,t)<=0&&u++;return i.splice(u,0,t),[i,u]}},{}],70:[function(e,t,r){"use strict";r.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},r.toByteArray=function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,f=s>0?a-4:a;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},r.fromByteArray=function(e){for(var t,r=e.length,o=r%3,i=[],a=16383,s=0,u=r-o;su?u:s+a));1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var o,i,a=[],s=t;s>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],71:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AbstractNode=void 0;const n=e("./util"),o=e("./find-similar-node");r.AbstractNode=class{constructor(e,t,r){this.level=e,this.id=(0,n.nextNodeId)(),this.deleted=!1,this.type=r,this.rootNode=t,t&&this.rootNode.addNode(this)}isEqualToOtherNode(e,t=this.toString()){return t===e.toString()}remove(){if(this.ensureNotDeleted("remove"),this.isInternalNode()){if(this.parents.size>0)throw new Error("cannot remove node with parents "+this.id)}if(this.branches){const e=this;e.branches.areBranchesStrictEqual()?e.branches.getBranch("0").parents.remove(e):(e.branches.getBranch("0").parents.remove(e),e.branches.getBranch("1").parents.remove(e))}this.deleted=!0,this.rootNode.removeNode(this)}toJSON(e=!1){const t={id:e?this.id:void 0,deleted:e?this.deleted:void 0,type:this.type,level:this.level};if(e&&this.parents&&(t.parents=this.parents.toString()),this.isLeafNode()&&(t.value=this.asLeafNode().value),this.branches&&!this.branches.deleted){const r=this.branches;t.branches={0:r.getBranch("0").toJSON(e),1:r.getBranch("1").toJSON(e)}}return t}toString(){let e="<"+this.type+":"+this.level;if(this.branches){const t=this.branches;e+="|0:"+t.getBranch("0"),e+="|1:"+t.getBranch("1")}return this.isLeafNode()&&(e+="|v:"+this.asLeafNode().value),e+=">",e}isRootNode(){return"RootNode"===this.type}isInternalNode(){return"InternalNode"===this.type}isLeafNode(){return"LeafNode"===this.type}asRootNode(){if(!this.isRootNode())throw new Error("ouch");return this}asInternalNode(){if(!this.isInternalNode())throw new Error("ouch");return this}asLeafNode(){if(!this.isLeafNode())throw new Error("ouch");return this}ensureNotDeleted(e="unknown"){if(this.deleted)throw new Error("forbidden operation "+e+" on deleted node "+this.id)}log(){console.log(JSON.stringify(this.toJSON(!0),null,2))}applyEliminationRule(e){this.ensureNotDeleted("applyEliminationRule"),e||(e=this.rootNode.getNodesOfLevel(this.level));const t=(0,o.findSimilarNode)(this,e);if(t){const e=this.parents.getAll(),r=[];return e.forEach((e=>{const n=e.branches.getKeyOfNode(this);e.branches.setBranch(n,t),e.branches.areBranchesStrictEqual()&&r.push(e),this.parents.remove(e)})),r.forEach((e=>{e.isInternalNode()&&e.applyReductionRule()})),!0}return!1}}},{"./find-similar-node":76,"./util":89}],72:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ensureNodesNotStrictEqual=r.Branches=void 0;r.Branches=class{constructor(e){this.node=e,this.deleted=!1,this.branches={}}setBranch(e,t){this.branches[e]!==t&&(this.branches[e]=t,t.parents.add(this.node))}getKeyOfNode(e){if(this.getBranch("0")===e)return"0";if(this.getBranch("1")===e)return"1";throw new Error("none matched")}getBranch(e){return this.branches[e]}getBothBranches(){return[this.getBranch("0"),this.getBranch("1")]}hasBranchAsNode(e){return this.getBranch("0")===e||this.getBranch("1")===e}hasNodeIdAsBranch(e){return this.getBranch("0").id===e||this.getBranch("1").id===e}areBranchesStrictEqual(){return this.branches[0]===this.branches[1]}hasEqualBranches(){return JSON.stringify(this.branches[0])===JSON.stringify(this.branches[1])}},r.ensureNodesNotStrictEqual=function(e,t){if(e===t)throw new Error("cannot have two strict equal branches")}},{}],73:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createBddFromTruthTable=void 0;const n=e("./root-node"),o=e("./util"),i=e("./internal-node"),a=e("./leaf-node");r.createBddFromTruthTable=function(e){const t=new n.RootNode,r=e.keys().next().value.length,s=Math.pow(2,r);if(e.size!==s)throw new Error("truth table has missing entries");for(const[r,n]of e){let e=t;for(let n=0;n{const n=e.getNodesOfLevel(t);n.forEach((e=>{o.set(e.id,e)})),r=r.concat(n)}));const i=n(e);if(r.length!==i.size){const e=r.map((e=>e.id)).sort(),t=Array.from(i).map((e=>e.id)).sort().filter((t=>!e.includes(t)));if(i.size>r.length){const e=t[0],n=r.find((t=>!!t.isInternalNode()&&t.branches.hasNodeIdAsBranch(e)));console.log("referenceToFirst:"),null==n||n.log()}throw new Error("ensureCorrectBdd() nodes in list not equal size to recursive nodes allNodes: "+r.length+" recursiveNodes: "+i.size+" nodesOnlyInRecursive: "+t.join(", ")+" ")}if(r.forEach((e=>{if(e.isRootNode())return;const t=e;if(e.deleted)throw new Error("ensureCorrectBdd() bdd includes a deleted node");if(0===t.parents.size)throw new Error("ensureCorrectBdd() node has no parent "+t.id);if(t.isInternalNode()){const e=t,r=e.branches.getBothBranches();if(e.branches.areBranchesStrictEqual())throw new Error("ensureCorrectBdd() node has two equal branches: "+r.map((e=>e.id)).join(", "));r.forEach((t=>{if(!t.parents.has(e))throw new Error("ensureCorrectBdd() branch must have the node as parent")}))}t.parents.getAll().forEach((e=>{if(!e.branches.hasBranchAsNode(t))throw new Error("ensureCorrectBdd() parent node does not have child as branch")}))})),t.includes('"deleted":true'))throw new Error("ensureCorrectBdd() bdd includes a deleted node")},r.getNodesRecursive=n},{}],75:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.fillTruthTable=void 0;const n=e("./util");r.fillTruthTable=function(e,t,r){const o=(0,n.maxBinaryWithLength)(t);let i=(0,n.minBinaryWithLength)(t),a=!1;for(;!a;)e.has(i)||e.set(i,r),i===o?a=!0:i=(0,n.getNextStateSet)(i)}},{"./util":89}],76:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.findSimilarNode=void 0,r.findSimilarNode=function(e,t){const r=e.toString();for(let n=0;n{const r=t.branches.getKeyOfNode(this);t.branches.setBranch(r,e),this.parents.remove(t),t.branches.areBranchesStrictEqual()&&t.isInternalNode()&&t.applyReductionRule()})),!0}return!1}}r.InternalNode=a},{"./abstract-node":71,"./branches":72,"./parents":87}],79:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.LeafNode=void 0;const n=e("./parents"),o=e("./abstract-node"),i=e("./util");class a extends o.AbstractNode{constructor(e,t,r,o){super(e,t,"LeafNode"),this.value=r,this.parents=new n.Parents(this),this.parents.add(o)}removeIfValueEquals(e){if(this.ensureNotDeleted(),this.value!==e)return!1;return this.parents.getAll().forEach((e=>{const t=e.branches.getKeyOfNode(this),r=e.branches.getBranch((0,i.oppositeBoolean)(t));this.parents.remove(e),e.branches.setBranch(t,r),e.isInternalNode()&&e.applyReductionRule()})),!0}}r.LeafNode=a},{"./abstract-node":71,"./parents":87,"./util":89}],80:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.nodeToString=r.bddToMinimalString=void 0;const n=e("./string-format"),o=e("./string-format");function i(e,t,r){const o=(0,n.getNextCharId)(r);switch(e.type){case"LeafNode":const r=(0,n.getCharOfValue)(e.asLeafNode().value);return{id:o.char,nextCode:o.nextCode,str:o.char+r};case"InternalNode":const i=t.get(e.asInternalNode().branches.getBranch("0")),a=t.get(e.asInternalNode().branches.getBranch("1"));return{id:o.char,nextCode:o.nextCode,str:o.char+i+a+(0,n.getCharOfLevel)(e.level)};case"RootNode":const s=t.get(e.asRootNode().branches.getBranch("0")),u=t.get(e.asRootNode().branches.getBranch("1"));return{id:o.char,nextCode:o.nextCode,str:""+s+u+(0,n.getCharOfLevel)(e.level)};default:throw new Error("unknown node type")}}r.bddToMinimalString=function(e){let t="",r=o.FIRST_CHAR_CODE_FOR_ID;const n=e.getLeafNodes().length;if(n>99)throw new Error("cannot build string with too many leaf nodes");t+=n.toString().padStart(2,"0");const a=e.levels.slice().reverse(),s=new Map;return a.forEach((n=>{e.getNodesOfLevel(n).forEach((e=>{const n=i(e,s,r);r=n.nextCode,s.set(e,n.id),t+=n.str}))})),t},r.nodeToString=i},{"./string-format":85}],81:[function(e,t,r){"use strict";function n(e){const t=e.branches.getBranch("0"),r=e.branches.getBranch("1");return{l:e.level,0:t.isLeafNode()?t.asLeafNode().value:n(t),1:r.isLeafNode()?r.asLeafNode().value:n(r)}}Object.defineProperty(r,"__esModule",{value:!0}),r.nodeToSimpleBddNode=r.bddToSimpleBdd=void 0,r.bddToSimpleBdd=function(e){return n(e)},r.nodeToSimpleBddNode=n},{}],82:[function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),o(e("./bdd-to-minimal-string"),r),o(e("./minimal-string-to-simple-bdd"),r),o(e("./resolve-with-simple-bdd"),r),o(e("./string-format"),r),o(e("./bdd-to-simple-bdd"),r)},{"./bdd-to-minimal-string":80,"./bdd-to-simple-bdd":81,"./minimal-string-to-simple-bdd":83,"./resolve-with-simple-bdd":84,"./string-format":85}],83:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.minimalStringToSimpleBdd=void 0;const n=e("../util"),o=e("./string-format");r.minimalStringToSimpleBdd=function(e){const t=new Map,r=2+2*parseInt(e.charAt(0)+e.charAt(1),10),i=e.substring(2,r),a=(0,n.splitStringToChunks)(i,2);for(let e=0;e=128&&e<=160&&(e=161),{char:String.fromCharCode(e),nextCode:e+1}}},{}],86:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getArrayWithIndexes=r.changeKeyOrder=r.shuffleBooleanOrdering=r.optimizeBruteForce=r.defaultCompareResults=void 0;const n=e("./create-bdd-from-truth-table"),o=e("./util");function i(e){const t=s((0,o.firstKeyOfMap)(e).length),r=(0,o.shuffleArray)(t),n={},i={};r.forEach(((e,t)=>{n[t]=e,i[e]=t}));const u=new Map;for(const[t,r]of e.entries()){const e=a(t,n);u.set(e,r)}return{newTable:u,mapping:n,mappingBeforeToAfter:i}}function a(e,t){return e.split("").map(((e,r)=>({char:e,indexBefore:r,indexAfter:t[r]}))).sort(((e,t)=>e.indexAfter-t.indexAfter)).map((e=>e.char)).join("")}function s(e){const t=[];let r=0;for(;rnull),compareResults:s=r.defaultCompareResults,afterBddCreation:u=(()=>null),log:c=!1}){const l=(0,n.createBddFromTruthTable)(e);u(l),l.minimize();let f={truthTable:e,bdd:l};c&&(l.log(),console.log("initial nodes amount: "+l.countNodes()));let p=0;for(;pe!==d)).forEach((e=>{const n=t.mappingBeforeToAfter[e];h.push(n);const o=new Set;l.set(n,o),r.getNodesOfLevel(e).forEach((e=>{e.level=n,o.add(e)}))}));const b=new Set;r.getNodesOfLevel(d).forEach((e=>b.add(e))),l.set(d,b),h.push(d),r.nodesByLevel=l,r.levels=h,u(r),r.minimize(),c&&(console.log("got new bdd with nodes amount of "+r.countNodes()),console.dir(t.mappingBeforeToAfter));const v=await s(f.bdd,r);if("RootNode"!==v.type)throw new Error("compareResults did not return a bdd");v===r&&(c&&(console.log("#".repeat(50)),console.log("found better bdd "+r.countNodes())),f={bdd:r,truthTable:t.newTable},a(f))}return f},r.shuffleBooleanOrdering=i,r.changeKeyOrder=a,r.getArrayWithIndexes=s},{"./create-bdd-from-truth-table":73,"./util":89}],87:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Parents=void 0;r.Parents=class{constructor(e){this.node=e,this.parents=new Set}remove(e){this.parents.delete(e),0===this.parents.size&&this.node.remove()}getAll(){return Array.from(this.parents)}add(e){if(this.node.level===e.level)throw new Error("a node cannot be parent of a node with the same level");this.parents.add(e)}has(e){return this.parents.has(e)}toString(){const e=[];for(const t of this.parents)e.push(t.id);return e.join(", ")}get size(){return this.parents.size}}},{}],88:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RootNode=void 0;const n=e("./abstract-node"),o=e("./branches"),i=e("./util"),a=e("./minimal-string");class s extends n.AbstractNode{constructor(){super(0,null,"RootNode"),this.branches=new o.Branches(this),this.levels=[],this.nodesByLevel=new Map,this.levels.push(0);const e=new Set;e.add(this),this.nodesByLevel.set(0,e)}addNode(e){const t=e.level;this.levels.includes(t)||this.levels.push(t),this.ensureLevelSetExists(t);const r=this.nodesByLevel.get(t);null==r||r.add(e)}removeNode(e){const t=this.nodesByLevel.get(e.level);if(!t.has(e))throw new Error("removed non-existing node "+e.id);t.delete(e)}ensureLevelSetExists(e){this.nodesByLevel.has(e)||this.nodesByLevel.set(e,new Set)}getLevels(){return Array.from(this.levels).sort(((e,t)=>e-t))}getNodesOfLevel(e){this.ensureLevelSetExists(e);const t=this.nodesByLevel.get(e);return Array.from(t)}countNodes(){let e=0;return this.getLevels().forEach((t=>{const r=this.getNodesOfLevel(t).length;e+=r})),e}minimize(e=!1){let t=!1;for(;!t;){e&&console.log("minimize() itterate once");let r=0,n=(0,i.lastOfArray)(this.getLevels());for(;n>0;){const t=this.getNodesOfLevel(n);e&&console.log("minimize() run for level "+n+" with "+t.length+" nodes");let o=0;for(const n of t){if(o++,e&&o%4e3==0&&console.log("minimize() node #"+n.id),n.isLeafNode()){n.asLeafNode().applyEliminationRule()&&r++}if(!n.deleted&&n.isInternalNode()){const e=n,o=e.applyReductionRule();let i=!1;e.deleted||(i=e.applyEliminationRule(t)),(o||i)&&r++}}n--}0===r?t=!0:e&&console.log("minimize() itteration done with "+r+" minimisations")}}getLeafNodes(){const e=(0,i.lastOfArray)(this.getLevels());return this.getNodesOfLevel(e).reverse()}removeIrrelevantLeafNodes(e){let t=!1;for(;!t;){let r=0;const n=this.getLeafNodes();for(const t of n){t.removeIfValueEquals(e)&&r++}this.minimize(),0===r&&(t=!0)}}resolve(e,t){let r=this;for(;;){const n=e[r.level](t),o=(0,i.booleanToBooleanString)(n);if(r=r.branches.getBranch(o),r.isLeafNode())return r.asLeafNode().value}}toSimpleBdd(){return(0,a.bddToSimpleBdd)(this)}}r.RootNode=s},{"./abstract-node":71,"./branches":72,"./minimal-string":82,"./util":89}],89:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.splitStringToChunks=r.lastOfArray=r.shuffleArray=r.firstKeyOfMap=r.getNextStateSet=r.maxBinaryWithLength=r.minBinaryWithLength=r.binaryToDecimal=r.oppositeBinary=r.decimalToPaddedBinary=r.nextNodeId=r.lastChar=r.oppositeBoolean=r.booleanToBooleanString=r.booleanStringToBoolean=void 0,r.booleanStringToBoolean=function(e){return"1"===e},r.booleanToBooleanString=function(e){return e?"1":"0"},r.oppositeBoolean=function(e){return"1"===e?"0":"1"},r.lastChar=function(e){return e.slice(-1)};const n=function(e=6){let t="";const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length;for(let o=0;o>>0).toString(2).padStart(t,"0")}function a(e){return parseInt(e,2)}r.nextNodeId=function(){const e="node_"+n+"_"+o;return o++,e},r.decimalToPaddedBinary=i,r.oppositeBinary=function(e){if("1"===e)return"0";if("0"===e)return"1";throw new Error("non-binary given")},r.binaryToDecimal=a,r.minBinaryWithLength=function(e){return new Array(e).fill(0).map((()=>"0")).join("")},r.maxBinaryWithLength=function(e){return new Array(e).fill(0).map((()=>"1")).join("")},r.getNextStateSet=function(e){return i(a(e)+1,e.length)},r.firstKeyOfMap=function(e){return e.keys().next().value},r.shuffleArray=function(e){for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e},r.lastOfArray=function(e){return e[e.length-1]},r.splitStringToChunks=function(e,t){const r=[];for(let n=0,o=e.length;n0||e._addEL.internal.length>0}function p(e,t,r){e._addEL[t].push(r),function(e){if(!e._iL&&f(e)){var t=function(t){e._addEL[t.type].forEach((function(e){var r=1e5,n=e.time-r;t.time>=n&&e.fn(t.data)}))},r=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,r)})):(e._iL=!0,e.method.onMessage(e._state,t,r))}}(e)}function d(e,t,r){e._addEL[t]=e._addEL[t].filter((function(e){return e!==r})),function(e){if(e._iL&&!f(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}r.BroadcastChannel=c,c._pubkey=!0,c.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(e));return l(this,"message",e)},postInternal:function(e){return l(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};d(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,p(this,"message",t)):this._onML=null},addEventListener:function(e,t){p(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){d(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){a.delete(this),this.closed=!0;var t=this._prepP?this._prepP:n.PROMISE_RESOLVED_VOID;return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}}},{"./method-chooser.js":96,"./options.js":101,"./util.js":102}],91:[function(e,t,r){"use strict";var n=e("./index.js");t.exports={BroadcastChannel:n.BroadcastChannel,createLeaderElection:n.createLeaderElection,clearNodeFolder:n.clearNodeFolder,enforceOptions:n.enforceOptions,beLeader:n.beLeader}},{"./index.js":92}],92:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"BroadcastChannel",{enumerable:!0,get:function(){return n.BroadcastChannel}}),Object.defineProperty(r,"OPEN_BROADCAST_CHANNELS",{enumerable:!0,get:function(){return n.OPEN_BROADCAST_CHANNELS}}),Object.defineProperty(r,"beLeader",{enumerable:!0,get:function(){return i.beLeader}}),Object.defineProperty(r,"clearNodeFolder",{enumerable:!0,get:function(){return n.clearNodeFolder}}),Object.defineProperty(r,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}}),Object.defineProperty(r,"enforceOptions",{enumerable:!0,get:function(){return n.enforceOptions}});var n=e("./broadcast-channel.js"),o=e("./leader-election.js"),i=e("./leader-election-util.js")},{"./broadcast-channel.js":90,"./leader-election-util.js":93,"./leader-election.js":95}],93:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.beLeader=function(e){e.isLeader=!0,e._hasLeader=!0;var t=(0,n.add)((function(){return e.die()}));e._unl.push(t);var r=function(t){"leader"===t.context&&"apply"===t.action&&o(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),o(e,"tell"))};return e.broadcastChannel.addEventListener("internal",r),e._lstns.push(r),o(e,"tell")},r.sendLeaderMessage=o;var n=e("unload");function o(e,t){var r={context:"leader",action:t,token:e.token};return e.broadcastChannel.postInternal(r)}},{unload:677}],94:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.LeaderElectionWebLock=void 0;var n=e("./util.js"),o=e("./leader-election-util.js"),i=function(e,t){var r=this;this.broadcastChannel=e,e._befC.push((function(){return r.die()})),this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,n.randomToken)(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=!1,this._wKMC={},this.lN="pubkey-bc||"+e.method.type+"||"+e.name};r.LeaderElectionWebLock=i,i.prototype={hasLeader:function(){var e=this;return navigator.locks.query().then((function(t){var r=t.held?t.held.filter((function(t){return t.name===e.lN})):[];return!!(r&&r.length>0)}))},awaitLeadership:function(){var e=this;if(!this._wLMP){this._wKMC.c=new AbortController;var t=new Promise((function(t,r){e._wKMC.res=t,e._wKMC.rej=r}));this._wLMP=new Promise((function(r){navigator.locks.request(e.lN,{signal:e._wKMC.c.signal},(function(){return e._wKMC.c=void 0,(0,o.beLeader)(e),r(),t})).catch((function(){}))}))}return this._wLMP},set onduplicate(e){},die:function(){var e=this,t=(0,o.sendLeaderMessage)(this,"death");return this._lstns.forEach((function(t){return e.broadcastChannel.removeEventListener("internal",t)})),this._lstns=[],this._unl.forEach((function(e){return e.remove()})),this._unl=[],this.isLeader&&(this.isLeader=!1),this.isDead=!0,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort("LeaderElectionWebLock.die() called"),t}}},{"./leader-election-util.js":93,"./util.js":102}],95:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e||(e={});e=JSON.parse(JSON.stringify(e)),e.fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var r=(0,n.supportsWebLockAPI)()?new i.LeaderElectionWebLock(e,t):new a(e,t);return e._befC.push((function(){return r.die()})),e._leaderElector=r,r};var n=e("./util.js"),o=e("./leader-election-util.js"),i=e("./leader-election-web-lock.js"),a=function(e,t){var r=this;this.broadcastChannel=e,this._options=t,this.isLeader=!1,this._hasLeader=!1,this.isDead=!1,this.token=(0,n.randomToken)(),this._aplQ=n.PROMISE_RESOLVED_VOID,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=!1;var o=function(e){"leader"===e.context&&("death"===e.action&&(r._hasLeader=!1),"tell"===e.action&&(r._hasLeader=!0))};this.broadcastChannel.addEventListener("internal",o),this._lstns.push(o)};a.prototype={hasLeader:function(){return Promise.resolve(this._hasLeader)},applyOnce:function(e){var t=this;if(this.isLeader)return(0,n.sleep)(0,!0);if(this.isDead)return(0,n.sleep)(0,!1);if(this._aplQC>1)return this._aplQ;return this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then((function(){return function(){if(t.isLeader)return n.PROMISE_RESOLVED_TRUE;var r,i=!1,a=new Promise((function(e){r=function(){i=!0,e()}})),s=function(e){"leader"===e.context&&e.token!=t.token&&("apply"===e.action&&e.token>t.token&&r(),"tell"===e.action&&(r(),t._hasLeader=!0))};t.broadcastChannel.addEventListener("internal",s);var u=e?4*t._options.responseTime:t._options.responseTime;return(0,o.sendLeaderMessage)(t,"apply").then((function(){return Promise.race([(0,n.sleep)(u),a.then((function(){return Promise.reject(new Error)}))])})).then((function(){return(0,o.sendLeaderMessage)(t,"apply")})).then((function(){return Promise.race([(0,n.sleep)(u),a.then((function(){return Promise.reject(new Error)}))])})).catch((function(){})).then((function(){return t.broadcastChannel.removeEventListener("internal",s),!i&&(0,o.beLeader)(t).then((function(){return!0}))}))}()})).then((function(){t._aplQC=t._aplQC-1})),this._aplQ.then((function(){return t.isLeader}))},awaitLeadership:function(){return this._aLP||(this._aLP=function(e){if(e.isLeader)return n.PROMISE_RESOLVED_VOID;return new Promise((function(t){var r=!1;function o(){r||(r=!0,e.broadcastChannel.removeEventListener("internal",i),t(!0))}e.applyOnce().then((function(){e.isLeader&&o()})),function t(){return(0,n.sleep)(e._options.fallbackInterval).then((function(){if(!e.isDead&&!r)return e.isLeader?void o():e.applyOnce(!0).then((function(){e.isLeader?o():t()}))}))}();var i=function(t){"leader"===t.context&&"death"===t.action&&(e._hasLeader=!1,e.applyOnce().then((function(){e.isLeader&&o()})))};e.broadcastChannel.addEventListener("internal",i),e._lstns.push(i)}))}(this)),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;return this._lstns.forEach((function(t){return e.broadcastChannel.removeEventListener("internal",t)})),this._lstns=[],this._unl.forEach((function(e){return e.remove()})),this._unl=[],this.isLeader&&(this._hasLeader=!1,this.isLeader=!1),this.isDead=!0,(0,o.sendLeaderMessage)(this,"death")}}},{"./leader-election-util.js":93,"./leader-election-web-lock.js":94,"./util.js":102}],96:[function(e,t,r){"use strict";e("@babel/runtime/helpers/typeof");Object.defineProperty(r,"__esModule",{value:!0}),r.chooseMethod=function(e){var t=[].concat(e.methods,s).filter(Boolean);if(e.type){if("simulate"===e.type)return a.SimulateMethod;var r=t.find((function(t){return t.type===e.type}));if(r)return r;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||(t=t.filter((function(e){return"idb"!==e.type})));var n=t.find((function(e){return e.canBeUsed()}));if(n)return n;throw new Error("No usable method found in "+JSON.stringify(s.map((function(e){return e.type}))))};var n=e("./methods/native.js"),o=e("./methods/indexed-db.js"),i=e("./methods/localstorage.js"),a=e("./methods/simulate.js");var s=[n.NativeMethod,o.IndexedDBMethod,i.LocalstorageMethod]},{"./methods/indexed-db.js":97,"./methods/localstorage.js":98,"./methods/native.js":99,"./methods/simulate.js":100,"@babel/runtime/helpers/typeof":67}],97:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.TRANSACTION_SETTINGS=r.IndexedDBMethod=void 0,r.averageResponseTime=S,r.canBeUsed=x,r.cleanOldMessages=m,r.close=O,r.commitIndexedDBTransaction=f,r.create=y,r.createDatabase=p,r.getAllMessages=function(e){var t=e.transaction(u,"readonly",c),r=t.objectStore(u),n=[];return new Promise((function(e){r.openCursor().onsuccess=function(r){var o=r.target.result;o?(n.push(o.value),o.continue()):(f(t),e(n))}}))},r.getIdb=l,r.getMessagesHigherThan=h,r.getOldMessages=v,r.microSeconds=void 0,r.onMessage=j,r.postMessage=w,r.removeMessagesById=b,r.type=void 0,r.writeMessage=d;var n=e("../util.js"),o=e("oblivious-set"),i=e("../options.js"),a=n.microSeconds;r.microSeconds=a;var s="pubkey.broadcast-channel-0-",u="messages",c={durability:"relaxed"};r.TRANSACTION_SETTINGS=c;function l(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function f(e){e.commit&&e.commit()}function p(e){var t=l(),r=s+e,n=t.open(r);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise((function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}}))}function d(e,t,r){var n={uuid:t,time:(new Date).getTime(),data:r},o=e.transaction([u],"readwrite",c);return new Promise((function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(n),f(o)}))}function h(e,t){var r=e.transaction(u,"readonly",c),n=r.objectStore(u),o=[],i=IDBKeyRange.bound(t+1,1/0);if(n.getAll){var a=n.getAll(i);return new Promise((function(e,t){a.onerror=function(e){return t(e)},a.onsuccess=function(t){e(t.target.result)}}))}return new Promise((function(e,a){var s=function(){try{return i=IDBKeyRange.bound(t+1,1/0),n.openCursor(i)}catch(e){return n.openCursor()}}();s.onerror=function(e){return a(e)},s.onsuccess=function(n){var i=n.target.result;i?i.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return!(e.uuid===t.uuid||t.eMIs.has(e.id)||e.data.time0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0);t.idb||(t.idb={});t.idb.ttl||(t.idb.ttl=45e3);t.idb.fallbackInterval||(t.idb.fallbackInterval=150);e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose);t.localstorage||(t.localstorage={});t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4);e.methods&&(t.methods=e.methods);t.node||(t.node={});t.node.ttl||(t.node.ttl=12e4);t.node.maxParallelWrites||(t.node.maxParallelWrites=2048);void 0===t.node.useFastPath&&(t.node.useFastPath=!0);return t}},{}],102:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.PROMISE_RESOLVED_VOID=r.PROMISE_RESOLVED_TRUE=r.PROMISE_RESOLVED_FALSE=void 0,r.isPromise=function(e){return e&&"function"==typeof e.then},r.microSeconds=function(){var e=(new Date).getTime();return e===a?1e3*e+ ++s:(a=e,s=0,1e3*e)},r.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},r.randomToken=function(){return Math.random().toString(36).substring(2)},r.sleep=function(e,t){e||(e=0);return new Promise((function(r){return setTimeout((function(){return r(t)}),e)}))},r.supportsWebLockAPI=function(){return"undefined"!=typeof navigator&&void 0!==navigator.locks&&"function"==typeof navigator.locks.request};var n=Promise.resolve(!1);r.PROMISE_RESOLVED_FALSE=n;var o=Promise.resolve(!0);r.PROMISE_RESOLVED_TRUE=o;var i=Promise.resolve();r.PROMISE_RESOLVED_VOID=i;var a=0,s=0},{}],103:[function(e,t,r){(function(t){(function(){ +!function e(t,r,n){function o(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[a]={exports:{}};t[a][0].call(l.exports,(function(e){return o(t[a][1][e]||e)}),l,l.exports,e,t,r,n)}return r[a].exports}for(var i="function"==typeof require&&require,a=0;a!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}();r.ChangeEventBuffer=o},{"rxjs/operators":675}],3:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getIndexMeta=a,r.getIndexStringLength=function(e,t){var r=a(e,t),n=0;return r.forEach((e=>{var t=e.schemaPart,r=t.type;if("string"===r)n+=t.maxLength;else if("boolean"===r)n+=1;else{var o=e.parsedLengths;n=n+o.nonDecimals+o.decimals}})),n},r.getIndexableStringMonad=function(e,t){var r=a(e,t);return function(e){for(var t="",n=0;n{var f=(0,n.getSchemaByObjectPath)(e,t),p=r[l],d=f.type;switch(d){case"string":var h=(0,o.ensureNotFalsy)(f.maxLength);c+="string"==typeof p?p.padEnd(h," "):"".padEnd(h," ");break;case"boolean":if(null===p)c+=a?"0":i.INDEX_MAX;else c+=p?"1":"0";break;case"number":case"integer":var b=s(f);if(null===p||p===i.INDEX_MIN){var v=a?"0":i.INDEX_MAX;c+=v.repeat(b.nonDecimals+b.decimals)}else c+=u(b,p);break;default:throw new Error("unknown index type "+d)}})),c},r.getStartIndexStringFromUpperBound=function(e,t,r,a){var c="";return t.forEach(((t,l)=>{var f=(0,n.getSchemaByObjectPath)(e,t),p=r[l],d=f.type;switch(d){case"string":var h=(0,o.ensureNotFalsy)(f.maxLength);c+="string"==typeof p?p.padEnd(h,a?i.INDEX_MAX:" "):"".padEnd(h,a?i.INDEX_MAX:" ");break;case"boolean":if(null===p)c+=a?"0":"1";else c+=p?"1":"0";break;case"number":case"integer":var b=s(f);if(null===p||p===i.INDEX_MAX)c+=(a?"9":"0").repeat(b.nonDecimals+b.decimals);else c+=u(b,p);break;default:throw new Error("unknown index type "+d)}})),c},r.getStringLengthOfIndexNumber=s;var n=e("./rx-schema-helper"),o=e("./plugins/utils"),i=e("./query-planner");function a(e,t){return t.map((t=>{var r=(0,n.getSchemaByObjectPath)(e,t);if(!r)throw new Error("not in schema: "+t);var i,a=r.type;return"number"!==a&&"integer"!==a||(i=s(r)),{fieldName:t,schemaPart:r,parsedLengths:i,hasComplexPath:t.includes("."),getValueFn:(0,o.objectPathMonad)(t)}}))}function s(e){var t=Math.floor(e.minimum),r=Math.ceil(e.maximum),n=e.multipleOf,o=(r-t).toString().length,i=n.toString().split("."),a=0;return i.length>1&&(a=i[1].length),{minimum:t,maximum:r,nonDecimals:o,decimals:a,roundedMinimum:t}}function u(e,t){void 0===t&&(t=0),te.maximum&&(t=e.maximum);var r="";r+=(Math.floor(t)-e.roundedMinimum).toString().padStart(e.nonDecimals,"0");var n=t.toString().split("."),o=n.length>1?n[1]:"0";return e.decimals>0&&(r+=o.padEnd(e.decimals,"0")),r}},{"./plugins/utils":12,"./query-planner":31,"./rx-schema-helper":50}],4:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.DocumentCache=void 0;var n=e("./plugins/utils"),o=e("./overwritable"),i=e("./rx-change-event"),a=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.documentByRevisionHeight.delete(e.revisionHeight),0===r.documentByRevisionHeight.size&&this.cacheItemByDocId.delete(t))})):void 0,this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var n=(0,i.getDocumentDataOfRxChangeEvent)(e);r.latestDoc=n}}))}var t=e.prototype;return t.getCachedRxDocument=function(e){var t,r=e[this.primaryPath],i=(0,n.getHeightOfRevision)(e._rev),a=(0,n.getFromMapOrCreate)(this.cacheItemByDocId,r,(()=>function(e){return{documentByRevisionHeight:new Map,latestDoc:e}}(e))),u=a.documentByRevisionHeight.get(i),c=u?u.deref():void 0;return c||(e=o.overwritable.deepFreezeWhenDevMode(e),c=this.documentCreator(e),a.documentByRevisionHeight.set(i,(t=c,s?new WeakRef(t):{deref:()=>t})),this.registry&&this.registry.register(c,{docId:r,revisionHeight:i})),c},t.getLatestDocumentData=function(e){return(0,n.getFromMapOrThrow)(this.cacheItemByDocId,e).latestDoc},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.latestDoc},e}();r.DocumentCache=a;var s="function"==typeof WeakRef},{"./overwritable":9,"./plugins/utils":12,"./rx-change-event":39}],5:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RXQUERY_QUERY_PARAMS_CACHE=void 0,r.calculateNewResults=function(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=c(e),a=(0,i.ensureNotFalsy)(e._result).docsData.slice(0),s=(0,i.ensureNotFalsy)(e._result).docsDataMap,u=!1;return t.map((e=>(0,o.rxChangeEventToEventReduceChangeEvent)(e))).filter(i.arrayFilterNotEmpty).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:s},o=(0,n.calculateActionName)(t);return"runFullQueryAgain"===o||("doNothing"!==o?(u=!0,(0,n.runAction)(o,r,e,a,s),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:u,newResults:a}},r.getQueryParams=c,r.getSortFieldsOfQuery=s;var n=e("event-reduce-js"),o=e("./rx-change-event"),i=e("./plugins/utils"),a=e("./rx-query-helper");function s(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var u=new WeakMap;function c(e){return(0,i.getFromMapOrCreate)(u,e,(()=>{var t=e.collection,r=(0,a.normalizeMangoQuery)(t.storageInstance.schema,(0,i.clone)(e.mangoQuery)),n=t.schema.primaryPath,o=(0,a.getSortComparator)(t.schema.jsonSchema,r),u=(0,a.getQueryMatcher)(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:s(n,r),sortComparator:(t,r)=>{var n={docA:t,docB:r,rxQuery:e};return o(n.docA,n.docB)},queryMatcher:t=>u({doc:t,rxQuery:e}.doc)}}))}r.RXQUERY_QUERY_PARAMS_CACHE=u},{"./plugins/utils":12,"./rx-change-event":39,"./rx-query-helper":47,"event-reduce-js":413}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.HOOKS=void 0,r._clearHook=function(e,t){n[e]=n[e].filter((e=>e!==t))},r.runAsyncPluginHooks=function(e,t){return Promise.all(n[e].map((e=>e(t))))},r.runPluginHooks=function(e,t){n[e]&&n[e].forEach((e=>e(t)))};var n={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[]};r.HOOKS=n},{}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.IncrementalWriteQueue=void 0,r.findNewestOfDocumentStates=a,r.modifierFromPublicToInternal=function(e){return async t=>{var r=(0,o.stripMetaDataFromDocument)(t);r._deleted=t._deleted;var n=await e(r),i=Object.assign({},n,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==n._deleted?n._deleted:t._deleted});return void 0===i._deleted&&(i._deleted=!1),i}};var n=e("./rx-error"),o=e("./plugins/utils"),i=function(){function e(e,t,r,n){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=n}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],n=(0,o.getFromMapOrCreate)(this.queueByDocId,r,(()=>[]));return new Promise(((r,i)=>{var a={lastKnownDocumentState:e,modifier:t,resolve:r,reject:i};(0,o.ensureNotFalsy)(n).push(a),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,r])=>{var n=a(r.map((e=>e.lastKnownDocumentState))),i=n;for(var s of r)try{i=await s.modifier((0,o.clone)(i))}catch(e){s.reject(e),s.reject=()=>{},s.resolve=()=>{}}try{await this.preWrite(i,n)}catch(e){return void r.forEach((t=>t.reject(e)))}e.push({previous:n,document:i})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:{},success:{}};return await Promise.all(Array.from(Object.entries(r.success)).map((([e,r])=>{this.postWrite(r),(0,o.getFromMapOrThrow)(t,e).forEach((e=>e.resolve(r)))}))),Array.from(Object.entries(r.error)).forEach((([e,r])=>{var i=(0,o.getFromMapOrThrow)(t,e),a=(0,n.isBulkWriteConflictError)(r);if(a){var s=(0,o.getFromMapOrCreate)(this.queueByDocId,e,(()=>[]));i.reverse().forEach((e=>{e.lastKnownDocumentState=(0,o.ensureNotFalsy)(a.documentInDb),(0,o.ensureNotFalsy)(s).unshift(e)}))}else{var u=(0,n.rxStorageWriteErrorToRxError)(r);i.forEach((e=>e.reject(u)))}})),this.isRunning=!1,this.triggerRun()}},e}();function a(e){var t=e[0],r=(0,o.parseRevision)(t._rev).height;return e.forEach((e=>{var n=(0,o.parseRevision)(e._rev).height;n>r&&(t=e,r=n)})),t}r.IncrementalWriteQueue=i},{"./plugins/utils":12,"./rx-error":46}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={addRxPlugin:!0};Object.defineProperty(r,"addRxPlugin",{enumerable:!0,get:function(){return o.addRxPlugin}});var o=e("./plugin"),i=e("./rx-database");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===i[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return i[e]}}))}));var a=e("./rx-error");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===a[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return a[e]}}))}));var s=e("./rx-database-internal-store");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===s[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return s[e]}}))}));var u=e("./overwritable");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===u[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return u[e]}}))}));var c=e("./rx-collection");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===c[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=e("./rx-collection-helper");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===l[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return l[e]}}))}));var f=e("./rx-document");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===f[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./rx-change-event");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===p[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return p[e]}}))}));var d=e("./rx-document-prototype-merge");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===d[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return d[e]}}))}));var h=e("./rx-query");Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===h[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return h[e]}}))}));var b=e("./rx-query-helper");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===b[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return b[e]}}))}));var v=e("./rx-schema");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===v[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./rx-schema-helper");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===m[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=e("./rx-storage-helper");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===y[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return y[e]}}))}));var g=e("./rx-storage-statics");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===g[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return g[e]}}))}));var _=e("./replication-protocol/index");Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===_[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return _[e]}}))}));var O=e("./rx-storage-multiinstance");Object.keys(O).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===O[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return O[e]}}))}));var w=e("./custom-index");Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===w[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return w[e]}}))}));var j=e("./query-planner");Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===j[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return j[e]}}))}));var x=e("./plugin-helpers");Object.keys(x).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===x[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return x[e]}}))}));var S=e("./plugins/utils");Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===S[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return S[e]}}))}));var E=e("./hooks");Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===E[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return E[e]}}))}));var P=e("./query-cache");Object.keys(P).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===P[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return P[e]}}))}))},{"./custom-index":3,"./hooks":6,"./overwritable":9,"./plugin":11,"./plugin-helpers":10,"./plugins/utils":12,"./query-cache":30,"./query-planner":31,"./replication-protocol/index":36,"./rx-change-event":39,"./rx-collection":41,"./rx-collection-helper":40,"./rx-database":43,"./rx-database-internal-store":42,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-error":46,"./rx-query":49,"./rx-query-helper":47,"./rx-schema":51,"./rx-schema-helper":50,"./rx-storage-helper":52,"./rx-storage-multiinstance":53,"./rx-storage-statics":54}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.overwritable=void 0;var n={isDevMode:()=>!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 "};r.overwritable=n},{}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.wrapRxStorageInstance=function(e,t,r,o=(e=>e)){async function s(e){return e?await t(e):e}async function u(e){return e?await r(e):e}var c=new a.BehaviorSubject(0);return{databaseName:e.databaseName,internals:e.internals,cleanup:e.cleanup.bind(e),options:e.options,close:e.close.bind(e),schema:e.schema,collectionName:e.collectionName,count:e.count.bind(e),remove:e.remove.bind(e),originalStorageInstance:e,bulkWrite:async(t,r)=>{var o=[];await Promise.all(t.map((async e=>{var[t,r]=await Promise.all([e.previous?s(e.previous):void 0,s(e.document)]);o.push({previous:t,document:r})})));var l=await e.bulkWrite(o,r),f={success:{},error:{}},p=[];return Object.entries(l.success).forEach((([e,t])=>{p.push(u(t).then((t=>f.success[e]=t)))})),Object.entries(l.error).forEach((([e,t])=>{p.push(async function(e){var t=(0,i.flatClone)(e);return t.writeRow=(0,i.flatClone)(t.writeRow),t.documentInDb&&(t.documentInDb=await u(t.documentInDb)),t.writeRow.previous&&(t.writeRow.previous=await u(t.writeRow.previous)),t.writeRow.document=await u(t.writeRow.document),t}(t).then((t=>f.error[e]=t)))})),await Promise.all(p),await(0,a.firstValueFrom)(c.pipe((0,n.filter)((e=>0===e)))),f},query:t=>e.query(t).then((e=>Promise.all(e.documents.map((e=>u(e)))))).then((e=>({documents:e}))),getAttachmentData:async(t,r)=>{var n=await e.getAttachmentData(t,r);return n=await o(n)},findDocumentsById:(t,r)=>e.findDocumentsById(t,r).then((async e=>{var t={};return await Promise.all(Object.entries(e).map((async([e,r])=>{t[e]=await u(r)}))),t})),getChangedDocumentsSince:(t,r)=>e.getChangedDocumentsSince(t,r).then((async e=>({checkpoint:e.checkpoint,documents:await Promise.all(e.documents.map((e=>u(e))))}))),changeStream:()=>e.changeStream().pipe((0,n.tap)((()=>c.next(c.getValue()+1))),(0,n.mergeMap)((async e=>{var t=await Promise.all(e.events.map((async e=>{var[t,r]=await Promise.all([u(e.documentData),u(e.previousDocumentData)]);return{operation:e.operation,eventId:e.eventId,documentId:e.documentId,endTime:e.endTime,startTime:e.startTime,documentData:t,previousDocumentData:r,isLocal:!1}})));return{id:e.id,events:t,checkpoint:e.checkpoint,context:e.context}})),(0,n.tap)((()=>c.next(c.getValue()-1)))),conflictResultionTasks:()=>e.conflictResultionTasks().pipe((0,n.mergeMap)((async e=>{var t=await u(e.input.assumedMasterState),r=await u(e.input.newDocumentState),n=await u(e.input.realMasterState);return{id:e.id,context:e.context,input:{assumedMasterState:t,realMasterState:n,newDocumentState:r}}}))),resolveConflictResultionTask:t=>{if(t.output.isEqual)return e.resolveConflictResultionTask(t);var r={id:t.id,output:{isEqual:!1,documentData:t.output.documentData}};return e.resolveConflictResultionTask(r)}}},r.wrappedValidateStorageFactory=function(e,t){var r=(0,i.getFromMapOrCreate)(s,t,(()=>new Map));function n(t){var n=(0,i.defaultHashSha256)(JSON.stringify(t));return(0,i.getFromMapOrCreate)(r,n,(()=>e(t)))}return e=>Object.assign({},e.storage,{async createStorageInstance(t){var r,a=await e.storage.createStorageInstance(t),s=(0,o.getPrimaryFieldOfPrimaryKey)(t.schema.primaryKey);(0,i.requestIdleCallbackIfAvailable)((()=>r=n(t.schema)));var u=a.bulkWrite.bind(a);return a.bulkWrite=(e,o)=>{r||(r=n(t.schema));var i=[],a=[];return e.forEach((e=>{var t=e.document[s],n=r(e.document);n.length>0?i.push({status:422,isError:!0,documentId:t,writeRow:e,validationErrors:n}):a.push(e)})),(a.length>0?u(a,o):Promise.resolve({error:{},success:{}})).then((e=>(i.forEach((t=>{e.error[t.documentId]=t})),e)))},a}})};var n=e("rxjs/operators"),o=e("./rx-schema-helper"),i=e("./plugins/utils"),a=e("rxjs"),s=new Map},{"./plugins/utils":12,"./rx-schema-helper":50,rxjs:450,"rxjs/operators":675}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.addRxPlugin=function(e){if((0,c.runPluginHooks)("preAddRxPlugin",{plugin:e,plugins:p}),p.has(e))return;if(d.has(e.name))throw(0,l.newRxError)("PL3",{name:e.name,plugin:e});p.add(e),d.add(e.name);if(!e.rxdb)throw(0,l.newRxTypeError)("PL1",{plugin:e});e.init&&e.init();e.prototypes&&Object.entries(e.prototypes).forEach((([e,t])=>t(f[e])));e.overwritable&&Object.assign(u.overwritable,e.overwritable);e.hooks&&Object.entries(e.hooks).forEach((([e,t])=>{t.after&&c.HOOKS[e].push(t.after),t.before&&c.HOOKS[e].unshift(t.before)}))};var n=e("./rx-schema"),o=e("./rx-document"),i=e("./rx-query"),a=e("./rx-collection"),s=e("./rx-database"),u=e("./overwritable"),c=e("./hooks"),l=e("./rx-error"),f={RxSchema:n.RxSchema.prototype,RxDocument:o.basePrototype,RxQuery:i.RxQueryBase.prototype,RxCollection:a.RxCollectionBase.prototype,RxDatabase:s.RxDatabaseBase.prototype},p=new Set,d=new Set},{"./hooks":6,"./overwritable":9,"./rx-collection":41,"./rx-database":43,"./rx-document":45,"./rx-error":46,"./rx-query":49,"./rx-schema":51}],12:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./utils-array");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===n[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return n[e]}}))}));var o=e("./utils-blob");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===o[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return o[e]}}))}));var i=e("./utils-base64");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===i[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return i[e]}}))}));var a=e("./utils-revision");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===a[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return a[e]}}))}));var s=e("./utils-document");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===s[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return s[e]}}))}));var u=e("./utils-hash");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===u[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return u[e]}}))}));var c=e("./utils-promise");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===c[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=e("./utils-string");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===l[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return l[e]}}))}));var f=e("./utils-object-deep-equal");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===f[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./utils-object-dot-prop");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===p[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return p[e]}}))}));var d=e("./utils-object");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===d[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return d[e]}}))}));var h=e("./utils-map");Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===h[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return h[e]}}))}));var b=e("./utils-error");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===b[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return b[e]}}))}));var v=e("./utils-time");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===v[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./utils-regex");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===m[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=e("./utils-other");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===y[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return y[e]}}))}));var g=e("./utils-rxdb-version");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in r&&r[e]===g[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return g[e]}}))}))},{"./utils-array":13,"./utils-base64":14,"./utils-blob":15,"./utils-document":16,"./utils-error":17,"./utils-hash":18,"./utils-map":19,"./utils-object":22,"./utils-object-deep-equal":20,"./utils-object-dot-prop":21,"./utils-other":23,"./utils-promise":24,"./utils-regex":25,"./utils-revision":26,"./utils-rxdb-version":27,"./utils-string":28,"./utils-time":29}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.arrayFilterNotEmpty=function(e){if(null==e)return!1;return!0},r.asyncFilter=async function(e,t){var r=await Promise.all(e.map(t));return e.filter(((...[,e])=>r[e]))},r.batchArray=function(e,t){e=e.slice(0);var r=[];for(;e.length;){var n=e.splice(0,t);r.push(n)}return r},r.countUntilNotMatching=function(e,t){var r=0,n=-1;for(var o of e){if(!t(o,n+=1))break;r+=1}return r},r.isMaybeReadonlyArray=function(e){return Array.isArray(e)},r.lastOfArray=function(e){return e[e.length-1]},r.maxOfNumbers=function(e){return Math.max(...e)},r.removeOneFromArrayIfMatches=function(e,t){var r=(e=e.slice()).length,n=!1;for(;r--&&!n;)t(e[r])&&(n=!0,e.splice(r,1));return e},r.shuffleArray=function(e){return e.slice(0).sort((()=>Math.random()-.5))},r.sumNumberArray=function(e){for(var t=0,r=e.length;r--;)t+=e[r];return t},r.toArray=function(e){return Array.isArray(e)?e.slice(0):[e]}},{}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.arrayBufferToBase64=function(e){for(var t="",r=new Uint8Array(e),n=r.byteLength,o=0;oe.arrayBuffer()));return(0,n.arrayBufferToBase64)(t)},r.blobToString=function(e){"[object Uint8Array]"===Object.prototype.toString.call(e)&&(e=new Blob([e]));if("string"==typeof e)return Promise.resolve(e);return e.text()},r.createBlob=function(e,t){return new Blob([e],{type:t})},r.createBlobFromBase64=async function(e,t){var r=await fetch("data:"+t+";base64,"+e);return await r.blob()},r.getBlobSize=function(e){return e.size},r.isBlob=function(e){return!!(e instanceof Blob||void 0!==t&&t.isBuffer(e))};var n=e("./utils-base64")}).call(this)}).call(this,e("buffer").Buffer)},{"./utils-base64":14,buffer:103}],16:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RX_META_LWT_MINIMUM=void 0,r.areRxDocumentArraysEqual=function(e,t,r){if(t.length!==r.length)return!1;var n=0,o=t.length;for(;nt._meta.lwt===r._meta.lwt?r[e]{r+=(0,n.ucfirst)(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 ")};var n=e("./utils-string")},{"./utils-string":28}],18:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defaultHashSha256=function(e){return(0,n.sha256)(e)};var n=e("ohash")},{ohash:447}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getFromMapOrCreate=function(e,t,r,n){var o=e.get(t);void 0===o?(o=r(),e.set(t,o)):n&&n(o);return o}},{}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.deepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,o;if(Array.isArray(t)){if((n=t.length)!==r.length)return!1;for(o=n;0!=o--;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();var i=Object.keys(t);if((n=i.length)!==Object.keys(r).length)return!1;for(o=n;0!=o--;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;0!=o--;){var a=i[o];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r}},{}],21:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.deepKeys=function(e){return[...f(e)]},r.deleteProperty=function(e,t){if(!n(e)||"string"!=typeof t)return!1;for(var r=a(t),o=0;o{var t=typeof e;return null!==e&&("object"===t||"function"===t)},o=new Set(["__proto__","prototype","constructor"]),i=new Set("0123456789");function a(e){var t=[],r="",n="start",a=!1;for(var s of e)switch(s){case"\\":if("index"===n)throw new Error("Invalid character in an index");if("indexEnd"===n)throw new Error("Invalid character after an index");a&&(r+=s),n="property",a=!a;break;case".":if("index"===n)throw new Error("Invalid character in an index");if("indexEnd"===n){n="property";break}if(a){a=!1,r+=s;break}if(o.has(r))return[];t.push(r),r="",n="property";break;case"[":if("index"===n)throw new Error("Invalid character in an index");if("indexEnd"===n){n="index";break}if(a){a=!1,r+=s;break}if("property"===n){if(o.has(r))return[];t.push(r),r=""}n="index";break;case"]":if("index"===n){t.push(Number.parseInt(r,10)),r="",n="indexEnd";break}if("indexEnd"===n)throw new Error("Invalid character after an index");default:if("index"===n&&!i.has(s))throw new Error("Invalid character in an index");if("indexEnd"===n)throw new Error("Invalid character after an index");"start"===n&&(n="property"),a&&(a=!1,r+="\\"),r+=s}switch(a&&(r+="\\"),n){case"property":if(o.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function s(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 u(e,t){if(s(e,t))throw new Error("Cannot use string index")}function c(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[\\.[]/g,"\\$&")}function l(e){return Array.isArray(e)?e.map(((e,t)=>[t,e])):Object.entries(e)}function*f(e,t=[]){if(n(e))for(var[r,o]of l(e))yield*f(o,[...t,r]);else t.length>0&&(yield function(e){var t="";for(var[r,n]of l(e))"number"==typeof n?t+="["+n+"]":(n=c(n),t+=0===r?n:"."+n);return t}(t))}},{}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.clone=void 0,r.deepFreeze=function e(t){return Object.freeze(t),Object.getOwnPropertyNames(t).forEach((function(r){!t.hasOwnProperty(r)||null===t[r]||"object"!=typeof t[r]&&"function"!=typeof t[r]||Object.isFrozen(t[r])||e(t[r])})),t},r.firstPropertyNameOfObject=function(e){return Object.keys(e)[0]},r.firstPropertyValueOfObject=function(e){var t=Object.keys(e)[0];return e[t]},r.flatClone=function(e){return Object.assign({},e)},r.flattenObject=function e(t){var r={};for(var n in t)if(t.hasOwnProperty(n))if("object"==typeof t[n]){var o=e(t[n]);for(var i in o)o.hasOwnProperty(i)&&(r[n+"."+i]=o[i])}else r[n]=t[n];return r},r.getFromObjectOrThrow=function(e,t){var r=e[t];if(!r)throw new Error("missing value from object "+t);return r},r.objectPathMonad=function(e){var t=e.split(".");if(1===t.length)return t=>t[e];return e=>{for(var r=e,n=0;n"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((t=>e(t,r)));if("object"==typeof t&&!Array.isArray(t)){if(t instanceof RegExp)return t;var n={};return Object.keys(t).sort(((e,t)=>e.localeCompare(t))).forEach((o=>{n[o]=e(t[o],r)})),n}return t},r.stringifyFilter=function(e,t){if(t instanceof RegExp)return t.toString();return t};var n=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),n=r.length;n--;)r[n]=e(t[n]);return r}var o={};for(var i in t)o[i]=e(t[i]);return o};r.clone=n},{}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RXJS_SHARE_REPLAY_DEFAULTS=void 0,r.ensureInteger=function(e){if(!Number.isInteger(e))throw new Error("ensureInteger() is falsy");return e},r.ensureNotFalsy=function(e){if(!e)throw new Error("ensureNotFalsy() is falsy");return e},r.getFromMapOrThrow=function(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r},r.runXTimes=function(e,t){new Array(e).fill(0).forEach(((e,r)=>t(r)))};r.RXJS_SHARE_REPLAY_DEFAULTS={bufferSize:1,refCount:!0}},{}],24:[function(e,t,r){"use strict";function n(e=0){return new Promise((t=>setTimeout(t,e)))}Object.defineProperty(r,"__esModule",{value:!0}),r.PROMISE_RESOLVE_VOID=r.PROMISE_RESOLVE_TRUE=r.PROMISE_RESOLVE_NULL=r.PROMISE_RESOLVE_FALSE=void 0,r.nextTick=function(){return new Promise((e=>setTimeout(e,0)))},r.promiseSeries=function(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))},r.promiseWait=n,r.requestIdleCallbackIfAvailable=function(e){"object"==typeof window&&window.requestIdleCallback&&window.requestIdleCallback(e)},r.requestIdlePromise=function(e=null){return"object"==typeof window&&window.requestIdleCallback?new Promise((t=>window.requestIdleCallback(t,{timeout:e}))):n(0)},r.toPromise=function(e){return e&&"function"==typeof e.then?e:Promise.resolve(e)};var o=Promise.resolve(!0);r.PROMISE_RESOLVE_TRUE=o;var i=Promise.resolve(!1);r.PROMISE_RESOLVE_FALSE=i;var a=Promise.resolve(null);r.PROMISE_RESOLVE_NULL=a;var s=Promise.resolve();r.PROMISE_RESOLVE_VOID=s},{}],25:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.REGEX_PARSE_REGEX_EXPRESSION=r.REGEX_ALL_PIPES=r.REGEX_ALL_DOTS=void 0,r.parseRegex=function(e){var t=(0,n.ensureNotFalsy)(e.toString().match(o));return{pattern:t[2],flags:t[3]}};var n=e("./utils-other");r.REGEX_ALL_DOTS=/\./g;r.REGEX_ALL_PIPES=/\|/g;var o=/(\/?)(.+)\1([a-z]*)/i;r.REGEX_PARSE_REGEX_EXPRESSION=o},{"./utils-other":23}],26:[function(e,t,r){"use strict";function n(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}Object.defineProperty(r,"__esModule",{value:!0}),r.createRevision=function(e,t){var r=t?t._rev:null;return(r?n(r).height:0)+1+"-"+e},r.getHeightOfRevision=function(e){return parseInt(e.split("-")[0],10)},r.parseRevision=n},{}],27:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RXDB_VERSION=void 0;r.RXDB_VERSION="14.6.0"},{}],28:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RANDOM_STRING=void 0,r.arrayBufferToString=function(e){return String.fromCharCode.apply(null,new Uint16Array(e))},r.isFolderPath=function(e){return!(!e.includes("/")&&!e.includes("\\"))},r.randomCouchString=function(e=10){for(var t="",r="abcdefghijklmnopqrstuvwxyz",n=0;n(0,n.requestIdlePromise)(200))).then((()=>{e.destroyed||e.cacheReplacementPolicy(e,e._queryCache),c.delete(e)}))},r.uncacheRxQuery=i;var n=e("./plugins/utils"),o=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return(0,n.getFromMapOrCreate)(this._map,t,(()=>e))},e}();function i(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function a(e){return e.refCount$.observers.length}r.QueryCache=o;r.DEFAULT_TRY_TO_KEEP_MAX=100;r.DEFAULT_UNEXECUTED_LIFETIME=3e4;var s=(e,t)=>(r,o)=>{if(!(o._map.size0||(0===l._lastEnsureEqual&&l._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,f).forEach((e=>i(o,e)))}};r.defaultCacheReplacementPolicyMonad=s;var u=s(100,3e4);r.defaultCacheReplacementPolicy=u;var c=new WeakSet;r.COLLECTIONS_WITH_RUNNING_CLEANUP=c},{"./plugins/utils":12}],31:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UPPER_BOUND_LOGICAL_OPERATORS=r.LOWER_BOUND_LOGICAL_OPERATORS=r.LOGICAL_OPERATORS=r.INDEX_MIN=r.INDEX_MAX=void 0,r.getMatcherQueryOpts=f,r.getQueryPlan=function(e,t){var r=(0,o.getPrimaryFieldOfPrimaryKey)(e.primaryKey),n=t.selector,u=e.indexes?e.indexes.slice(0):[];t.index?u=[t.index]:u.push([r]);var c,d=t.sort.map((e=>Object.keys(e)[0])).join(","),h=!!t.sort.find((e=>"desc"===Object.values(e)[0])),b=-1;u.forEach((r=>{var o=!0,u=!0,v=r.map((e=>{var t=n[e],r=t?Object.keys(t):[],c={};t&&r.length?r.forEach((e=>{if(s.has(e)){var r=f(e,t[e]);c=Object.assign(c,r)}})):c={startKey:u?a:i,endKey:o?i:a,inclusiveStart:!0,inclusiveEnd:!0};return void 0===c.startKey&&(c.startKey=a),void 0===c.endKey&&(c.endKey=i),void 0===c.inclusiveStart&&(c.inclusiveStart=!0),void 0===c.inclusiveEnd&&(c.inclusiveEnd=!0),u&&!c.inclusiveStart&&(u=!1),o&&!c.inclusiveEnd&&(o=!1),c})),m={index:r,startKeys:v.map((e=>e.startKey)),endKeys:v.map((e=>e.endKey)),inclusiveEnd:o,inclusiveStart:u,sortFieldsSameAsIndexFields:!h&&d===r.join(","),selectorSatisfiedByIndex:l(r,t.selector)},y=p(e,t,m);(y>0&&y>b||t.index)&&(b=y,c=m)})),c||(c={index:[r],startKeys:[a],endKeys:[i],inclusiveEnd:!0,inclusiveStart:!0,sortFieldsSameAsIndexFields:!h&&d===r,selectorSatisfiedByIndex:l([r],t.selector)});return c},r.isSelectorSatisfiedByIndex=l,r.rateQueryPlan=p;var n=e("./plugins/utils"),o=e("./rx-schema-helper"),i=String.fromCharCode(65535);r.INDEX_MAX=i;var a=Number.MIN_VALUE;r.INDEX_MIN=a;var s=new Set(["$eq","$gt","$gte","$lt","$lte"]);r.LOGICAL_OPERATORS=s;var u=new Set(["$eq","$gt","$gte"]);r.LOWER_BOUND_LOGICAL_OPERATORS=u;var c=new Set(["$eq","$lt","$lte"]);function l(e,t){var r,n;return!Object.entries(t).find((([t,r])=>!e.includes(t)||Object.entries(r).find((([e,t])=>!s.has(e)))))&&(!e.find((e=>{var n=t[e];if(!n)return!1;var o=Object.keys(n).find((e=>u.has(e)));return!(!r||!o)||("$eq"!==o&&(r=o),!1)}))&&!e.find((e=>{var r=t[e];if(!r)return!1;var o=Object.keys(r).find((e=>c.has(e)));return!(!n||!o)||("$eq"!==o&&(n=o),!1)})))}function f(e,t){switch(e){case"$eq":return{startKey:t,endKey:t};case"$lte":return{endKey:t};case"$gte":return{startKey:t};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}function p(e,t,r){var o=0,s=e=>{e>0&&(o+=e)};return s(10*(0,n.countUntilNotMatching)(r.startKeys,(e=>e!==a&&e!==i))),s(10*(0,n.countUntilNotMatching)(r.startKeys,(e=>e!==i&&e!==a))),s(10*(0,n.countUntilNotMatching)(r.startKeys,((e,t)=>e===r.endKeys[t]))*1.5),s(r.sortFieldsSameAsIndexFields?5:0),o}r.UPPER_BOUND_LOGICAL_OPERATORS=c},{"./plugins/utils":12,"./rx-schema-helper":50}],32:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getCheckpointKey=function(e){return"rx-storage-replication-"+e.hashFunction([e.identifier,e.forkInstance.databaseName,e.forkInstance.collectionName].join("||"))},r.getLastCheckpointDoc=async function(e,t){var r=(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,{isCheckpoint:"1",itemId:t}),o=(await e.input.metaInstance.findDocumentsById([r],!1))[r];return e.lastCheckpointDoc[t]=o,o?o.data:void 0},r.setCheckpoint=async function(e,t,r){var a=e.lastCheckpointDoc[t];if(r&&!e.events.canceled.getValue()&&(!a||JSON.stringify(a.data)!==JSON.stringify(r))){var s={id:"",isCheckpoint:"1",itemId:t,_deleted:!1,_attachments:{},data:r,_meta:(0,i.getDefaultRxDocumentMeta)(),_rev:(0,i.getDefaultRevision)()};for(s.id=(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,s);;){a&&(s.data=(0,o.stackCheckpoints)([a.data,s.data])),s._meta.lwt=(0,i.now)(),s._rev=(0,i.createRevision)(e.input.identifier,a);var u=await e.input.metaInstance.bulkWrite([{previous:a,document:s}],"replication-set-checkpoint");if(u.success[s.id])return void(e.lastCheckpointDoc[t]=(0,i.getFromObjectOrThrow)(u.success,s.id));var c=(0,i.getFromObjectOrThrow)(u.error,s.id);if(409!==c.status)throw c;a=(0,i.ensureNotFalsy)(c.documentInDb),s._rev=(0,i.createRevision)(e.input.identifier,a)}}};var n=e("../rx-schema-helper"),o=e("../rx-storage-helper"),i=e("../plugins/utils")},{"../plugins/utils":12,"../rx-schema-helper":50,"../rx-storage-helper":52}],33:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defaultConflictHandler=void 0,r.resolveConflictError=async function(e,t,r){var o=e.input.conflictHandler,i=await o(t,"replication-resolve-conflict");if(i.isEqual)return;var a=Object.assign({},i.documentData,{_meta:(0,n.flatClone)(r._meta),_rev:(0,n.getDefaultRevision)(),_attachments:(0,n.flatClone)(r._attachments)});return a._meta.lwt=(0,n.now)(),a._rev=(0,n.createRevision)(e.input.identifier,r),{resolvedDoc:a,output:i}};var n=e("../plugins/utils");r.defaultConflictHandler=function(e,t){return(0,n.deepEqual)(e.newDocumentState,e.realMasterState)?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})}},{"../plugins/utils":12}],34:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.startReplicationDownstream=async function(e){if(e.input.initialCheckpoint&&e.input.initialCheckpoint.downstream){await(0,s.getLastCheckpointDoc)(e,"down")||await(0,s.setCheckpoint)(e,"down",e.input.initialCheckpoint.downstream)}var t=e.input.hashFunction(e.input.identifier),r=e.input.replicationHandler,l=0,f=[];function p(t){e.stats.down.addNewTask=e.stats.down.addNewTask+1;var n={time:l++,task:t};f.push(n),e.streamQueue.down=e.streamQueue.down.then((()=>{for(var t=[];f.length>0;){e.events.active.down.next(!0);var n=(0,a.ensureNotFalsy)(f.shift());if(!(n.time(0,s.getLastCheckpointDoc)(e,"down")));var t=await e.checkpointQueue,n=[];for(;!e.events.canceled.getValue();){h=l++;var o=await r.masterChangesSince(t,e.input.pullBatchSize);if(0===o.documents.length)break;if(t=(0,i.stackCheckpoints)([t,o.checkpoint]),n.push(m(o.documents,t)),o.documents.length{if("RESYNC"===e)throw new Error("SNH");r=r.concat(e.documents),n=(0,i.stackCheckpoints)([n,e.checkpoint])})),m(r,(0,a.ensureNotFalsy)(n))}(t)})).then((()=>{e.events.active.down.next(!1),e.firstSyncDone.down.getValue()||e.events.canceled.getValue()||e.firstSyncDone.down.next(!0)}))}p("RESYNC");var d=r.masterChangeStream$.subscribe((t=>{e.stats.down.masterChangeStreamEmit=e.stats.down.masterChangeStreamEmit+1,p(t)}));(0,n.firstValueFrom)(e.events.canceled.pipe((0,n.filter)((e=>!!e)))).then((()=>d.unsubscribe()));var h=-1;var b=a.PROMISE_RESOLVE_VOID,v={docs:{}};function m(r,n){return e.stats.down.persistFromMaster=e.stats.down.persistFromMaster+1,r.forEach((t=>{var r=t[e.primaryPath];v.docs[r]=t})),v.checkpoint=n,b=b.then((()=>{var r=v.docs;v.docs={};var n=v.checkpoint,i=Object.keys(r);if(e.events.canceled.getValue()||0===i.length)return a.PROMISE_RESOLVE_VOID;var l=[],f={},p={},d=[];return Promise.all([e.input.forkInstance.findDocumentsById(i,!0),(0,c.getAssumedMasterState)(e,i)]).then((([n,o])=>Promise.all(i.map((async i=>{var s=n[i],h=s?(0,u.writeDocToDocState)(s):void 0,b=r[i],v=o[i];if(v&&v.metaDocument.isResolvedConflict===s._rev)return a.PROMISE_RESOLVE_VOID;var m=v&&h?e.input.conflictHandler({realMasterState:v.docData,newDocumentState:h},"downstream-check-if-equal-0").then((e=>e.isEqual)):a.PROMISE_RESOLVE_FALSE,y=await m;if(!y&&v&&v.docData._rev&&s._meta[e.input.identifier]&&(0,a.parseRevision)(s._rev).height===s._meta[e.input.identifier]&&(y=!0),s&&v&&!1===y||s&&!v)return a.PROMISE_RESOLVE_VOID;var g=h?e.input.conflictHandler({realMasterState:b,newDocumentState:h},"downstream-check-if-equal-1").then((e=>e.isEqual)):a.PROMISE_RESOLVE_FALSE,_=await g;if(h&&_)return v&&!1!==y||d.push((0,c.getMetaWriteRow)(e,h,v?v.metaDocument:void 0)),a.PROMISE_RESOLVE_VOID;var O=Object.assign({},b,s?{_meta:(0,a.flatClone)(s._meta),_attachments:{},_rev:(0,a.getDefaultRevision)()}:{_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}});if(b._rev){var w=s?(0,a.parseRevision)(s._rev).height+1:1;O._meta[e.input.identifier]=w}var j={previous:s,document:O};j.document._rev=(0,a.createRevision)(t,j.previous),l.push(j),f[i]=j,p[i]=(0,c.getMetaWriteRow)(e,b,v?v.metaDocument:void 0)}))))).then((()=>{if(l.length>0)return e.input.forkInstance.bulkWrite(l,e.downstreamBulkWriteFlag).then((t=>{Object.keys(t.success).forEach((t=>{e.events.processed.down.next(f[t]),d.push(p[t])})),Object.values(t.error).forEach((t=>{409!==t.status&&e.events.error.next((0,o.newRxError)("RC_PULL",{writeError:t}))}))}))})).then((()=>{if(d.length>0)return e.input.metaInstance.bulkWrite(d,"replication-down-write-meta").then((t=>{Object.entries(t.error).forEach((([t,r])=>{e.events.error.next((0,o.newRxError)("RC_PULL",{id:t,writeError:r}))}))}))})).then((()=>{e.checkpointQueue=e.checkpointQueue.then((()=>(0,s.setCheckpoint)(e,"down",n)))}))})).catch((t=>e.events.error.next(t)))}};var n=e("rxjs"),o=e("../rx-error"),i=e("../rx-storage-helper"),a=e("../plugins/utils"),s=e("./checkpoint"),u=e("./helper"),c=e("./meta-instance")},{"../plugins/utils":12,"../rx-error":46,"../rx-storage-helper":52,"./checkpoint":32,"./helper":35,"./meta-instance":37,rxjs:450}],35:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.docStateToWriteDoc=function(e,t,r){var o=Object.assign({},t,{_attachments:{},_meta:{lwt:(0,n.now)()},_rev:(0,n.getDefaultRevision)()});return o._rev=(0,n.createRevision)(e,r),o},r.writeDocToDocState=function(e){var t=(0,n.flatClone)(e);return delete t._attachments,delete t._meta,delete t._rev,t};var n=e("../plugins/utils")},{"../plugins/utils":12}],36:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n={replicateRxStorageInstance:!0,awaitRxStorageReplicationFirstInSync:!0,awaitRxStorageReplicationInSync:!0,awaitRxStorageReplicationIdle:!0,rxStorageInstanceToReplicationHandler:!0,cancelRxStorageReplication:!0};r.awaitRxStorageReplicationFirstInSync=d,r.awaitRxStorageReplicationIdle=async function(e){await d(e);for(;;){var{down:t,up:r}=e.streamQueue;if(await Promise.all([r,t]),t===e.streamQueue.down&&r===e.streamQueue.up)return}},r.awaitRxStorageReplicationInSync=function(e){return Promise.all([e.streamQueue.up,e.streamQueue.down,e.checkpointQueue])},r.cancelRxStorageReplication=function(e){e.events.canceled.next(!0),e.events.active.up.complete(),e.events.active.down.complete(),e.events.processed.up.complete(),e.events.processed.down.complete(),e.events.resolvedConflicts.complete(),e.events.canceled.complete()},r.replicateRxStorageInstance=function(e){var t=(0,s.getCheckpointKey)(e),r={primaryPath:(0,i.getPrimaryFieldOfPrimaryKey)(e.forkInstance.schema.primaryKey),input:e,checkpointKey:t,downstreamBulkWriteFlag:"replication-downstream-"+t,events:{canceled:new o.BehaviorSubject(!1),active:{down:new o.BehaviorSubject(!0),up:new o.BehaviorSubject(!0)},processed:{down:new o.Subject,up:new o.Subject},resolvedConflicts:new o.Subject,error:new o.Subject},stats:{down:{addNewTask:0,downstreamProcessChanges:0,downstreamResyncOnce:0,masterChangeStreamEmit:0,persistFromMaster:0},up:{forkChangeStreamEmit:0,persistToMaster:0,persistToMasterConflictWrites:0,persistToMasterHadConflicts:0,processTasks:0,upstreamInitialSync:0}},firstSyncDone:{down:new o.BehaviorSubject(!1),up:new o.BehaviorSubject(!1)},streamQueue:{down:a.PROMISE_RESOLVE_VOID,up:a.PROMISE_RESOLVE_VOID},checkpointQueue:a.PROMISE_RESOLVE_VOID,lastCheckpointDoc:{}};return(0,u.startReplicationDownstream)(r),(0,l.startReplicationUpstream)(r),r},r.rxStorageInstanceToReplicationHandler=function(e,t,r){var n=(0,i.getPrimaryFieldOfPrimaryKey)(e.schema.primaryKey);return{masterChangeStream$:e.changeStream().pipe((0,o.map)((e=>({checkpoint:e.checkpoint,documents:e.events.map((e=>(0,c.writeDocToDocState)((0,a.ensureNotFalsy)(e.documentData))))})))),masterChangesSince:(t,r)=>e.getChangedDocumentsSince(r,t).then((e=>({checkpoint:e.documents.length>0?e.checkpoint:t,documents:e.documents.map((e=>(0,c.writeDocToDocState)(e)))}))),async masterWrite(o){var i={};o.forEach((e=>{var t=e.newDocumentState[n];i[t]=e}));var s=Object.keys(i),u=await e.findDocumentsById(s,!0),l=[],f=[];if(await Promise.all(Object.entries(i).map((async([e,n])=>{var o=u[e];o?o&&!n.assumedMasterState?l.push((0,c.writeDocToDocState)(o)):!0===(await t({realMasterState:(0,c.writeDocToDocState)(o),newDocumentState:(0,a.ensureNotFalsy)(n.assumedMasterState)},"rxStorageInstanceToReplicationHandler-masterWrite")).isEqual?f.push({previous:o,document:(0,c.docStateToWriteDoc)(r,n.newDocumentState,o)}):l.push((0,c.writeDocToDocState)(o)):f.push({document:(0,c.docStateToWriteDoc)(r,n.newDocumentState)})}))),f.length>0){var p=await e.bulkWrite(f,"replication-master-write");Object.values(p.error).forEach((e=>{if(409!==e.status)throw new Error("non conflict error");l.push((0,c.writeDocToDocState)((0,a.ensureNotFalsy)(e.documentInDb)))}))}return l}}};var o=e("rxjs"),i=e("../rx-schema-helper"),a=e("../plugins/utils"),s=e("./checkpoint");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===s[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return s[e]}}))}));var u=e("./downstream");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===u[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return u[e]}}))}));var c=e("./helper");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===c[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=e("./upstream");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===l[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return l[e]}}))}));var f=e("./meta-instance");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===f[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./conflicts");function d(e){return(0,o.firstValueFrom)((0,o.combineLatest)([e.firstSyncDone.down.pipe((0,o.filter)((e=>!!e))),e.firstSyncDone.up.pipe((0,o.filter)((e=>!!e)))])).then((()=>{}))}Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in r&&r[e]===p[e]||Object.defineProperty(r,e,{enumerable:!0,get:function(){return p[e]}}))}))},{"../plugins/utils":12,"../rx-schema-helper":50,"./checkpoint":32,"./conflicts":33,"./downstream":34,"./helper":35,"./meta-instance":37,"./upstream":38,rxjs:450}],37:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getAssumedMasterState=function(e,t){return e.input.metaInstance.findDocumentsById(t.map((t=>(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,{itemId:t,isCheckpoint:"0"}))),!0).then((e=>{var t={};return Object.values(e).forEach((e=>{t[e.itemId]={docData:e.data,metaDocument:e}})),t}))},r.getMetaWriteRow=function(e,t,r,a){var s=t[e.primaryPath],u=r?(0,o.flatCloneDocWithMeta)(r):{id:"",isCheckpoint:"0",itemId:s,data:t,_attachments:{},_deleted:!1,_rev:(0,i.getDefaultRevision)(),_meta:{lwt:0}};return u.data=t,u.isResolvedConflict=a,u._meta.lwt=(0,i.now)(),u.id=(0,n.getComposedPrimaryKeyOfDocumentData)(e.input.metaInstance.schema,u),u._rev=(0,i.createRevision)(e.input.identifier,r),{previous:r,document:u}},r.getRxReplicationMetaInstanceSchema=function(e,t){var r=(0,n.getLengthOfPrimaryKey)(e),o={primaryKey:{key:"id",fields:["itemId","isCheckpoint"],separator:"|"},type:"object",version:0,additionalProperties:!1,properties:{id:{type:"string",minLength:1,maxLength:r+2},isCheckpoint:{type:"string",enum:["0","1"],minLength:1,maxLength:1},itemId:{type:"string",maxLength:r},data:{type:"object",additionalProperties:!0},isResolvedConflict:{type:"string"}},required:["id","isCheckpoint","itemId","data"]};t&&(o.encrypted=["data"]);return(0,n.fillWithDefaultSettings)(o)};var n=e("../rx-schema-helper"),o=e("../rx-storage-helper"),i=e("../plugins/utils")},{"../plugins/utils":12,"../rx-schema-helper":50,"../rx-storage-helper":52}],38:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.startReplicationUpstream=async function(e){if(e.input.initialCheckpoint&&e.input.initialCheckpoint.upstream){await(0,a.getLastCheckpointDoc)(e,"up")||await(0,a.setCheckpoint)(e,"up",e.input.initialCheckpoint.upstream)}var t=e.input.replicationHandler;e.streamQueue.up=e.streamQueue.up.then((()=>d().then((()=>{h()}))));var r=0,l=-1,f=[],p=e.input.forkInstance.changeStream().pipe((0,n.filter)((t=>t.context!==e.downstreamBulkWriteFlag))).subscribe((t=>(e.stats.up.forkChangeStreamEmit=e.stats.up.forkChangeStreamEmit+1,f.push({task:t,time:r++}),e.input.waitBeforePersist?e.input.waitBeforePersist().then((()=>h())):h())));async function d(){if(e.stats.up.upstreamInitialSync=e.stats.up.upstreamInitialSync+1,!e.events.canceled.getValue()){e.checkpointQueue=e.checkpointQueue.then((()=>(0,a.getLastCheckpointDoc)(e,"up")));for(var t=await e.checkpointQueue,n=[];!e.events.canceled.getValue();){l=r++;var s=await e.input.forkInstance.getChangedDocumentsSince(e.input.pushBatchSize,t);if(0===s.documents.length)break;t=(0,o.stackCheckpoints)([t,s.checkpoint]),n.push(m(s.documents,(0,i.ensureNotFalsy)(t)))}(await Promise.all(n)).find((e=>!!e))?await d():e.firstSyncDone.up.getValue()||e.events.canceled.getValue()||e.firstSyncDone.up.next(!0)}}function h(){e.events.canceled.getValue()||0===f.length?e.events.active.up.next(!1):(e.stats.up.processTasks=e.stats.up.processTasks+1,e.events.active.up.next(!0),e.streamQueue.up=e.streamQueue.up.then((()=>{for(var t=[],r={};f.length>0;){var n=(0,i.ensureNotFalsy)(f.shift());n.timee.documentData))),r=(0,o.stackCheckpoints)([r,n.task.checkpoint]))}return(0===t.length?i.PROMISE_RESOLVE_FALSE:m(t,r)).then((()=>{0===f.length?e.events.active.up.next(!1):h()}))})))}(0,n.firstValueFrom)(e.events.canceled.pipe((0,n.filter)((e=>!!e)))).then((()=>p.unsubscribe()));var b=i.PROMISE_RESOLVE_FALSE,v={docs:{}};function m(r,n){return e.stats.up.persistToMaster=e.stats.up.persistToMaster+1,r.forEach((t=>{var r=t[e.primaryPath];v.docs[r]=t})),v.checkpoint=n,b=b.then((async()=>{if(e.events.canceled.getValue())return!1;var r=v.docs;v.docs={};var n=v.checkpoint,o=Object.keys(r);if(0===o.length)return!1;var l=await(0,c.getAssumedMasterState)(e,o),f={},p=[],d={},h={};if(await Promise.all(o.map((async t=>{var n=r[t];h[t]=n;var o=(0,u.writeDocToDocState)(n),a=l[t];a&&a.metaDocument.isResolvedConflict!==n._rev&&(await e.input.conflictHandler({realMasterState:a.docData,newDocumentState:o},"upstream-check-if-equal")).isEqual||a&&a.docData._rev&&(0,i.parseRevision)(n._rev).height===n._meta[e.input.identifier]||(p.push(t),f[t]={assumedMasterState:a?a.docData:void 0,newDocumentState:o},d[t]=(0,c.getMetaWriteRow)(e,o,a?a.metaDocument:void 0))}))),0===p.length)return!1;var b=Object.values(f),m=new Set,y={},g=(0,i.batchArray)(b,e.input.pushBatchSize);await Promise.all(g.map((async r=>{(await t.masterWrite(r)).forEach((t=>{var r=t[e.primaryPath];m.add(r),y[r]=t}))})));var _=[];p.forEach((t=>{m.has(t)||(e.events.processed.up.next(f[t]),_.push(d[t]))})),_.length>0&&await e.input.metaInstance.bulkWrite(_,"replication-up-write-meta");var O=!1;if(m.size>0){e.stats.up.persistToMasterHadConflicts=e.stats.up.persistToMasterHadConflicts+1;var w=[],j={};if(await Promise.all(Object.entries(y).map((([t,r])=>{var n=f[t],o={newDocumentState:n.newDocumentState,assumedMasterState:n.assumedMasterState,realMasterState:r};return(0,s.resolveConflictError)(e,o,h[t]).then((n=>{if(n){e.events.resolvedConflicts.next({input:o,output:n.output}),w.push({previous:h[t],document:n.resolvedDoc});var a=l[t];j[t]=(0,c.getMetaWriteRow)(e,(0,i.ensureNotFalsy)(r),a?a.metaDocument:void 0,n.resolvedDoc._rev)}}))}))),w.length>0){O=!0,e.stats.up.persistToMasterConflictWrites=e.stats.up.persistToMasterConflictWrites+1;var x=await e.input.forkInstance.bulkWrite(w,"replication-up-write-conflict"),S=[];Object.keys(x.success).forEach((e=>{S.push(j[e])})),S.length>0&&await e.input.metaInstance.bulkWrite(S,"replication-up-write-conflict-meta")}}return e.checkpointQueue=e.checkpointQueue.then((()=>(0,a.setCheckpoint)(e,"up",n))),O})).catch((t=>(e.events.error.next(t),!1)))}};var n=e("rxjs"),o=e("../rx-storage-helper"),i=e("../plugins/utils"),a=e("./checkpoint"),s=e("./conflicts"),u=e("./helper"),c=e("./meta-instance")},{"../plugins/utils":12,"../rx-storage-helper":52,"./checkpoint":32,"./conflicts":33,"./helper":35,"./meta-instance":37,rxjs:450}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.flattenEvents=function e(t){var r=[];Array.isArray(t)?t.forEach((t=>{var n=e(t);r=r.concat(n)})):t.id&&t.events?t.events.forEach((e=>r.push(e))):r.push(t);var n=new Set,o=[];return r.forEach((e=>{n.has(e.eventId)||(n.add(e.eventId),o.push(e))})),o},r.getDocumentDataOfRxChangeEvent=function(e){return e.documentData?e.documentData:e.previousDocumentData},r.rxChangeEventToEventReduceChangeEvent=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:n.overwritable.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}};var n=e("./overwritable")},{"./overwritable":9}],40:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createRxCollectionStorageInstance=async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)},r.fillObjectDataBeforeInsert=function(e,t){t=(0,n.flatClone)(t),t=(0,o.fillObjectWithDefaults)(e,t),(t=(0,o.fillPrimaryKey)(e.primaryPath,e.jsonSchema,t))._meta=(0,n.getDefaultRxDocumentMeta)(),t.hasOwnProperty("_deleted")||(t._deleted=!1);t.hasOwnProperty("_attachments")||(t._attachments={});t.hasOwnProperty("_rev")||(t._rev=(0,n.getDefaultRevision)());return t},r.removeCollectionStorages=async function(e,t,r,o,c,l){var f=(await(0,a.getAllCollectionDocuments)(e.statics,t)).filter((e=>e.data.name===c)),p=[];f.forEach((e=>{p.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>p.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var d=new Set;if(p=p.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!d.has(t)&&(d.add(t),!0)})),await Promise.all(p.map((async t=>{var n=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:o,multiInstance:!1,options:{},schema:t.schema,devMode:u.overwritable.isDevMode()});await n.remove(),t.isCollection&&await(0,i.runAsyncPluginHooks)("postRemoveRxCollection",{storage:e,databaseName:o,collectionName:c})}))),l){var h=f.map((e=>{var t=(0,s.flatCloneDocWithMeta)(e);return t._deleted=!0,t._meta.lwt=(0,n.now)(),t._rev=(0,n.createRevision)(r,e),{previous:e,document:t}}));await t.bulkWrite(h,"rx-database-remove-collection-all")}};var n=e("./plugins/utils"),o=e("./rx-schema-helper"),i=e("./hooks"),a=e("./rx-database-internal-store"),s=e("./rx-storage-helper"),u=e("./overwritable")},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-database-internal-store":42,"./rx-schema-helper":50,"./rx-storage-helper":52}],41:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxCollectionBase=void 0,r.createRxCollection=function({database:e,name:t,schema:r,instanceCreationOptions:n={},migrationStrategies:o={},autoMigrate:i=!0,statics:u={},methods:c={},attachments:l={},options:p={},localDocuments:h=!1,cacheReplacementPolicy:b=f.defaultCacheReplacementPolicy,conflictHandler:m=v.defaultConflictHandler}){var y={databaseInstanceToken:e.token,databaseName:e.name,collectionName:t,schema:r.jsonSchema,options:n,multiInstance:e.multiInstance,password:e.password,devMode:g.overwritable.isDevMode()};return(0,d.runPluginHooks)("preCreateRxStorageInstance",y),(0,s.createRxCollectionStorageInstance)(e,y).then((s=>{var f=new j(e,t,r,s,n,o,c,l,p,b,u,m);return f.prepare().then((()=>{Object.entries(u).forEach((([e,t])=>{Object.defineProperty(f,e,{get:()=>t.bind(f)})}));var e=a.PROMISE_RESOLVE_VOID;return i&&0!==f.schema.version&&(e=f.migratePromise()),e})).then((()=>((0,d.runPluginHooks)("createRxCollection",{collection:f,creator:{name:t,schema:r,storageInstance:s,instanceCreationOptions:n,migrationStrategies:o,methods:c,attachments:l,options:p,cacheReplacementPolicy:b,localDocuments:h,statics:u}}),f))).catch((e=>s.close().then((()=>Promise.reject(e)))))}))},r.isRxCollection=function(e){return e instanceof j};var o=n(e("@babel/runtime/helpers/createClass")),i=e("rxjs/operators"),a=e("./plugins/utils"),s=e("./rx-collection-helper"),u=e("./rx-query"),c=e("./rx-error"),l=e("./doc-cache"),f=e("./query-cache"),p=e("./change-event-buffer"),d=e("./hooks"),h=e("./rx-document-prototype-merge"),b=e("./rx-storage-helper"),v=e("./replication-protocol"),m=e("./incremental-write"),y=e("./rx-document"),g=e("./overwritable"),_=["pre","post"],O=["insert","save","remove","create"],w=!1,j=function(){function e(e,t,r,n,o={},i={},s={},u={},c={},l=f.defaultCacheReplacementPolicy,p={},d=v.defaultConflictHandler){this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=(0,f.createQueryCache)(),this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=n,this.instanceCreationOptions=o,this.migrationStrategies=i,this.methods=s,this.attachments=u,this.options=c,this.cacheReplacementPolicy=l,this.statics=p,this.conflictHandler=d,function(e){if(w)return;w=!0;var t=Object.getPrototypeOf(e);O.forEach((e=>{_.map((r=>{var n=r+(0,a.ucfirst)(e);t[n]=function(t,n){return this.addHook(r,e,t,n)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=(0,b.getWrappedStorageInstance)(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new m.IncrementalWriteQueue(this.storageInstance,this.schema.primaryPath,((e,t)=>(0,y.beforeDocumentUpdateWrite)(this,e,t)),(e=>this._runHooks("post","save",e)));var e=this.database.eventBulks$.pipe((0,i.filter)((e=>e.collectionName===this.name)));this.$=e.pipe((0,i.mergeMap)((e=>e.events))),this.checkpoint$=e.pipe((0,i.map)((e=>e.checkpoint))),this._changeEventBuffer=(0,p.createChangeEventBuffer)(this.asRxCollection),this._docCache=new l.DocumentCache(this.schema.primaryPath,this.$.pipe((0,i.filter)((e=>!e.isLocal))),(e=>(0,h.createNewRxDocument)(this.asRxCollection,e)));var t=await this.database.storageToken,r=this.storageInstance.changeStream().subscribe((e=>{var r={id:e.id,internal:!1,collectionName:this.name,storageToken:t,events:e.events.map((e=>(0,b.storageChangeEventToRxChangeEvent)(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context};this.database.$emit(r)}));return this._subs.push(r),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),a.PROMISE_RESOLVE_VOID},t.migrationNeeded=function(){throw(0,a.pluginMissing)("migration")},t.getDataMigrator=function(){throw(0,a.pluginMissing)("migration")},t.migrate=function(e=10){return this.getDataMigrator().migrate(e)},t.migratePromise=function(e=10){return this.getDataMigrator().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return(0,b.throwIfIsStorageWriteError)(this,e[this.schema.primaryPath],e,r),(0,a.ensureNotFalsy)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>(0,s.fillObjectDataBeforeInsert)(this.schema,e))),n=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,o=new Map,i=n.map((e=>(o.set(e[t],e),{document:e}))),a=await this.storageInstance.bulkWrite(i,"rx-collection-bulk-insert"),u=Object.values(a.success).map((e=>this._docCache.getCachedRxDocument(e)));return this.hasHooks("post","insert")&&await Promise.all(u.map((e=>this._runHooks("post","insert",o.get(e.primary),e)))),{success:u,error:Object.values(a.error)}},t.bulkRemove=async function(e){if(0===e.length)return{success:[],error:[]};var t=await this.findByIds(e).exec(),r=[],n=new Map;Array.from(t.values()).forEach((e=>{var t=e.toMutableJSON(!0);r.push(t),n.set(e.primary,t)})),await Promise.all(r.map((e=>{var r=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,t.get(r))})));var o=r.map((e=>{var t=(0,a.flatClone)(e);return t._deleted=!0,{previous:e,document:t}})),i=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),s=Object.keys(i.success);return await Promise.all(s.map((e=>this._runHooks("post","remove",n.get(e),t.get(e))))),{success:s.map((e=>(0,a.getFromMapOrThrow)(t,e))),error:Object.values(i.error)}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var n=(0,s.fillObjectDataBeforeInsert)(this.schema,e),o=n[this.schema.primaryPath];if(!o)throw(0,c.newRxError)("COL3",{primaryPath:this.schema.primaryPath,data:n,schema:this.schema.jsonSchema});r.set(o,n),t.push(n)}));var n=await this.bulkInsert(t),o=n.success.slice(0),i=await Promise.all(n.error.map((async e=>{if(409!==e.status)throw(0,c.newRxError)("VD2",{collection:this.name,writeError:e});var t=e.documentId,n=(0,a.getFromMapOrThrow)(r,t),o=(0,a.ensureNotFalsy)(e.documentInDb),i=this._docCache.getCachedRxDocument(o);return await i.incrementalModify((()=>n))})));return o=o.concat(i)},t.upsert=function(e){return this.bulkUpsert([e]).then((e=>e[0]))},t.incrementalUpsert=function(e){var t=(0,s.fillObjectDataBeforeInsert)(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw(0,c.newRxError)("COL4",{data:e});var n=this._incrementalUpsertQueues.get(r);return n||(n=a.PROMISE_RESOLVE_VOID),n=n.then((()=>function(e,t,r){var n=e._docCache.getLatestDocumentDataIfExists(t);if(n)return Promise.resolve({doc:e._docCache.getCachedRxDocument(n),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,n),n},t.find=function(e){if("string"==typeof e)throw(0,c.newRxError)("COL5",{queryObj:e});return e||(e=(0,u._getDefaultQuery)()),(0,u.createRxQuery)("find",e,this)},t.findOne=function(e){var t;if("string"==typeof e)t=(0,u.createRxQuery)("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e=(0,u._getDefaultQuery)()),e.limit)throw(0,c.newRxError)("QU6");e.limit=1,t=(0,u.createRxQuery)("findOne",e,this)}if("number"==typeof e||Array.isArray(e))throw(0,c.newRxTypeError)("COL6",{queryObj:e});return t},t.count=function(e){return e||(e=(0,u._getDefaultQuery)()),(0,u.createRxQuery)("count",e,this)},t.findByIds=function(e){var t={selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}};return(0,u.createRxQuery)("findByIds",t,this)},t.exportJSON=function(){throw(0,a.pluginMissing)("json-dump")},t.importJSON=function(e){throw(0,a.pluginMissing)("json-dump")},t.insertCRDT=function(e){throw(0,a.pluginMissing)("crdt")},t.addHook=function(e,t,r,n=!1){if("function"!=typeof r)throw(0,c.newRxTypeError)("COL7",{key:t,when:e});if(!_.includes(e))throw(0,c.newRxTypeError)("COL8",{key:t,when:e});if(!O.includes(t))throw(0,c.newRxError)("COL9",{key:t});if("post"===e&&"create"===t&&!0===n)throw(0,c.newRxError)("COL10",{when:e,key:t,parallel:n});var o=r.bind(this),i=n?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(o)},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,n){var o=this.getHooks(e,t);if(!o)return a.PROMISE_RESOLVE_VOID;var i=o.series.map((e=>()=>e(r,n)));return(0,a.promiseSeries)(i).then((()=>Promise.all(o.parallel.map((e=>e(r,n))))))},t._runHooksSync=function(e,t,r,n){var o=this.getHooks(e,t);o&&o.series.forEach((e=>e(r,n)))},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?a.PROMISE_RESOLVE_FALSE:(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],(0,d.runAsyncPluginHooks)("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await(0,s.removeCollectionStorages)(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.hashFunction)},(0,o.default)(e,[{key:"insert$",get:function(){return this.$.pipe((0,i.filter)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,i.filter)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,i.filter)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();r.RxCollectionBase=j},{"./change-event-buffer":2,"./doc-cache":4,"./hooks":6,"./incremental-write":7,"./overwritable":9,"./plugins/utils":12,"./query-cache":30,"./replication-protocol":36,"./rx-collection-helper":40,"./rx-document":45,"./rx-document-prototype-merge":44,"./rx-error":46,"./rx-query":49,"./rx-storage-helper":52,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61,"rxjs/operators":675}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.STORAGE_TOKEN_DOCUMENT_KEY=r.STORAGE_TOKEN_DOCUMENT_ID=r.INTERNAL_STORE_SCHEMA_TITLE=r.INTERNAL_STORE_SCHEMA=r.INTERNAL_CONTEXT_STORAGE_TOKEN=r.INTERNAL_CONTEXT_COLLECTION=void 0,r._collectionNamePrimary=h,r.addConnectedStorageToCollection=async function(e,t,r){var o=f(h(e.name,e.schema.jsonSchema),s);for(;;){var u=await(0,i.getSingleDocument)(e.database.internalStore,o),c=(0,a.clone)((0,a.ensureNotFalsy)(u));if(c.data.connectedStorages||(c.data.connectedStorages=[]),c.data.connectedStorages.find((e=>e.collectionName===t&&e.schema.version===r.version)))return;c.data.connectedStorages.push({collectionName:t,schema:r});try{await(0,i.writeSingle)(e.database.internalStore,{previous:(0,a.ensureNotFalsy)(u),document:c},"add-connected-storage-to-collection")}catch(e){if(!(0,n.isBulkWriteConflictError)(e))throw e}}},r.ensureStorageTokenDocumentExists=async function(e){var t=(0,a.randomCouchString)(10),r=e.password?e.hashFunction(JSON.stringify(e.password)):void 0,o={id:d,context:u,key:p,data:{token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}},i=await e.internalStore.bulkWrite([{document:o}],"internal-add-storage-token");if(i.success[d])return i.success[d];var s=(0,a.ensureNotFalsy)(i.error[d]);if(s.isError&&409===s.status){var c=s;if(r&&r!==c.documentInDb.data.passwordHash)throw(0,n.newRxError)("DB1",{passwordHash:r,existingPasswordHash:c.documentInDb.data.passwordHash});var l=c.documentInDb;return(0,a.ensureNotFalsy)(l)}throw s},r.getAllCollectionDocuments=async function(e,t){var r=e.prepareQuery(t.schema,{selector:{context:s},sort:[{id:"asc"}],skip:0});return(await t.query(r)).documents},r.getPrimaryKeyOfInternalDocument=f;var n=e("./rx-error"),o=e("./rx-schema-helper"),i=e("./rx-storage-helper"),a=e("./plugins/utils"),s="collection";r.INTERNAL_CONTEXT_COLLECTION=s;var u="storage-token";r.INTERNAL_CONTEXT_STORAGE_TOKEN=u;var c="RxInternalDocument";r.INTERNAL_STORE_SCHEMA_TITLE=c;var l=(0,o.fillWithDefaultSettings)({version:0,title:c,primaryKey:{key:"id",fields:["context","key"],separator:"|"},type:"object",properties:{id:{type:"string",maxLength:200},key:{type:"string"},context:{type:"string",enum:[s,u,"OTHER"]},data:{type:"object",additionalProperties:!0}},indexes:[],required:["key","context","data"],additionalProperties:!1,sharding:{shards:1,mode:"collection"}});function f(e,t){return(0,o.getComposedPrimaryKeyOfDocumentData)(l,{key:e,context:t})}r.INTERNAL_STORE_SCHEMA=l;var p="storageToken";r.STORAGE_TOKEN_DOCUMENT_KEY=p;var d=f(p,u);function h(e,t){return e+"-"+t.version}r.STORAGE_TOKEN_DOCUMENT_ID=d},{"./plugins/utils":12,"./rx-error":46,"./rx-schema-helper":50,"./rx-storage-helper":52}],43:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxDatabaseBase=void 0,r.createRxDatabase=function({storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:o=!0,eventReduce:i=!1,ignoreDuplicate:u=!1,options:l={},cleanupPolicy:f,allowSlowCount:p=!1,localDocuments:d=!1,hashFunction:h=a.defaultHashSha256}){(0,c.runPluginHooks)("preCreateRxDatabase",{storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:o,eventReduce:i,ignoreDuplicate:u,options:l,localDocuments:d}),u||function(e){if(y.has(e))throw(0,s.newRxError)("DB8",{name:e,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(r);y.add(r);var b=(0,a.randomCouchString)(10);return O(b,e,r,t,o,n).catch((e=>{throw y.delete(r),e})).then((a=>{var s=new _(r,b,e,t,n,o,i,l,a,h,f,p);return(0,c.runAsyncPluginHooks)("createRxDatabase",{database:s,creator:{storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:o,eventReduce:i,ignoreDuplicate:u,options:l,localDocuments:d}}).then((()=>s))}))},r.createRxDatabaseStorageInstance=O,r.dbCount=function(){return g},r.ensureNoStartupErrors=j,r.isRxDatabase=function(e){return e instanceof _},r.isRxDatabaseFirstTimeInstantiated=async function(e){return(await e.storageTokenDocument).data.instanceToken===e.token},r.removeRxDatabase=w;var o=n(e("@babel/runtime/helpers/createClass")),i=e("custom-idle-queue"),a=e("./plugins/utils"),s=e("./rx-error"),u=e("./rx-schema"),c=e("./hooks"),l=e("rxjs"),f=e("rxjs/operators"),p=e("./rx-collection"),d=e("./rx-storage-helper"),h=e("oblivious-set"),b=e("./rx-database-internal-store"),v=e("./rx-collection-helper"),m=e("./overwritable"),y=new Set,g=0,_=function(){function e(e,t,r,n,o,s,u=!1,c={},p,v,m,y){this.idleQueue=new i.IdleQueue,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.eventBulks$=new l.Subject,this.observable$=this.eventBulks$.pipe((0,f.mergeMap)((e=>e.events))),this.storageToken=a.PROMISE_RESOLVE_FALSE,this.storageTokenDocument=a.PROMISE_RESOLVE_FALSE,this.emittedEventBulkIds=new h.ObliviousSet(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=n,this.password=o,this.multiInstance=s,this.eventReduce=u,this.options=c,this.internalStore=p,this.hashFunction=v,this.cleanupPolicy=m,this.allowSlowCount=y,g++,"pseudoInstance"!==this.name&&(this.internalStore=(0,d.getWrappedStorageInstance)(this.asRxDatabase,p,b.INTERNAL_STORE_SCHEMA),this.storageTokenDocument=(0,b.ensureStorageTokenDocumentExists)(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.$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(0,d.getSingleDocument)(this.internalStore,(0,b.getPrimaryKeyOfInternalDocument)((0,b._collectionNamePrimary)(e,t),b.INTERNAL_CONTEXT_COLLECTION));if(!r)throw(0,s.newRxError)("SNH",{name:e,schema:t});var n=(0,d.flatCloneDocWithMeta)(r);n._deleted=!0,await this.internalStore.bulkWrite([{document:n,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},n=[],o={};Object.entries(e).forEach((([e,i])=>{var l=e,f=i.schema;t[l]=f;var p=(0,u.createRxSchema)(f,this.hashFunction);if(r[l]=p,this.collections[e])throw(0,s.newRxError)("DB3",{name:e});var d=(0,b._collectionNamePrimary)(e,f),h={id:(0,b.getPrimaryKeyOfInternalDocument)(d,b.INTERNAL_CONTEXT_COLLECTION),key:d,context:b.INTERNAL_CONTEXT_COLLECTION,data:{name:l,schemaHash:p.hash,schema:p.jsonSchema,version:p.version,connectedStorages:[]},_deleted:!1,_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}};n.push({document:h});var v=Object.assign({},i,{name:l,schema:p,database:this}),m=(0,a.flatClone)(i);m.database=this,m.name=e,(0,c.runPluginHooks)("preCreateRxCollection",m),v.conflictHandler=m.conflictHandler,o[l]=v}));var i=await this.internalStore.bulkWrite(n,"rx-database-add-collection");await j(this),Object.entries(i.error).forEach((([e,n])=>{if(409!==n.status)throw(0,s.newRxError)("DB12",{database:this.name,writeError:n});var o=(0,a.ensureNotFalsy)(n.documentInDb),i=o.data.name,u=r[i];if(o.data.schemaHash!==u.hash)throw(0,s.newRxError)("DB6",{database:this.name,collection:i,previousSchemaHash:o.data.schemaHash,schemaHash:u.hash,previousSchema:o.data.schema,schema:(0,a.ensureNotFalsy)(t[i])})}));var l={};return await Promise.all(Object.keys(e).map((async e=>{var t=o[e],r=await(0,p.createRxCollection)(t);l[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),l},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw(0,a.pluginMissing)("json-dump")},t.importJSON=function(e){throw(0,a.pluginMissing)("json-dump")},t.backup=function(e){throw(0,a.pluginMissing)("backup")},t.leaderElector=function(){throw(0,a.pluginMissing)("leader-election")},t.isLeader=function(){throw(0,a.pluginMissing)("leader-election")},t.waitForLeadership=function(){throw(0,a.pluginMissing)("leader-election")},t.migrationStates=function(){throw(0,a.pluginMissing)("migration")},t.destroy=async function(){return this.destroyed?a.PROMISE_RESOLVE_FALSE:(this.destroyed=!0,await(0,c.runAsyncPluginHooks)("preDestroyRxDatabase",this),this.eventBulks$.complete(),g--,this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?a.PROMISE_RESOLVE_FALSE: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((()=>y.delete(this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>w(this.name,this.storage)))},(0,o.default)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function O(e,t,r,n,o,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:d.INTERNAL_STORAGE_NAME,schema:b.INTERNAL_STORE_SCHEMA,options:n,multiInstance:o,password:i,devMode:m.overwritable.isDevMode()})}async function w(e,t){var r=(0,a.randomCouchString)(10),n=await O(r,t,e,{},!1),o=await(0,b.getAllCollectionDocuments)(t.statics,n),i=new Set;o.forEach((e=>i.add(e.data.name)));var s=Array.from(i);return await Promise.all(s.map((o=>(0,v.removeCollectionStorages)(t,n,r,e,o)))),await(0,c.runAsyncPluginHooks)("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),s}async function j(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}r.RxDatabaseBase=_},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-collection":41,"./rx-collection-helper":40,"./rx-database-internal-store":42,"./rx-error":46,"./rx-schema":51,"./rx-storage-helper":52,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61,"custom-idle-queue":408,"oblivious-set":446,rxjs:450,"rxjs/operators":675}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createNewRxDocument=function(e,t){var r=(0,n.createWithConstructor)(c(e),e,i.overwritable.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),(0,o.runPluginHooks)("postCreateRxDocument",r),r},r.getDocumentOrmPrototype=l,r.getDocumentPrototype=u,r.getRxDocumentConstructor=c;var n=e("./rx-document"),o=e("./hooks"),i=e("./overwritable"),a=e("./plugins/utils"),s=new WeakMap;function u(e){var t=e.schema.getDocumentPrototype(),r=l(e),o=n.basePrototype,i={};return[t,r,o].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(i,t,{get(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(i,t,r))}))})),i}function c(e){return(0,a.getFromMapOrCreate)(s,e,(()=>(0,n.createRxDocumentConstructor)(u(e))))}function l(e){var t={};return Object.entries(e.methods).forEach((([e,r])=>{t[e]=r})),t}},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-document":45}],45:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.basePrototype=void 0,r.beforeDocumentUpdateWrite=h,r.createRxDocumentConstructor=function(e=p){var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t},r.createWithConstructor=function(e,t,r){var n=new e(t,r);return(0,a.runPluginHooks)("createRxDocument",n),n},r.defineGetterSetter=d,r.isRxDocument=function(e){return"object"==typeof e&&null!==e&&"isInstanceOfRxDocument"in e};var n=e("rxjs/operators"),o=e("./plugins/utils"),i=e("./rx-error"),a=e("./hooks"),s=e("./rx-change-event"),u=e("./overwritable"),c=e("./rx-schema-helper"),l=e("./rx-storage-helper"),f=e("./incremental-write"),p={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,n.map)((e=>e._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,n.filter)((e=>!e.isLocal)),(0,n.filter)((e=>e.documentId===this.primary)),(0,n.map)((e=>(0,s.getDocumentDataOfRxChangeEvent)(e))),(0,n.startWith)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,n.distinctUntilChanged)(((e,t)=>e._rev===t._rev)),(0,n.map)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,n.shareReplay)(o.RXJS_SHARE_REPLAY_DEFAULTS))},get$(e){if(u.overwritable.isDevMode()){if(e.includes(".item."))throw(0,i.newRxError)("DOC1",{path:e});if(e===this.primaryPath)throw(0,i.newRxError)("DOC2");if(this.collection.schema.finalFields.includes(e))throw(0,i.newRxError)("DOC3",{path:e});if(!(0,c.getSchemaByObjectPath)(this.collection.schema.jsonSchema,e))throw(0,i.newRxError)("DOC4",{path:e})}return this.$.pipe((0,n.map)((t=>(0,o.getProperty)(t,e))),(0,n.distinctUntilChanged)())},populate(e){var t=(0,c.getSchemaByObjectPath)(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return o.PROMISE_RESOLVE_NULL;if(!t)throw(0,i.newRxError)("DOC5",{path:e});if(!t.ref)throw(0,i.newRxError)("DOC6",{path:e,schemaObj:t});var n=this.collection.database.collections[t.ref];if(!n)throw(0,i.newRxError)("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?n.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):n.findOne(r).exec()},get(e){if(this._data){var t=this._propertyCache.get(e);if(t)return t;var r=(0,o.getProperty)(this._data,e);return"object"!=typeof r||Array.isArray(r)?u.overwritable.deepFreezeWhenDevMode(r):(r=(0,o.clone)(r),d(this.collection.schema,r,e,this),this._propertyCache.set(e,r),r)}},toJSON(e=!1){if(e)return u.overwritable.deepFreezeWhenDevMode(this._data);var t=(0,o.flatClone)(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,u.overwritable.deepFreezeWhenDevMode(t)},toMutableJSON(e=!1){return(0,o.clone)(this.toJSON(e))},update(e){throw(0,o.pluginMissing)("update")},incrementalUpdate(e){throw(0,o.pluginMissing)("update")},updateCRDT(e){throw(0,o.pluginMissing)("crdt")},putAttachment(){throw(0,o.pluginMissing)("attachments")},getAttachment(){throw(0,o.pluginMissing)("attachments")},allAttachments(){throw(0,o.pluginMissing)("attachments")},get allAttachments$(){throw(0,o.pluginMissing)("attachments")},async modify(e,t){var r=this._data,n=await(0,f.modifierFromPublicToInternal)(e)(r);return this._saveData(n,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,(0,f.modifierFromPublicToInternal)(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=(0,o.clone)(t);return Object.entries(e).forEach((([e,t])=>{r[e]=t})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((([e,r])=>{t[e]=r})),t)))},async _saveData(e,t){if(e=(0,o.flatClone)(e),this._data._deleted)throw(0,i.newRxError)("DOC11",{id:this.primary,document:this});await h(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),n=r.error[this.primary];return(0,l.throwIfIsStorageWriteError)(this.collection,this.primary,e,n),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument((0,o.getFromObjectOrThrow)(r.success,this.primary))},remove(){var e=this.collection;if(this.deleted)return Promise.reject((0,i.newRxError)("DOC13",{document:this,id:this.primary}));var t,r=(0,o.flatClone)(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"),n=t.error[this.primary];return(0,l.throwIfIsStorageWriteError)(e,this.primary,r,n),(0,o.getFromObjectOrThrow)(t.success,this.primary)})).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(0,i.newRxError)("DOC14")}};function d(e,t,r="",n=!1){if(null!==t){var i=(0,c.getSchemaByObjectPath)(e.jsonSchema,r);void 0!==i&&(i.properties&&(i=i.properties),Object.keys(i).forEach((e=>{var i=(0,o.trimDots)(r+"."+e);t.__defineGetter__(e,(function(){var e=n||this;if(e.get&&"function"==typeof e.get)return e.get(i)})),Object.defineProperty(t,e+"$",{get:function(){return(n||this).get$(i)},enumerable:!1,configurable:!1}),Object.defineProperty(t,e+"_",{get:function(){return(n||this).populate(i)},enumerable:!1,configurable:!1}),t.__defineSetter__(e,(function(e){return(n||this).set(i,e)}))})))}}function h(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),u.overwritable.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}r.basePrototype=p},{"./hooks":6,"./incremental-write":7,"./overwritable":9,"./plugins/utils":12,"./rx-change-event":39,"./rx-error":46,"./rx-schema-helper":50,"./rx-storage-helper":52,"rxjs/operators":675}],46:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxTypeError=r.RxError=void 0,r.isBulkWriteConflictError=function(e){return!(!e||409!==e.status)&&e},r.newRxError=f,r.newRxTypeError=function(e,t){return new l(e,s.overwritable.tunnelErrorMessage(e),t)},r.rxStorageWriteErrorToRxError=function(e){return f("COL20",{name:p[e.status],document:e.documentId,writeError:e})};var o=n(e("@babel/runtime/helpers/createClass")),i=n(e("@babel/runtime/helpers/inheritsLoose")),a=n(e("@babel/runtime/helpers/wrapNativeSuper")),s=e("./overwritable");function u(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((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(e){}return t+":"+r})).join("\n"),t+="}")}(r)}var c=function(e){function t(t,r,n={}){var o,i=u(r,t,n);return(o=e.call(this,i)||this).code=t,o.message=i,o.parameters=n,o.rxdb=!0,o}return(0,i.default)(t,e),t.prototype.toString=function(){return this.message},(0,o.default)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,a.default)(Error));r.RxError=c;var l=function(e){function t(t,r,n={}){var o,i=u(r,t,n);return(o=e.call(this,i)||this).code=t,o.message=i,o.parameters=n,o.rxdb=!0,o}return(0,i.default)(t,e),t.prototype.toString=function(){return this.message},(0,o.default)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,a.default)(TypeError));function f(e,t){return new c(e,s.overwritable.tunnelErrorMessage(e),t)}r.RxTypeError=l;var p={409:"document write conflict",422:"schema validation error",510:"attachment data missing"}},{"./overwritable":9,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/inheritsLoose":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/wrapNativeSuper":68}],47:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getQueryMatcher=function(e,t){if(!t.sort)throw(0,s.newRxError)("SNH",{query:t});var r=(0,u.getMingoQuery)(t.selector);return e=>!e._deleted&&!!r.find([e]).next()},r.getSortComparator=function(e,t){if(!t.sort)throw(0,s.newRxError)("SNH",{query:t});var r=[];return t.sort.forEach((e=>{var t=Object.keys(e)[0],n=Object.values(e)[0];r.push({key:t,direction:n,getValueFn:(0,i.objectPathMonad)(t)})})),(e,t)=>{for(var n=0;n{"object"==typeof t&&null!==t||(a.selector[e]={$eq:t})}))):a.selector={};if(a.index){var s=(0,i.toArray)(a.index);s.includes(r)||s.push(r),a.index=s}if(a.sort){a.sort.find((e=>(0,i.firstPropertyNameOfObject)(e)===r))||(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 u=new Set;Object.entries(a.selector).forEach((([e,t])=>{("object"!=typeof t||null===t||!!Object.keys(t).find((e=>n.LOGICAL_OPERATORS.has(e))))&&u.add(e)}));var l,f=-1;e.indexes.forEach((e=>{var t=(0,i.isMaybeReadonlyArray)(e)?e:[e],r=t.findIndex((e=>!u.has(e)));r>0&&r>f&&(f=r,l=t)})),l&&(a.sort=l.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a},r.normalizeQueryRegex=c;var n=e("./query-planner"),o=e("./rx-schema-helper"),i=e("./plugins/utils"),a=e("mingo/util"),s=e("./rx-error"),u=e("./rx-query-mingo");function c(e){if("object"!=typeof e||null===e)return e;var t=Object.keys(e),r={};return t.forEach((t=>{var n=e[t];if("$regex"===t&&n instanceof RegExp){var o=(0,i.parseRegex)(n);r.$regex=o.pattern,r.$options=o.flags}else Array.isArray(n)?r[t]=n.map((e=>c(e))):r[t]=c(n)})),r}},{"./plugins/utils":12,"./query-planner":31,"./rx-error":46,"./rx-query-mingo":48,"./rx-schema-helper":50,"mingo/util":445}],48:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getMingoQuery=function(e){S||((0,n.useOperators)(n.OperatorType.PIPELINE,{$sort:a.$sort,$project:i.$project}),(0,n.useOperators)(n.OperatorType.QUERY,{$and:s.$and,$eq:f.$eq,$elemMatch:g.$elemMatch,$exists:_.$exists,$gt:d.$gt,$gte:h.$gte,$in:w.$in,$lt:b.$lt,$lte:v.$lte,$ne:p.$ne,$nin:O.$nin,$mod:y.$mod,$nor:l.$nor,$not:u.$not,$or:c.$or,$regex:m.$regex,$size:j.$size,$type:x.$type}),S=!0);return new o.Query(e)};var n=e("mingo/core"),o=e("mingo/query"),i=e("mingo/operators/pipeline/project"),a=e("mingo/operators/pipeline/sort"),s=e("mingo/operators/query/logical/and"),u=e("mingo/operators/query/logical/not"),c=e("mingo/operators/query/logical/or"),l=e("mingo/operators/query/logical/nor"),f=e("mingo/operators/query/comparison/eq"),p=e("mingo/operators/query/comparison/ne"),d=e("mingo/operators/query/comparison/gt"),h=e("mingo/operators/query/comparison/gte"),b=e("mingo/operators/query/comparison/lt"),v=e("mingo/operators/query/comparison/lte"),m=e("mingo/operators/query/evaluation/regex"),y=e("mingo/operators/query/evaluation/mod"),g=e("mingo/operators/query/array/elemMatch"),_=e("mingo/operators/query/element/exists"),O=e("mingo/operators/query/comparison/nin"),w=e("mingo/operators/query/comparison/in"),j=e("mingo/operators/query/array/size"),x=e("mingo/operators/query/element/type"),S=!1},{"mingo/core":420,"mingo/operators/pipeline/project":424,"mingo/operators/pipeline/sort":425,"mingo/operators/query/array/elemMatch":426,"mingo/operators/query/array/size":427,"mingo/operators/query/comparison/eq":428,"mingo/operators/query/comparison/gt":429,"mingo/operators/query/comparison/gte":430,"mingo/operators/query/comparison/in":431,"mingo/operators/query/comparison/lt":432,"mingo/operators/query/comparison/lte":433,"mingo/operators/query/comparison/ne":434,"mingo/operators/query/comparison/nin":435,"mingo/operators/query/element/exists":436,"mingo/operators/query/element/type":437,"mingo/operators/query/evaluation/mod":438,"mingo/operators/query/evaluation/regex":439,"mingo/operators/query/logical/and":440,"mingo/operators/query/logical/nor":441,"mingo/operators/query/logical/not":442,"mingo/operators/query/logical/or":443,"mingo/query":444}],49:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxQueryBase=void 0,r._getDefaultQuery=b,r.createRxQuery=function(e,t,r,n){(0,c.runPluginHooks)("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:n});var o=new h(e,t,r,n);return o=v(o),(0,f.triggerCacheReplacement)(r),o},r.isFindOneByIdQuery=_,r.isRxQuery=function(e){return e instanceof h},r.queryCollection=g,r.tunnelQueryCache=v;var o=n(e("@babel/runtime/helpers/createClass")),i=e("rxjs"),a=e("rxjs/operators"),s=e("./plugins/utils"),u=e("./rx-error"),c=e("./hooks"),l=e("./event-reduce"),f=e("./query-cache"),p=e("./rx-query-helper"),d=0,h=function(){function e(e,t,r,n={}){this.id=++d,this._execOverDatabaseCount=0,this._creationTime=(0,s.now)(),this._lastEnsureEqual=0,this.uncached=!1,this.refCount$=new i.BehaviorSubject(null),this._result=null,this._latestChangeEvent=-1,this._lastExecStart=0,this._lastExecEnd=0,this._ensureEqualQueue=s.PROMISE_RESOLVE_FALSE,this.op=e,this.mangoQuery=t,this.collection=r,this.other=n,t||(this.mangoQuery={selector:{}}),this.isFindOneByIdQuery=_(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 Map,r=new Map,n=e.map((e=>this.collection._docCache.getCachedRxDocument(e))),o=n.map((e=>(t.set(e.primary,e._data),r.set(e.primary,e),e._data)));this._result={docsData:o,docsMap:r,docsDataMap:t,count:o.length,docs:n,time:(0,s.now)()}}else this._result={docsData:[],docsMap:new Map,docsDataMap:new Map,count:e,docs:[],time:(0,s.now)()}},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,s.now)(),"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(0,u.newRxError)("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,s.ensureNotFalsy)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,n=new Map,o=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);n.set(e,r)}}else o.push(e)})),o.length>0){var i=await this.collection.storageInstance.findDocumentsById(o,!1);Object.values(i).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);n.set(t.primary,t)}))}return n}return g(this).then((e=>(this._lastExecEnd=(0,s.now)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw(0,u.newRxError)("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return y(this).then((()=>(0,i.firstValueFrom)(this.$))).then((t=>{if(!t&&e)throw(0,u.newRxError)("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=(0,s.sortObject)({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e,s.stringifyFilter);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:(0,p.normalizeMangoQuery)(this.collection.schema.jsonSchema,this.mangoQuery)};(0,c.runPluginHooks)("prePrepareQuery",e);var t=this.collection.database.storage.statics.prepareQuery(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(0,s.pluginMissing)("update")},t.where=function(e){throw(0,s.pluginMissing)("query-builder")},t.sort=function(e){throw(0,s.pluginMissing)("query-builder")},t.skip=function(e){throw(0,s.pluginMissing)("query-builder")},t.limit=function(e){throw(0,s.pluginMissing)("query-builder")},(0,o.default)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,a.filter)((e=>!e.isLocal)),(0,a.startWith)(null),(0,a.mergeMap)((()=>y(this))),(0,a.map)((()=>this._result)),(0,a.shareReplay)(s.RXJS_SHARE_REPLAY_DEFAULTS),(0,a.distinctUntilChanged)(((e,t)=>!(!e||e.time!==(0,s.ensureNotFalsy)(t).time))),(0,a.filter)((e=>!!e)),(0,a.map)((e=>{var t=(0,s.ensureNotFalsy)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.docs.length?null:t.docs[0]:"findByIds"===this.op?t.docsMap:t.docs.slice(0)})));this._$=(0,i.merge)(e,this.refCount$.pipe((0,a.filter)((()=>!1))))}return this._$}},{key:"queryMatcher",get:function(){var e=this.collection.schema.jsonSchema,t=(0,p.normalizeMangoQuery)(this.collection.schema.jsonSchema,this.mangoQuery);return(0,s.overwriteGetterForCaching)(this,"queryMatcher",(0,p.getQueryMatcher)(e,t))}},{key:"asRxQuery",get:function(){return this}}]),e}();function b(){return{selector:{}}}function v(e){return e.collection._queryCache.getByQuery(e)}function m(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function y(e){return e.collection.database.destroyed||m(e)?s.PROMISE_RESOLVE_FALSE:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,s.now)(),e.collection.database.destroyed||m(e))return s.PROMISE_RESOLVE_FALSE;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var n=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===n)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var o=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(n);if("count"===e.op){var i=(0,s.ensureNotFalsy)(e._result).count,a=i;o.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),n=e.doesDocumentDataMatch(t.documentData);!r&&n&&a++,r&&!n&&a--})),a!==i&&(t=!0,e._setResultData(a))}else{var u=(0,l.calculateNewResults)(e,o);u.runFullQueryAgain?r=!0:u.changed&&(t=!0,e._setResultData(u.newResults))}}}if(r){var c=e.collection._changeEventBuffer.counter;return e._execOverDatabase().then((r=>(e._latestChangeEvent=c,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&(0,s.areRxDocumentArraysEqual)(e.collection.schema.primaryPath,r,e._result.docsData)||(t=!0,e._setResultData(r)),t))))}return Promise.resolve(t)}(e))),e._ensureEqualQueue)}async function g(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var n=e.isFindOneByIdQuery;n=n.filter((r=>{var n=e.collection._docCache.getLatestDocumentDataIfExists(r);return!n||(t.push(n),!1)}));var o=await r.storageInstance.findDocumentsById(n,!1);Object.values(o).forEach((e=>{t.push(e)}))}else{var i=e.isFindOneByIdQuery,a=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!a)a=(await r.storageInstance.findDocumentsById([i],!1))[i];a&&t.push(a)}else{var s=e.getPreparedQuery(),u=await r.storageInstance.query(s);t=u.documents}return t}function _(e,t){if(!t.skip&&t.selector&&1===Object.keys(t.selector).length&&t.selector[e]){var r=t.selector[e];if("string"==typeof r)return r;if(1===Object.keys(r).length&&"string"==typeof r.$eq)return r.$eq;if(1===Object.keys(r).length&&Array.isArray(r.$eq)&&!r.$eq.find((e=>"string"!=typeof e)))return r.$eq}return!1}r.RxQueryBase=h},{"./event-reduce":5,"./hooks":6,"./plugins/utils":12,"./query-cache":30,"./rx-error":46,"./rx-query-helper":47,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61,rxjs:450,"rxjs/operators":675}],50:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RX_META_SCHEMA=r.DEFAULT_CHECKPOINT_SCHEMA=void 0,r.fillObjectWithDefaults=function(e,t){for(var r=Object.keys(e.defaultValues),n=0;n{var r=(0,o.getProperty)(t,e);if(void 0===r)throw(0,n.newRxError)("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function u(e){var t=a((e=(0,o.flatClone)(e)).primaryKey);e.properties=(0,o.flatClone)(e.properties),e.additionalProperties=!1,e.hasOwnProperty("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=c,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=l(e);return e.required=e.required.concat(r).filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0,e.indexes&&(e.indexes=e.indexes.map((e=>{var r=(0,o.isMaybeReadonlyArray)(e)?e.slice(0):[e];if(!r.includes(t)){var n=r.slice(0);return n.push(t),n}return r}))),e}var c={type:"object",properties:{lwt:{type:"number",minimum:o.RX_META_LWT_MINIMUM,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function l(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=a(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}r.RX_META_SCHEMA=c;r.DEFAULT_CHECKPOINT_SCHEMA={type:"object",properties:{id:{type:"string"},lwt:{type:"number"}},required:["id","lwt"],additionalProperties:!1}},{"./plugins/utils":12,"./rx-error":46}],51:[function(e,t,r){"use strict";var n=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(r,"__esModule",{value:!0}),r.RxSchema=void 0,r.createRxSchema=function(e,t,r=!0){r&&(0,s.runPluginHooks)("preCreateRxSchema",e);var n=(0,c.fillWithDefaultSettings)(e);n=(0,c.normalizeRxJsonSchema)(n),l.overwritable.deepFreezeWhenDevMode(n);var o=new f(n,t);return(0,s.runPluginHooks)("createRxSchema",o),o},r.getIndexes=p,r.getPreviousVersions=function(e){var t=e.version?e.version:0,r=0;return new Array(t).fill(0).map((()=>r++))},r.isRxSchema=function(e){return e instanceof f},r.toTypedRxJsonSchema=function(e){return e};var o=n(e("@babel/runtime/helpers/createClass")),i=e("./plugins/utils"),a=e("./rx-error"),s=e("./hooks"),u=e("./rx-document"),c=e("./rx-schema-helper"),l=e("./overwritable"),f=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=p(this.jsonSchema),this.primaryPath=(0,c.getPrimaryFieldOfPrimaryKey)(this.jsonSchema.primaryKey),this.finalFields=(0,c.getFinalFields)(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!(0,i.deepEqual)(e[r],t[r]))throw(0,a.newRxError)("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={};return(0,u.defineGetterSetter)(this,e,""),(0,i.overwriteGetterForCaching)(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return(0,c.getComposedPrimaryKeyOfDocumentData)(this.jsonSchema,e)},(0,o.default)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((([,e])=>e.hasOwnProperty("default"))).forEach((([t,r])=>e[t]=r.default)),(0,i.overwriteGetterForCaching)(this,"defaultValues",e)}},{key:"hash",get:function(){return(0,i.overwriteGetterForCaching)(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function p(e){return(e.indexes||[]).map((e=>(0,i.isMaybeReadonlyArray)(e)?e:[e]))}r.RxSchema=f},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-document":45,"./rx-error":46,"./rx-schema-helper":50,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":61}],52:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME=r.INTERNAL_STORAGE_NAME=void 0,r.attachmentWriteDataToNormalData=c,r.categorizeBulkWriteRows=function(e,t,r,n,i){var u,c=!!e.schema.attachments,p=[],d=[],h={},b=[],v={id:(0,a.randomCouchString)(10),events:[],checkpoint:null,context:i},m=[],y=[],g=[],_=(0,a.now)(),O="function"==typeof r.get;return n.forEach((n=>{var i,w=n.document[t],j=O?r.get(w):r[w];if(j){var x=j._rev;if(!n.previous||n.previous&&x!==n.previous._rev){var S={isError:!0,status:409,documentId:w,writeRow:n,documentInDb:j};return void(h[w]=S)}var E=c?s(n):n;c&&(n.document._deleted?n.previous&&Object.keys(n.previous._attachments).forEach((e=>{y.push({documentId:w,attachmentId:e})})):(Object.entries(n.document._attachments).find((([e,t])=>((n.previous?n.previous._attachments[e]:void 0)||t.data||(i={documentId:w,documentInDb:j,isError:!0,status:510,writeRow:n,attachmentId:e}),!0))),i||Object.entries(n.document._attachments).forEach((([e,t])=>{var r=n.previous?n.previous._attachments[e]:void 0;if(r){var o=E.document._attachments[e].digest;t.data&&r.digest!==o&&g.push({documentId:w,attachmentId:e,attachmentData:t})}else m.push({documentId:w,attachmentId:e,attachmentData:t})})))),i?h[w]=i:(d.push(E),(!u||u.document._meta.lwt{t.data?m.push({documentId:w,attachmentId:e,attachmentData:t}):(i={documentId:w,isError:!0,status:510,writeRow:n,attachmentId:e},h[w]=i)})),i||(c?p.push(s(n)):p.push(n),(!u||u.document._meta.lwt{return u=t,(c=(0,a.flatClone)(u.document))._meta=(0,a.flatClone)(c._meta),n.overwritable.isDevMode()&&(c=(0,i.fillPrimaryKey)(s,r,c),u.previous,u.previous&&Object.keys(u.previous._meta).forEach((e=>{if(!u.document._meta.hasOwnProperty(e))throw(0,o.newRxError)("SNH",{dataBefore:u.previous,dataAfter:u.document})}))),c._meta.lwt=(0,a.now)(),c._rev=(0,a.createRevision)(e.token,u.previous),{document:c,previous:u.previous};var u,c}));return e.lockedRun((()=>t.bulkWrite(l,c))).then((r=>{var n=Object.values(r.error).filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,a.ensureNotFalsy)(e.documentInDb)._deleted)));if(n.length>0){var o={error:(0,a.flatClone)(r.error),success:(0,a.flatClone)(r.success)},i=n.map((t=>(delete o.error[t.documentId],{previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:(0,a.createRevision)(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(i,c))).then((e=>(o.error=Object.assign(o.error,e.error),o.success=Object.assign(o.success,e.success),o)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,n)=>e.lockedRun((()=>t.findDocumentsById(r,n))),getAttachmentData:(r,n)=>e.lockedRun((()=>t.getAttachmentData(r,n))),getChangedDocumentsSince:(r,n)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,a.ensureNotFalsy)(r),n))),cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(u),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(u),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=Object.assign({},e.output.documentData,{_meta:(0,a.getDefaultRxDocumentMeta)(),_rev:(0,a.getDefaultRevision)(),_attachments:{}}),n=(0,a.flatClone)(r);return delete n._meta,delete n._rev,delete n._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:n}})}};return e.storageInstances.add(u),u},r.hasEncryption=p,r.stackCheckpoints=function(e){return Object.assign({},...e)},r.storageChangeEventToRxChangeEvent=function(e,t,r){var o=t.documentData,i=t.previousDocumentData;return{eventId:t.eventId,documentId:t.documentId,collectionName:r?r.name:void 0,startTime:t.startTime,endTime:t.endTime,isLocal:e,operation:t.operation,documentData:n.overwritable.deepFreezeWhenDevMode(o),previousDocumentData:n.overwritable.deepFreezeWhenDevMode(i)}},r.stripAttachmentsDataFromDocument=l,r.stripAttachmentsDataFromRow=s,r.throwIfIsStorageWriteError=function(e,t,r,n){if(n)throw 409===n.status?(0,o.newRxError)("CONFLICT",{collection:e.name,id:t,writeError:n,data:r}):422===n.status?(0,o.newRxError)("VD2",{collection:e.name,id:t,writeError:n,data:r}):n},r.writeSingle=async function(e,t,r){var n=await e.bulkWrite([t],r);if(Object.keys(n.error).length>0)throw(0,a.firstPropertyValueOfObject)(n.error);return(0,a.firstPropertyValueOfObject)(n.success)};var n=e("./overwritable"),o=e("./rx-error"),i=e("./rx-schema-helper"),a=e("./plugins/utils");r.INTERNAL_STORAGE_NAME="_rxdb_internal";function s(e){return{previous:e.previous,document:l(e.document)}}function u(e){return atob(e).length}function c(e){var t=e.data;return t?{digest:(0,a.defaultHashSha256)(t),length:u(t),type:e.type}:e}function l(e){var t=(0,a.flatClone)(e);return t._attachments={},Object.entries(e._attachments).forEach((([e,r])=>{t._attachments[e]=c(r)})),t}function f(e,t,r){var n=r.document[t],o=[!!r.previous,r.previous&&r.previous._deleted,!!r.document._deleted].map((e=>e?"1":"0")).join("");return e.databaseName+"|"+e.collectionName+"|"+n+"||"+o+"|"+r.document._rev}function p(e){return!!(e.encrypted&&e.encrypted.length>0||e.attachments&&e.attachments.encrypted)}r.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME="rxdatabase_storage_local"},{"./overwritable":9,"./plugins/utils":12,"./rx-error":46,"./rx-schema-helper":50}],53:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.BROADCAST_CHANNEL_BY_TOKEN=void 0,r.addRxStorageMultiInstanceSupport=function(e,t,r,i){if(!t.multiInstance)return;var a=i||s(t.databaseInstanceToken,r.databaseName,r),c=new n.Subject,l=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&c.next(r.eventBulk)};a.addEventListener("message",l);var f=r.changeStream(),p=!1,d=f.subscribe((r=>{p||a.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return c.asObservable().pipe((0,o.mergeWith)(f))};var h=r.close.bind(r);r.close=async function(){return p=!0,d.unsubscribe(),a.removeEventListener("message",l),i||await u(t.databaseInstanceToken,r),h()};var b=r.remove.bind(r);r.remove=async function(){return p=!0,d.unsubscribe(),a.removeEventListener("message",l),i||await u(t.databaseInstanceToken,r),b()}},r.getBroadcastChannelReference=s,r.removeBroadcastChannelReference=u;var n=e("rxjs"),o=e("rxjs/operators"),i=e("broadcast-channel"),a=new Map;function s(e,t,r){var n=a.get(e);return n||(n={bc:new i.BroadcastChannel("RxDB:"+t),refs:new Set},a.set(e,n)),n.refs.add(r),n.bc}function u(e,t){var r=a.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(a.delete(e),r.bc.close()):void 0}r.BROADCAST_CHANNEL_BY_TOKEN=a},{"broadcast-channel":91,rxjs:450,"rxjs/operators":675}],54:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RxStorageDefaultStatics=void 0;var n=e("./rx-error"),o=e("./query-planner"),i={prepareQuery(e,t){if(!t.sort)throw(0,n.newRxError)("SNH",{query:t});return{query:t,queryPlan:(0,o.getQueryPlan)(e,t)}},checkpointSchema:e("./rx-schema-helper").DEFAULT_CHECKPOINT_SCHEMA};r.RxStorageDefaultStatics=i},{"./query-planner":31,"./rx-error":46,"./rx-schema-helper":50}],55:[function(e,t,r){"use strict";e("./noConflict");var n,o=(n=e("core-js/library/fn/global"))&&n.__esModule?n:{default:n};o.default._babelPolyfill&&"undefined"!=typeof console&&console.warn&&console.warn("@babel/polyfill is loaded more than once on this page. This is probably not desirable/intended and may have consequences if different versions of the polyfills are applied sequentially. If you do need to load the polyfill more than once, use @babel/polyfill/noConflict instead to bypass the warning."),o.default._babelPolyfill=!0},{"./noConflict":56,"core-js/library/fn/global":116}],56:[function(e,t,r){"use strict";e("core-js/es6"),e("core-js/fn/array/includes"),e("core-js/fn/array/flat-map"),e("core-js/fn/string/pad-start"),e("core-js/fn/string/pad-end"),e("core-js/fn/string/trim-start"),e("core-js/fn/string/trim-end"),e("core-js/fn/symbol/async-iterator"),e("core-js/fn/object/get-own-property-descriptors"),e("core-js/fn/object/values"),e("core-js/fn/object/entries"),e("core-js/fn/promise/finally"),e("core-js/web"),e("regenerator-runtime/runtime")},{"core-js/es6":104,"core-js/fn/array/flat-map":105,"core-js/fn/array/includes":106,"core-js/fn/object/entries":107,"core-js/fn/object/get-own-property-descriptors":108,"core-js/fn/object/values":109,"core-js/fn/promise/finally":110,"core-js/fn/string/pad-end":111,"core-js/fn/string/pad-start":112,"core-js/fn/string/trim-end":113,"core-js/fn/string/trim-start":114,"core-js/fn/symbol/async-iterator":115,"core-js/web":407,"regenerator-runtime/runtime":449}],57:[function(e,t,r){var n=e("./setPrototypeOf.js"),o=e("./isNativeReflectConstruct.js");function i(e,r,a){return o()?(t.exports=i=Reflect.construct.bind(),t.exports.__esModule=!0,t.exports.default=t.exports):(t.exports=i=function(e,t,r){var o=[null];o.push.apply(o,t);var i=new(Function.bind.apply(e,o));return r&&n(i,r.prototype),i},t.exports.__esModule=!0,t.exports.default=t.exports),i.apply(null,arguments)}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},{"./isNativeReflectConstruct.js":63,"./setPrototypeOf.js":64}],58:[function(e,t,r){var n=e("./toPropertyKey.js");function o(e,t){for(var r=0;r>1)],t)<=0?s=u+1:a=u-1;r(o,t)<=0&&u++;return i.splice(u,0,t),[i,u]}},{}],70:[function(e,t,r){"use strict";r.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},r.toByteArray=function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,f=s>0?a-4:a;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},r.fromByteArray=function(e){for(var t,r=e.length,o=r%3,i=[],a=16383,s=0,u=r-o;su?u:s+a));1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var o,i,a=[],s=t;s>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],71:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AbstractNode=void 0;const n=e("./util"),o=e("./find-similar-node");r.AbstractNode=class{constructor(e,t,r){this.level=e,this.id=(0,n.nextNodeId)(),this.deleted=!1,this.type=r,this.rootNode=t,t&&this.rootNode.addNode(this)}isEqualToOtherNode(e,t=this.toString()){return t===e.toString()}remove(){if(this.ensureNotDeleted("remove"),this.isInternalNode()){if(this.parents.size>0)throw new Error("cannot remove node with parents "+this.id)}if(this.branches){const e=this;e.branches.areBranchesStrictEqual()?e.branches.getBranch("0").parents.remove(e):(e.branches.getBranch("0").parents.remove(e),e.branches.getBranch("1").parents.remove(e))}this.deleted=!0,this.rootNode.removeNode(this)}toJSON(e=!1){const t={id:e?this.id:void 0,deleted:e?this.deleted:void 0,type:this.type,level:this.level};if(e&&this.parents&&(t.parents=this.parents.toString()),this.isLeafNode()&&(t.value=this.asLeafNode().value),this.branches&&!this.branches.deleted){const r=this.branches;t.branches={0:r.getBranch("0").toJSON(e),1:r.getBranch("1").toJSON(e)}}return t}toString(){let e="<"+this.type+":"+this.level;if(this.branches){const t=this.branches;e+="|0:"+t.getBranch("0"),e+="|1:"+t.getBranch("1")}return this.isLeafNode()&&(e+="|v:"+this.asLeafNode().value),e+=">",e}isRootNode(){return"RootNode"===this.type}isInternalNode(){return"InternalNode"===this.type}isLeafNode(){return"LeafNode"===this.type}asRootNode(){if(!this.isRootNode())throw new Error("ouch");return this}asInternalNode(){if(!this.isInternalNode())throw new Error("ouch");return this}asLeafNode(){if(!this.isLeafNode())throw new Error("ouch");return this}ensureNotDeleted(e="unknown"){if(this.deleted)throw new Error("forbidden operation "+e+" on deleted node "+this.id)}log(){console.log(JSON.stringify(this.toJSON(!0),null,2))}applyEliminationRule(e){this.ensureNotDeleted("applyEliminationRule"),e||(e=this.rootNode.getNodesOfLevel(this.level));const t=(0,o.findSimilarNode)(this,e);if(t){const e=this.parents.getAll(),r=[];return e.forEach((e=>{const n=e.branches.getKeyOfNode(this);e.branches.setBranch(n,t),e.branches.areBranchesStrictEqual()&&r.push(e),this.parents.remove(e)})),r.forEach((e=>{e.isInternalNode()&&e.applyReductionRule()})),!0}return!1}}},{"./find-similar-node":76,"./util":89}],72:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ensureNodesNotStrictEqual=r.Branches=void 0;r.Branches=class{constructor(e){this.node=e,this.deleted=!1,this.branches={}}setBranch(e,t){this.branches[e]!==t&&(this.branches[e]=t,t.parents.add(this.node))}getKeyOfNode(e){if(this.getBranch("0")===e)return"0";if(this.getBranch("1")===e)return"1";throw new Error("none matched")}getBranch(e){return this.branches[e]}getBothBranches(){return[this.getBranch("0"),this.getBranch("1")]}hasBranchAsNode(e){return this.getBranch("0")===e||this.getBranch("1")===e}hasNodeIdAsBranch(e){return this.getBranch("0").id===e||this.getBranch("1").id===e}areBranchesStrictEqual(){return this.branches[0]===this.branches[1]}hasEqualBranches(){return JSON.stringify(this.branches[0])===JSON.stringify(this.branches[1])}},r.ensureNodesNotStrictEqual=function(e,t){if(e===t)throw new Error("cannot have two strict equal branches")}},{}],73:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createBddFromTruthTable=void 0;const n=e("./root-node"),o=e("./util"),i=e("./internal-node"),a=e("./leaf-node");r.createBddFromTruthTable=function(e){const t=new n.RootNode,r=e.keys().next().value.length,s=Math.pow(2,r);if(e.size!==s)throw new Error("truth table has missing entries");for(const[r,n]of e){let e=t;for(let n=0;n{const n=e.getNodesOfLevel(t);n.forEach((e=>{o.set(e.id,e)})),r=r.concat(n)}));const i=n(e);if(r.length!==i.size){const e=r.map((e=>e.id)).sort(),t=Array.from(i).map((e=>e.id)).sort().filter((t=>!e.includes(t)));if(i.size>r.length){const e=t[0],n=r.find((t=>!!t.isInternalNode()&&t.branches.hasNodeIdAsBranch(e)));console.log("referenceToFirst:"),null==n||n.log()}throw new Error("ensureCorrectBdd() nodes in list not equal size to recursive nodes allNodes: "+r.length+" recursiveNodes: "+i.size+" nodesOnlyInRecursive: "+t.join(", ")+" ")}if(r.forEach((e=>{if(e.isRootNode())return;const t=e;if(e.deleted)throw new Error("ensureCorrectBdd() bdd includes a deleted node");if(0===t.parents.size)throw new Error("ensureCorrectBdd() node has no parent "+t.id);if(t.isInternalNode()){const e=t,r=e.branches.getBothBranches();if(e.branches.areBranchesStrictEqual())throw new Error("ensureCorrectBdd() node has two equal branches: "+r.map((e=>e.id)).join(", "));r.forEach((t=>{if(!t.parents.has(e))throw new Error("ensureCorrectBdd() branch must have the node as parent")}))}t.parents.getAll().forEach((e=>{if(!e.branches.hasBranchAsNode(t))throw new Error("ensureCorrectBdd() parent node does not have child as branch")}))})),t.includes('"deleted":true'))throw new Error("ensureCorrectBdd() bdd includes a deleted node")},r.getNodesRecursive=n},{}],75:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.fillTruthTable=void 0;const n=e("./util");r.fillTruthTable=function(e,t,r){const o=(0,n.maxBinaryWithLength)(t);let i=(0,n.minBinaryWithLength)(t),a=!1;for(;!a;)e.has(i)||e.set(i,r),i===o?a=!0:i=(0,n.getNextStateSet)(i)}},{"./util":89}],76:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.findSimilarNode=void 0,r.findSimilarNode=function(e,t){const r=e.toString();for(let n=0;n{const r=t.branches.getKeyOfNode(this);t.branches.setBranch(r,e),this.parents.remove(t),t.branches.areBranchesStrictEqual()&&t.isInternalNode()&&t.applyReductionRule()})),!0}return!1}}r.InternalNode=a},{"./abstract-node":71,"./branches":72,"./parents":87}],79:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.LeafNode=void 0;const n=e("./parents"),o=e("./abstract-node"),i=e("./util");class a extends o.AbstractNode{constructor(e,t,r,o){super(e,t,"LeafNode"),this.value=r,this.parents=new n.Parents(this),this.parents.add(o)}removeIfValueEquals(e){if(this.ensureNotDeleted(),this.value!==e)return!1;return this.parents.getAll().forEach((e=>{const t=e.branches.getKeyOfNode(this),r=e.branches.getBranch((0,i.oppositeBoolean)(t));this.parents.remove(e),e.branches.setBranch(t,r),e.isInternalNode()&&e.applyReductionRule()})),!0}}r.LeafNode=a},{"./abstract-node":71,"./parents":87,"./util":89}],80:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.nodeToString=r.bddToMinimalString=void 0;const n=e("./string-format"),o=e("./string-format");function i(e,t,r){const o=(0,n.getNextCharId)(r);switch(e.type){case"LeafNode":const r=(0,n.getCharOfValue)(e.asLeafNode().value);return{id:o.char,nextCode:o.nextCode,str:o.char+r};case"InternalNode":const i=t.get(e.asInternalNode().branches.getBranch("0")),a=t.get(e.asInternalNode().branches.getBranch("1"));return{id:o.char,nextCode:o.nextCode,str:o.char+i+a+(0,n.getCharOfLevel)(e.level)};case"RootNode":const s=t.get(e.asRootNode().branches.getBranch("0")),u=t.get(e.asRootNode().branches.getBranch("1"));return{id:o.char,nextCode:o.nextCode,str:""+s+u+(0,n.getCharOfLevel)(e.level)};default:throw new Error("unknown node type")}}r.bddToMinimalString=function(e){let t="",r=o.FIRST_CHAR_CODE_FOR_ID;const n=e.getLeafNodes().length;if(n>99)throw new Error("cannot build string with too many leaf nodes");t+=n.toString().padStart(2,"0");const a=e.levels.slice().reverse(),s=new Map;return a.forEach((n=>{e.getNodesOfLevel(n).forEach((e=>{const n=i(e,s,r);r=n.nextCode,s.set(e,n.id),t+=n.str}))})),t},r.nodeToString=i},{"./string-format":85}],81:[function(e,t,r){"use strict";function n(e){const t=e.branches.getBranch("0"),r=e.branches.getBranch("1");return{l:e.level,0:t.isLeafNode()?t.asLeafNode().value:n(t),1:r.isLeafNode()?r.asLeafNode().value:n(r)}}Object.defineProperty(r,"__esModule",{value:!0}),r.nodeToSimpleBddNode=r.bddToSimpleBdd=void 0,r.bddToSimpleBdd=function(e){return n(e)},r.nodeToSimpleBddNode=n},{}],82:[function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),o(e("./bdd-to-minimal-string"),r),o(e("./minimal-string-to-simple-bdd"),r),o(e("./resolve-with-simple-bdd"),r),o(e("./string-format"),r),o(e("./bdd-to-simple-bdd"),r)},{"./bdd-to-minimal-string":80,"./bdd-to-simple-bdd":81,"./minimal-string-to-simple-bdd":83,"./resolve-with-simple-bdd":84,"./string-format":85}],83:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.minimalStringToSimpleBdd=void 0;const n=e("../util"),o=e("./string-format");r.minimalStringToSimpleBdd=function(e){const t=new Map,r=2+2*parseInt(e.charAt(0)+e.charAt(1),10),i=e.substring(2,r),a=(0,n.splitStringToChunks)(i,2);for(let e=0;e=128&&e<=160&&(e=161),{char:String.fromCharCode(e),nextCode:e+1}}},{}],86:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getArrayWithIndexes=r.changeKeyOrder=r.shuffleBooleanOrdering=r.optimizeBruteForce=r.defaultCompareResults=void 0;const n=e("./create-bdd-from-truth-table"),o=e("./util");function i(e){const t=s((0,o.firstKeyOfMap)(e).length),r=(0,o.shuffleArray)(t),n={},i={};r.forEach(((e,t)=>{n[t]=e,i[e]=t}));const u=new Map;for(const[t,r]of e.entries()){const e=a(t,n);u.set(e,r)}return{newTable:u,mapping:n,mappingBeforeToAfter:i}}function a(e,t){return e.split("").map(((e,r)=>({char:e,indexBefore:r,indexAfter:t[r]}))).sort(((e,t)=>e.indexAfter-t.indexAfter)).map((e=>e.char)).join("")}function s(e){const t=[];let r=0;for(;rnull),compareResults:s=r.defaultCompareResults,afterBddCreation:u=(()=>null),log:c=!1}){const l=(0,n.createBddFromTruthTable)(e);u(l),l.minimize();let f={truthTable:e,bdd:l};c&&(l.log(),console.log("initial nodes amount: "+l.countNodes()));let p=0;for(;pe!==d)).forEach((e=>{const n=t.mappingBeforeToAfter[e];h.push(n);const o=new Set;l.set(n,o),r.getNodesOfLevel(e).forEach((e=>{e.level=n,o.add(e)}))}));const b=new Set;r.getNodesOfLevel(d).forEach((e=>b.add(e))),l.set(d,b),h.push(d),r.nodesByLevel=l,r.levels=h,u(r),r.minimize(),c&&(console.log("got new bdd with nodes amount of "+r.countNodes()),console.dir(t.mappingBeforeToAfter));const v=await s(f.bdd,r);if("RootNode"!==v.type)throw new Error("compareResults did not return a bdd");v===r&&(c&&(console.log("#".repeat(50)),console.log("found better bdd "+r.countNodes())),f={bdd:r,truthTable:t.newTable},a(f))}return f},r.shuffleBooleanOrdering=i,r.changeKeyOrder=a,r.getArrayWithIndexes=s},{"./create-bdd-from-truth-table":73,"./util":89}],87:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Parents=void 0;r.Parents=class{constructor(e){this.node=e,this.parents=new Set}remove(e){this.parents.delete(e),0===this.parents.size&&this.node.remove()}getAll(){return Array.from(this.parents)}add(e){if(this.node.level===e.level)throw new Error("a node cannot be parent of a node with the same level");this.parents.add(e)}has(e){return this.parents.has(e)}toString(){const e=[];for(const t of this.parents)e.push(t.id);return e.join(", ")}get size(){return this.parents.size}}},{}],88:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RootNode=void 0;const n=e("./abstract-node"),o=e("./branches"),i=e("./util"),a=e("./minimal-string");class s extends n.AbstractNode{constructor(){super(0,null,"RootNode"),this.branches=new o.Branches(this),this.levels=[],this.nodesByLevel=new Map,this.levels.push(0);const e=new Set;e.add(this),this.nodesByLevel.set(0,e)}addNode(e){const t=e.level;this.levels.includes(t)||this.levels.push(t),this.ensureLevelSetExists(t);const r=this.nodesByLevel.get(t);null==r||r.add(e)}removeNode(e){const t=this.nodesByLevel.get(e.level);if(!t.has(e))throw new Error("removed non-existing node "+e.id);t.delete(e)}ensureLevelSetExists(e){this.nodesByLevel.has(e)||this.nodesByLevel.set(e,new Set)}getLevels(){return Array.from(this.levels).sort(((e,t)=>e-t))}getNodesOfLevel(e){this.ensureLevelSetExists(e);const t=this.nodesByLevel.get(e);return Array.from(t)}countNodes(){let e=0;return this.getLevels().forEach((t=>{const r=this.getNodesOfLevel(t).length;e+=r})),e}minimize(e=!1){let t=!1;for(;!t;){e&&console.log("minimize() itterate once");let r=0,n=(0,i.lastOfArray)(this.getLevels());for(;n>0;){const t=this.getNodesOfLevel(n);e&&console.log("minimize() run for level "+n+" with "+t.length+" nodes");let o=0;for(const n of t){if(o++,e&&o%4e3==0&&console.log("minimize() node #"+n.id),n.isLeafNode()){n.asLeafNode().applyEliminationRule()&&r++}if(!n.deleted&&n.isInternalNode()){const e=n,o=e.applyReductionRule();let i=!1;e.deleted||(i=e.applyEliminationRule(t)),(o||i)&&r++}}n--}0===r?t=!0:e&&console.log("minimize() itteration done with "+r+" minimisations")}}getLeafNodes(){const e=(0,i.lastOfArray)(this.getLevels());return this.getNodesOfLevel(e).reverse()}removeIrrelevantLeafNodes(e){let t=!1;for(;!t;){let r=0;const n=this.getLeafNodes();for(const t of n){t.removeIfValueEquals(e)&&r++}this.minimize(),0===r&&(t=!0)}}resolve(e,t){let r=this;for(;;){const n=e[r.level](t),o=(0,i.booleanToBooleanString)(n);if(r=r.branches.getBranch(o),r.isLeafNode())return r.asLeafNode().value}}toSimpleBdd(){return(0,a.bddToSimpleBdd)(this)}}r.RootNode=s},{"./abstract-node":71,"./branches":72,"./minimal-string":82,"./util":89}],89:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.splitStringToChunks=r.lastOfArray=r.shuffleArray=r.firstKeyOfMap=r.getNextStateSet=r.maxBinaryWithLength=r.minBinaryWithLength=r.binaryToDecimal=r.oppositeBinary=r.decimalToPaddedBinary=r.nextNodeId=r.lastChar=r.oppositeBoolean=r.booleanToBooleanString=r.booleanStringToBoolean=void 0,r.booleanStringToBoolean=function(e){return"1"===e},r.booleanToBooleanString=function(e){return e?"1":"0"},r.oppositeBoolean=function(e){return"1"===e?"0":"1"},r.lastChar=function(e){return e.slice(-1)};const n=function(e=6){let t="";const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length;for(let o=0;o>>0).toString(2).padStart(t,"0")}function a(e){return parseInt(e,2)}r.nextNodeId=function(){const e="node_"+n+"_"+o;return o++,e},r.decimalToPaddedBinary=i,r.oppositeBinary=function(e){if("1"===e)return"0";if("0"===e)return"1";throw new Error("non-binary given")},r.binaryToDecimal=a,r.minBinaryWithLength=function(e){return new Array(e).fill(0).map((()=>"0")).join("")},r.maxBinaryWithLength=function(e){return new Array(e).fill(0).map((()=>"1")).join("")},r.getNextStateSet=function(e){return i(a(e)+1,e.length)},r.firstKeyOfMap=function(e){return e.keys().next().value},r.shuffleArray=function(e){for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e},r.lastOfArray=function(e){return e[e.length-1]},r.splitStringToChunks=function(e,t){const r=[];for(let n=0,o=e.length;n0||e._addEL.internal.length>0}function p(e,t,r){e._addEL[t].push(r),function(e){if(!e._iL&&f(e)){var t=function(t){e._addEL[t.type].forEach((function(e){var r=1e5,n=e.time-r;t.time>=n&&e.fn(t.data)}))},r=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,r)})):(e._iL=!0,e.method.onMessage(e._state,t,r))}}(e)}function d(e,t,r){e._addEL[t]=e._addEL[t].filter((function(e){return e!==r})),function(e){if(e._iL&&!f(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}r.BroadcastChannel=c,c._pubkey=!0,c.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(e));return l(this,"message",e)},postInternal:function(e){return l(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};d(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,p(this,"message",t)):this._onML=null},addEventListener:function(e,t){p(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){d(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){a.delete(this),this.closed=!0;var t=this._prepP?this._prepP:n.PROMISE_RESOLVED_VOID;return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}}},{"./method-chooser.js":96,"./options.js":101,"./util.js":102}],91:[function(e,t,r){"use strict";var n=e("./index.js");t.exports={BroadcastChannel:n.BroadcastChannel,createLeaderElection:n.createLeaderElection,clearNodeFolder:n.clearNodeFolder,enforceOptions:n.enforceOptions,beLeader:n.beLeader}},{"./index.js":92}],92:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"BroadcastChannel",{enumerable:!0,get:function(){return n.BroadcastChannel}}),Object.defineProperty(r,"OPEN_BROADCAST_CHANNELS",{enumerable:!0,get:function(){return n.OPEN_BROADCAST_CHANNELS}}),Object.defineProperty(r,"beLeader",{enumerable:!0,get:function(){return i.beLeader}}),Object.defineProperty(r,"clearNodeFolder",{enumerable:!0,get:function(){return n.clearNodeFolder}}),Object.defineProperty(r,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}}),Object.defineProperty(r,"enforceOptions",{enumerable:!0,get:function(){return n.enforceOptions}});var n=e("./broadcast-channel.js"),o=e("./leader-election.js"),i=e("./leader-election-util.js")},{"./broadcast-channel.js":90,"./leader-election-util.js":93,"./leader-election.js":95}],93:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.beLeader=function(e){e.isLeader=!0,e._hasLeader=!0;var t=(0,n.add)((function(){return e.die()}));e._unl.push(t);var r=function(t){"leader"===t.context&&"apply"===t.action&&o(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),o(e,"tell"))};return e.broadcastChannel.addEventListener("internal",r),e._lstns.push(r),o(e,"tell")},r.sendLeaderMessage=o;var n=e("unload");function o(e,t){var r={context:"leader",action:t,token:e.token};return e.broadcastChannel.postInternal(r)}},{unload:677}],94:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.LeaderElectionWebLock=void 0;var n=e("./util.js"),o=e("./leader-election-util.js"),i=function(e,t){var r=this;this.broadcastChannel=e,e._befC.push((function(){return r.die()})),this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,n.randomToken)(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=!1,this._wKMC={},this.lN="pubkey-bc||"+e.method.type+"||"+e.name};r.LeaderElectionWebLock=i,i.prototype={hasLeader:function(){var e=this;return navigator.locks.query().then((function(t){var r=t.held?t.held.filter((function(t){return t.name===e.lN})):[];return!!(r&&r.length>0)}))},awaitLeadership:function(){var e=this;if(!this._wLMP){this._wKMC.c=new AbortController;var t=new Promise((function(t,r){e._wKMC.res=t,e._wKMC.rej=r}));this._wLMP=new Promise((function(r){navigator.locks.request(e.lN,{signal:e._wKMC.c.signal},(function(){return e._wKMC.c=void 0,(0,o.beLeader)(e),r(),t})).catch((function(){}))}))}return this._wLMP},set onduplicate(e){},die:function(){var e=this,t=(0,o.sendLeaderMessage)(this,"death");return this._lstns.forEach((function(t){return e.broadcastChannel.removeEventListener("internal",t)})),this._lstns=[],this._unl.forEach((function(e){return e.remove()})),this._unl=[],this.isLeader&&(this.isLeader=!1),this.isDead=!0,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort("LeaderElectionWebLock.die() called"),t}}},{"./leader-election-util.js":93,"./util.js":102}],95:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e||(e={});e=JSON.parse(JSON.stringify(e)),e.fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var r=(0,n.supportsWebLockAPI)()?new i.LeaderElectionWebLock(e,t):new a(e,t);return e._befC.push((function(){return r.die()})),e._leaderElector=r,r};var n=e("./util.js"),o=e("./leader-election-util.js"),i=e("./leader-election-web-lock.js"),a=function(e,t){var r=this;this.broadcastChannel=e,this._options=t,this.isLeader=!1,this._hasLeader=!1,this.isDead=!1,this.token=(0,n.randomToken)(),this._aplQ=n.PROMISE_RESOLVED_VOID,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=!1;var o=function(e){"leader"===e.context&&("death"===e.action&&(r._hasLeader=!1),"tell"===e.action&&(r._hasLeader=!0))};this.broadcastChannel.addEventListener("internal",o),this._lstns.push(o)};a.prototype={hasLeader:function(){return Promise.resolve(this._hasLeader)},applyOnce:function(e){var t=this;if(this.isLeader)return(0,n.sleep)(0,!0);if(this.isDead)return(0,n.sleep)(0,!1);if(this._aplQC>1)return this._aplQ;return this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then((function(){return function(){if(t.isLeader)return n.PROMISE_RESOLVED_TRUE;var r,i=!1,a=new Promise((function(e){r=function(){i=!0,e()}})),s=function(e){"leader"===e.context&&e.token!=t.token&&("apply"===e.action&&e.token>t.token&&r(),"tell"===e.action&&(r(),t._hasLeader=!0))};t.broadcastChannel.addEventListener("internal",s);var u=e?4*t._options.responseTime:t._options.responseTime;return(0,o.sendLeaderMessage)(t,"apply").then((function(){return Promise.race([(0,n.sleep)(u),a.then((function(){return Promise.reject(new Error)}))])})).then((function(){return(0,o.sendLeaderMessage)(t,"apply")})).then((function(){return Promise.race([(0,n.sleep)(u),a.then((function(){return Promise.reject(new Error)}))])})).catch((function(){})).then((function(){return t.broadcastChannel.removeEventListener("internal",s),!i&&(0,o.beLeader)(t).then((function(){return!0}))}))}()})).then((function(){t._aplQC=t._aplQC-1})),this._aplQ.then((function(){return t.isLeader}))},awaitLeadership:function(){return this._aLP||(this._aLP=function(e){if(e.isLeader)return n.PROMISE_RESOLVED_VOID;return new Promise((function(t){var r=!1;function o(){r||(r=!0,e.broadcastChannel.removeEventListener("internal",i),t(!0))}e.applyOnce().then((function(){e.isLeader&&o()})),function t(){return(0,n.sleep)(e._options.fallbackInterval).then((function(){if(!e.isDead&&!r)return e.isLeader?void o():e.applyOnce(!0).then((function(){e.isLeader?o():t()}))}))}();var i=function(t){"leader"===t.context&&"death"===t.action&&(e._hasLeader=!1,e.applyOnce().then((function(){e.isLeader&&o()})))};e.broadcastChannel.addEventListener("internal",i),e._lstns.push(i)}))}(this)),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;return this._lstns.forEach((function(t){return e.broadcastChannel.removeEventListener("internal",t)})),this._lstns=[],this._unl.forEach((function(e){return e.remove()})),this._unl=[],this.isLeader&&(this._hasLeader=!1,this.isLeader=!1),this.isDead=!0,(0,o.sendLeaderMessage)(this,"death")}}},{"./leader-election-util.js":93,"./leader-election-web-lock.js":94,"./util.js":102}],96:[function(e,t,r){"use strict";e("@babel/runtime/helpers/typeof");Object.defineProperty(r,"__esModule",{value:!0}),r.chooseMethod=function(e){var t=[].concat(e.methods,s).filter(Boolean);if(e.type){if("simulate"===e.type)return a.SimulateMethod;var r=t.find((function(t){return t.type===e.type}));if(r)return r;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||(t=t.filter((function(e){return"idb"!==e.type})));var n=t.find((function(e){return e.canBeUsed()}));if(n)return n;throw new Error("No usable method found in "+JSON.stringify(s.map((function(e){return e.type}))))};var n=e("./methods/native.js"),o=e("./methods/indexed-db.js"),i=e("./methods/localstorage.js"),a=e("./methods/simulate.js");var s=[n.NativeMethod,o.IndexedDBMethod,i.LocalstorageMethod]},{"./methods/indexed-db.js":97,"./methods/localstorage.js":98,"./methods/native.js":99,"./methods/simulate.js":100,"@babel/runtime/helpers/typeof":67}],97:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.TRANSACTION_SETTINGS=r.IndexedDBMethod=void 0,r.averageResponseTime=S,r.canBeUsed=x,r.cleanOldMessages=m,r.close=O,r.commitIndexedDBTransaction=f,r.create=y,r.createDatabase=p,r.getAllMessages=function(e){var t=e.transaction(u,"readonly",c),r=t.objectStore(u),n=[];return new Promise((function(e){r.openCursor().onsuccess=function(r){var o=r.target.result;o?(n.push(o.value),o.continue()):(f(t),e(n))}}))},r.getIdb=l,r.getMessagesHigherThan=h,r.getOldMessages=v,r.microSeconds=void 0,r.onMessage=j,r.postMessage=w,r.removeMessagesById=b,r.type=void 0,r.writeMessage=d;var n=e("../util.js"),o=e("oblivious-set"),i=e("../options.js"),a=n.microSeconds;r.microSeconds=a;var s="pubkey.broadcast-channel-0-",u="messages",c={durability:"relaxed"};r.TRANSACTION_SETTINGS=c;function l(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function f(e){e.commit&&e.commit()}function p(e){var t=l(),r=s+e,n=t.open(r);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(u,{keyPath:"id",autoIncrement:!0})},new Promise((function(e,t){n.onerror=function(e){return t(e)},n.onsuccess=function(){e(n.result)}}))}function d(e,t,r){var n={uuid:t,time:(new Date).getTime(),data:r},o=e.transaction([u],"readwrite",c);return new Promise((function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(u).add(n),f(o)}))}function h(e,t){var r=e.transaction(u,"readonly",c),n=r.objectStore(u),o=[],i=IDBKeyRange.bound(t+1,1/0);if(n.getAll){var a=n.getAll(i);return new Promise((function(e,t){a.onerror=function(e){return t(e)},a.onsuccess=function(t){e(t.target.result)}}))}return new Promise((function(e,a){var s=function(){try{return i=IDBKeyRange.bound(t+1,1/0),n.openCursor(i)}catch(e){return n.openCursor()}}();s.onerror=function(e){return a(e)},s.onsuccess=function(n){var i=n.target.result;i?i.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return!(e.uuid===t.uuid||t.eMIs.has(e.id)||e.data.time0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0);t.idb||(t.idb={});t.idb.ttl||(t.idb.ttl=45e3);t.idb.fallbackInterval||(t.idb.fallbackInterval=150);e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose);t.localstorage||(t.localstorage={});t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4);e.methods&&(t.methods=e.methods);t.node||(t.node={});t.node.ttl||(t.node.ttl=12e4);t.node.maxParallelWrites||(t.node.maxParallelWrites=2048);void 0===t.node.useFastPath&&(t.node.useFastPath=!0);return t}},{}],102:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.PROMISE_RESOLVED_VOID=r.PROMISE_RESOLVED_TRUE=r.PROMISE_RESOLVED_FALSE=void 0,r.isPromise=function(e){return e&&"function"==typeof e.then},r.microSeconds=function(){var e=(new Date).getTime();return e===a?1e3*e+ ++s:(a=e,s=0,1e3*e)},r.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},r.randomToken=function(){return Math.random().toString(36).substring(2)},r.sleep=function(e,t){e||(e=0);return new Promise((function(r){return setTimeout((function(){return r(t)}),e)}))},r.supportsWebLockAPI=function(){return"undefined"!=typeof navigator&&void 0!==navigator.locks&&"function"==typeof navigator.locks.request};var n=Promise.resolve(!1);r.PROMISE_RESOLVED_FALSE=n;var o=Promise.resolve(!0);r.PROMISE_RESOLVED_TRUE=o;var i=Promise.resolve();r.PROMISE_RESOLVED_VOID=i;var a=0,s=0},{}],103:[function(e,t,r){(function(t){(function(){ /*! * The buffer module from node.js, for the browser. * diff --git a/dist/types/custom-index.d.ts b/dist/types/custom-index.d.ts index df0b3ad76c3..7caeee413f7 100644 --- a/dist/types/custom-index.d.ts +++ b/dist/types/custom-index.d.ts @@ -24,6 +24,8 @@ export declare function getIndexMeta(schema: RxJsonSchema(schema: RxJsonSchema>, index: string[]): (docData: RxDocumentData) => string; declare type ParsedLengths = { + minimum: number; + maximum: number; nonDecimals: number; decimals: number; roundedMinimum: number; diff --git a/dist/types/plugins/utils/utils-array.d.ts b/dist/types/plugins/utils/utils-array.d.ts index 28650092a3f..6bbd2c83021 100644 --- a/dist/types/plugins/utils/utils-array.d.ts +++ b/dist/types/plugins/utils/utils-array.d.ts @@ -30,3 +30,4 @@ export declare function asyncFilter(array: T[], predicate: (item: T, index: n * @link https://stackoverflow.com/a/3762735 */ export declare function sumNumberArray(array: number[]): number; +export declare function maxOfNumbers(arr: number[]): number; diff --git a/dist/types/plugins/utils/utils-rxdb-version.d.ts b/dist/types/plugins/utils/utils-rxdb-version.d.ts index 7e2aa38e40a..890d7b4bc68 100644 --- a/dist/types/plugins/utils/utils-rxdb-version.d.ts +++ b/dist/types/plugins/utils/utils-rxdb-version.d.ts @@ -1,4 +1,4 @@ /** * This file is replaced in the 'npm run build:version' script. */ -export declare const RXDB_VERSION = "14.5.2"; +export declare const RXDB_VERSION = "14.6.0"; diff --git a/docs/index.html b/docs/index.html index aa4cd1de433..96bdde54363 100644 --- a/docs/index.html +++ b/docs/index.html @@ -82,7 +82,10 @@ -